blob: c6564d666b24aa1300cc639662d2f17e5cbacaf6 [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"
Richard Trieue7f7ed22017-02-22 01:11:25 +000029#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/Type.h"
32#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/UnresolvedSet.h"
34#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000035#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "clang/Basic/FileSystemOptions.h"
39#include "clang/Basic/LangOptions.h"
40#include "clang/Basic/ObjCRuntime.h"
41#include "clang/Basic/OperatorKinds.h"
42#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Basic/TargetInfo.h"
47#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "clang/Basic/Version.h"
50#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000051#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "clang/Lex/HeaderSearch.h"
53#include "clang/Lex/HeaderSearchOptions.h"
54#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000055#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include "clang/Lex/PreprocessingRecord.h"
57#include "clang/Lex/Preprocessor.h"
58#include "clang/Lex/PreprocessorOptions.h"
59#include "clang/Sema/Scope.h"
60#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000061#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000062#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000063#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000064#include "clang/Serialization/ModuleManager.h"
65#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include "llvm/ADT/APFloat.h"
67#include "llvm/ADT/APInt.h"
68#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000069#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000070#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000071#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000072#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000073#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000074#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000075#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000076#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000077#include "llvm/Support/ErrorHandling.h"
78#include "llvm/Support/FileSystem.h"
79#include "llvm/Support/MemoryBuffer.h"
80#include "llvm/Support/Path.h"
81#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000082#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include <cassert>
85#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000086#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000087#include <cstring>
88#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000089#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000090#include <limits>
91#include <map>
92#include <memory>
93#include <new>
94#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000095#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000096#include <tuple>
97#include <utility>
98#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000099
100using namespace clang;
101using namespace clang::serialization;
102using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000103using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000104
Ben Langmuircb69b572014-03-07 06:40:32 +0000105//===----------------------------------------------------------------------===//
106// ChainedASTReaderListener implementation
107//===----------------------------------------------------------------------===//
108
109bool
110ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
111 return First->ReadFullVersionInformation(FullVersion) ||
112 Second->ReadFullVersionInformation(FullVersion);
113}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000114
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000115void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
116 First->ReadModuleName(ModuleName);
117 Second->ReadModuleName(ModuleName);
118}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000119
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000120void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
121 First->ReadModuleMapFile(ModuleMapPath);
122 Second->ReadModuleMapFile(ModuleMapPath);
123}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000125bool
126ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
127 bool Complain,
128 bool AllowCompatibleDifferences) {
129 return First->ReadLanguageOptions(LangOpts, Complain,
130 AllowCompatibleDifferences) ||
131 Second->ReadLanguageOptions(LangOpts, Complain,
132 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000133}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000134
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000135bool ChainedASTReaderListener::ReadTargetOptions(
136 const TargetOptions &TargetOpts, bool Complain,
137 bool AllowCompatibleDifferences) {
138 return First->ReadTargetOptions(TargetOpts, Complain,
139 AllowCompatibleDifferences) ||
140 Second->ReadTargetOptions(TargetOpts, Complain,
141 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000142}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000143
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000145 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000146 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
147 Second->ReadDiagnosticOptions(DiagOpts, Complain);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuircb69b572014-03-07 06:40:32 +0000150bool
151ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
152 bool Complain) {
153 return First->ReadFileSystemOptions(FSOpts, Complain) ||
154 Second->ReadFileSystemOptions(FSOpts, Complain);
155}
156
157bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000158 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
159 bool Complain) {
160 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
161 Complain) ||
162 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
163 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000165
Ben Langmuircb69b572014-03-07 06:40:32 +0000166bool ChainedASTReaderListener::ReadPreprocessorOptions(
167 const PreprocessorOptions &PPOpts, bool Complain,
168 std::string &SuggestedPredefines) {
169 return First->ReadPreprocessorOptions(PPOpts, Complain,
170 SuggestedPredefines) ||
171 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
172}
173void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
174 unsigned Value) {
175 First->ReadCounter(M, Value);
176 Second->ReadCounter(M, Value);
177}
178bool ChainedASTReaderListener::needsInputFileVisitation() {
179 return First->needsInputFileVisitation() ||
180 Second->needsInputFileVisitation();
181}
182bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
183 return First->needsSystemInputFileVisitation() ||
184 Second->needsSystemInputFileVisitation();
185}
Richard Smith216a3bd2015-08-13 17:57:10 +0000186void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
187 ModuleKind Kind) {
188 First->visitModuleFile(Filename, Kind);
189 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000190}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000191
Ben Langmuircb69b572014-03-07 06:40:32 +0000192bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000193 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000194 bool isOverridden,
195 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000196 bool Continue = false;
197 if (First->needsInputFileVisitation() &&
198 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000199 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
200 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000201 if (Second->needsInputFileVisitation() &&
202 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000203 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
204 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000205 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000206}
207
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000208void ChainedASTReaderListener::readModuleFileExtension(
209 const ModuleFileExtensionMetadata &Metadata) {
210 First->readModuleFileExtension(Metadata);
211 Second->readModuleFileExtension(Metadata);
212}
213
Guy Benyei11169dd2012-12-18 14:30:41 +0000214//===----------------------------------------------------------------------===//
215// PCH validator implementation
216//===----------------------------------------------------------------------===//
217
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000218ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000219
220/// \brief Compare the given set of language options against an existing set of
221/// language options.
222///
223/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000224/// \param AllowCompatibleDifferences If true, differences between compatible
225/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000226///
227/// \returns true if the languagae options mis-match, false otherwise.
228static bool checkLanguageOptions(const LangOptions &LangOpts,
229 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000230 DiagnosticsEngine *Diags,
231 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000232#define LANGOPT(Name, Bits, Default, Description) \
233 if (ExistingLangOpts.Name != LangOpts.Name) { \
234 if (Diags) \
235 Diags->Report(diag::err_pch_langopt_mismatch) \
236 << Description << LangOpts.Name << ExistingLangOpts.Name; \
237 return true; \
238 }
239
240#define VALUE_LANGOPT(Name, Bits, Default, Description) \
241 if (ExistingLangOpts.Name != LangOpts.Name) { \
242 if (Diags) \
243 Diags->Report(diag::err_pch_langopt_value_mismatch) \
244 << Description; \
245 return true; \
246 }
247
248#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
249 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
250 if (Diags) \
251 Diags->Report(diag::err_pch_langopt_value_mismatch) \
252 << Description; \
253 return true; \
254 }
255
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000256#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
257 if (!AllowCompatibleDifferences) \
258 LANGOPT(Name, Bits, Default, Description)
259
260#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
261 if (!AllowCompatibleDifferences) \
262 ENUM_LANGOPT(Name, Bits, Default, Description)
263
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000264#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
265 if (!AllowCompatibleDifferences) \
266 VALUE_LANGOPT(Name, Bits, Default, Description)
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#define BENIGN_LANGOPT(Name, Bits, Default, Description)
269#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000270#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#include "clang/Basic/LangOptions.def"
272
Ben Langmuircd98cb72015-06-23 18:20:18 +0000273 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
274 if (Diags)
275 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
276 return true;
277 }
278
Guy Benyei11169dd2012-12-18 14:30:41 +0000279 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
280 if (Diags)
281 Diags->Report(diag::err_pch_langopt_value_mismatch)
282 << "target Objective-C runtime";
283 return true;
284 }
285
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000286 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
287 LangOpts.CommentOpts.BlockCommandNames) {
288 if (Diags)
289 Diags->Report(diag::err_pch_langopt_value_mismatch)
290 << "block command names";
291 return true;
292 }
293
Guy Benyei11169dd2012-12-18 14:30:41 +0000294 return false;
295}
296
297/// \brief Compare the given set of target options against an existing set of
298/// target options.
299///
300/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
301///
302/// \returns true if the target options mis-match, false otherwise.
303static bool checkTargetOptions(const TargetOptions &TargetOpts,
304 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000305 DiagnosticsEngine *Diags,
306 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define CHECK_TARGET_OPT(Field, Name) \
308 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
309 if (Diags) \
310 Diags->Report(diag::err_pch_targetopt_mismatch) \
311 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
312 return true; \
313 }
314
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000315 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000318
319 // We can tolerate different CPUs in many cases, notably when one CPU
320 // supports a strict superset of another. When allowing compatible
321 // differences skip this check.
322 if (!AllowCompatibleDifferences)
323 CHECK_TARGET_OPT(CPU, "target CPU");
324
Guy Benyei11169dd2012-12-18 14:30:41 +0000325#undef CHECK_TARGET_OPT
326
327 // Compare feature sets.
328 SmallVector<StringRef, 4> ExistingFeatures(
329 ExistingTargetOpts.FeaturesAsWritten.begin(),
330 ExistingTargetOpts.FeaturesAsWritten.end());
331 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
332 TargetOpts.FeaturesAsWritten.end());
333 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
334 std::sort(ReadFeatures.begin(), ReadFeatures.end());
335
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000336 // We compute the set difference in both directions explicitly so that we can
337 // diagnose the differences differently.
338 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
339 std::set_difference(
340 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
341 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
342 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
343 ExistingFeatures.begin(), ExistingFeatures.end(),
344 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000345
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000346 // If we are allowing compatible differences and the read feature set is
347 // a strict subset of the existing feature set, there is nothing to diagnose.
348 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
349 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000350
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000351 if (Diags) {
352 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000353 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000354 << /* is-existing-feature */ false << Feature;
355 for (StringRef Feature : UnmatchedExistingFeatures)
356 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
357 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000358 }
359
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000360 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000361}
362
363bool
364PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000365 bool Complain,
366 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 const LangOptions &ExistingLangOpts = PP.getLangOpts();
368 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000369 Complain ? &Reader.Diags : nullptr,
370 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000371}
372
373bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000374 bool Complain,
375 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000376 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
377 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000378 Complain ? &Reader.Diags : nullptr,
379 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000380}
381
382namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000383
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
385 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000386 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
387 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000388
389} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000390
Ben Langmuirb92de022014-04-29 16:25:26 +0000391static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
392 DiagnosticsEngine &Diags,
393 bool Complain) {
394 typedef DiagnosticsEngine::Level Level;
395
396 // Check current mappings for new -Werror mappings, and the stored mappings
397 // for cases that were explicitly mapped to *not* be errors that are now
398 // errors because of options like -Werror.
399 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
400
401 for (DiagnosticsEngine *MappingSource : MappingSources) {
402 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
403 diag::kind DiagID = DiagIDMappingPair.first;
404 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
405 if (CurLevel < DiagnosticsEngine::Error)
406 continue; // not significant
407 Level StoredLevel =
408 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
409 if (StoredLevel < DiagnosticsEngine::Error) {
410 if (Complain)
411 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
412 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
413 return true;
414 }
415 }
416 }
417
418 return false;
419}
420
Alp Tokerac4e8e52014-06-22 21:58:33 +0000421static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
422 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
423 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
424 return true;
425 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000426}
427
428static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
429 DiagnosticsEngine &Diags,
430 bool IsSystem, bool Complain) {
431 // Top-level options
432 if (IsSystem) {
433 if (Diags.getSuppressSystemWarnings())
434 return false;
435 // If -Wsystem-headers was not enabled before, be conservative
436 if (StoredDiags.getSuppressSystemWarnings()) {
437 if (Complain)
438 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
439 return true;
440 }
441 }
442
443 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
444 if (Complain)
445 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
446 return true;
447 }
448
449 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
450 !StoredDiags.getEnableAllWarnings()) {
451 if (Complain)
452 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
453 return true;
454 }
455
456 if (isExtHandlingFromDiagsError(Diags) &&
457 !isExtHandlingFromDiagsError(StoredDiags)) {
458 if (Complain)
459 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
460 return true;
461 }
462
463 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
464}
465
466bool PCHValidator::ReadDiagnosticOptions(
467 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
468 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
469 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
470 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000471 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000472 // This should never fail, because we would have processed these options
473 // before writing them to an ASTFile.
474 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
475
476 ModuleManager &ModuleMgr = Reader.getModuleManager();
477 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
478
479 // If the original import came from a file explicitly generated by the user,
480 // don't check the diagnostic mappings.
481 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000482 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000483 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
484 // the transitive closure of its imports, since unrelated modules cannot be
485 // imported until after this module finishes validation.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000486 ModuleFile *TopImport = &*ModuleMgr.rbegin();
Ben Langmuirb92de022014-04-29 16:25:26 +0000487 while (!TopImport->ImportedBy.empty())
488 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000489 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000490 return false;
491
492 StringRef ModuleName = TopImport->ModuleName;
493 assert(!ModuleName.empty() && "diagnostic options read before module name");
494
495 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
496 assert(M && "missing module");
497
498 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
499 // contains the union of their flags.
500 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
501}
502
Guy Benyei11169dd2012-12-18 14:30:41 +0000503/// \brief Collect the macro definitions provided by the given preprocessor
504/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000505static void
506collectMacroDefinitions(const PreprocessorOptions &PPOpts,
507 MacroDefinitionsMap &Macros,
508 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
510 StringRef Macro = PPOpts.Macros[I].first;
511 bool IsUndef = PPOpts.Macros[I].second;
512
513 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
514 StringRef MacroName = MacroPair.first;
515 StringRef MacroBody = MacroPair.second;
516
517 // For an #undef'd macro, we only care about the name.
518 if (IsUndef) {
519 if (MacroNames && !Macros.count(MacroName))
520 MacroNames->push_back(MacroName);
521
522 Macros[MacroName] = std::make_pair("", true);
523 continue;
524 }
525
526 // For a #define'd macro, figure out the actual definition.
527 if (MacroName.size() == Macro.size())
528 MacroBody = "1";
529 else {
530 // Note: GCC drops anything following an end-of-line character.
531 StringRef::size_type End = MacroBody.find_first_of("\n\r");
532 MacroBody = MacroBody.substr(0, End);
533 }
534
535 if (MacroNames && !Macros.count(MacroName))
536 MacroNames->push_back(MacroName);
537 Macros[MacroName] = std::make_pair(MacroBody, false);
538 }
539}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000540
Guy Benyei11169dd2012-12-18 14:30:41 +0000541/// \brief Check the preprocessor options deserialized from the control block
542/// against the preprocessor options in an existing preprocessor.
543///
544/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000545/// \param Validate If true, validate preprocessor options. If false, allow
546/// macros defined by \p ExistingPPOpts to override those defined by
547/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000548static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
549 const PreprocessorOptions &ExistingPPOpts,
550 DiagnosticsEngine *Diags,
551 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000552 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000553 const LangOptions &LangOpts,
554 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Check macro definitions.
556 MacroDefinitionsMap ASTFileMacros;
557 collectMacroDefinitions(PPOpts, ASTFileMacros);
558 MacroDefinitionsMap ExistingMacros;
559 SmallVector<StringRef, 4> ExistingMacroNames;
560 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
561
562 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
563 // Dig out the macro definition in the existing preprocessor options.
564 StringRef MacroName = ExistingMacroNames[I];
565 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
566
567 // Check whether we know anything about this macro name or not.
568 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
569 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000570 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000571 // FIXME: Check whether this identifier was referenced anywhere in the
572 // AST file. If so, we should reject the AST file. Unfortunately, this
573 // information isn't in the control block. What shall we do about it?
574
575 if (Existing.second) {
576 SuggestedPredefines += "#undef ";
577 SuggestedPredefines += MacroName.str();
578 SuggestedPredefines += '\n';
579 } else {
580 SuggestedPredefines += "#define ";
581 SuggestedPredefines += MacroName.str();
582 SuggestedPredefines += ' ';
583 SuggestedPredefines += Existing.first.str();
584 SuggestedPredefines += '\n';
585 }
586 continue;
587 }
588
589 // If the macro was defined in one but undef'd in the other, we have a
590 // conflict.
591 if (Existing.second != Known->second.second) {
592 if (Diags) {
593 Diags->Report(diag::err_pch_macro_def_undef)
594 << MacroName << Known->second.second;
595 }
596 return true;
597 }
598
599 // If the macro was #undef'd in both, or if the macro bodies are identical,
600 // it's fine.
601 if (Existing.second || Existing.first == Known->second.first)
602 continue;
603
604 // The macro bodies differ; complain.
605 if (Diags) {
606 Diags->Report(diag::err_pch_macro_def_conflict)
607 << MacroName << Known->second.first << Existing.first;
608 }
609 return true;
610 }
611
612 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000613 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000614 if (Diags) {
615 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
616 }
617 return true;
618 }
619
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000620 // Detailed record is important since it is used for the module cache hash.
621 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000622 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000623 if (Diags) {
624 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
625 }
626 return true;
627 }
628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 // Compute the #include and #include_macros lines we need.
630 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
631 StringRef File = ExistingPPOpts.Includes[I];
632 if (File == ExistingPPOpts.ImplicitPCHInclude)
633 continue;
634
635 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
636 != PPOpts.Includes.end())
637 continue;
638
639 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000640 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 SuggestedPredefines += "\"\n";
642 }
643
644 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
645 StringRef File = ExistingPPOpts.MacroIncludes[I];
646 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
647 File)
648 != PPOpts.MacroIncludes.end())
649 continue;
650
651 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000652 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 SuggestedPredefines += "\"\n##\n";
654 }
655
656 return false;
657}
658
659bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
660 bool Complain,
661 std::string &SuggestedPredefines) {
662 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
663
664 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000665 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000667 SuggestedPredefines,
668 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000669}
670
Yaxun Liu43712e02016-09-07 18:40:20 +0000671bool SimpleASTReaderListener::ReadPreprocessorOptions(
672 const PreprocessorOptions &PPOpts,
673 bool Complain,
674 std::string &SuggestedPredefines) {
675 return checkPreprocessorOptions(PPOpts,
676 PP.getPreprocessorOpts(),
677 nullptr,
678 PP.getFileManager(),
679 SuggestedPredefines,
680 PP.getLangOpts(),
681 false);
682}
683
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000684/// Check the header search options deserialized from the control block
685/// against the header search options in an existing preprocessor.
686///
687/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
688static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
689 StringRef SpecificModuleCachePath,
690 StringRef ExistingModuleCachePath,
691 DiagnosticsEngine *Diags,
692 const LangOptions &LangOpts) {
693 if (LangOpts.Modules) {
694 if (SpecificModuleCachePath != ExistingModuleCachePath) {
695 if (Diags)
696 Diags->Report(diag::err_pch_modulecache_mismatch)
697 << SpecificModuleCachePath << ExistingModuleCachePath;
698 return true;
699 }
700 }
701
702 return false;
703}
704
705bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
706 StringRef SpecificModuleCachePath,
707 bool Complain) {
708 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
709 PP.getHeaderSearchInfo().getModuleCachePath(),
710 Complain ? &Reader.Diags : nullptr,
711 PP.getLangOpts());
712}
713
Guy Benyei11169dd2012-12-18 14:30:41 +0000714void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
715 PP.setCounterValue(Value);
716}
717
718//===----------------------------------------------------------------------===//
719// AST reader implementation
720//===----------------------------------------------------------------------===//
721
Nico Weber824285e2014-05-08 04:26:47 +0000722void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
723 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000725 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000726}
727
Guy Benyei11169dd2012-12-18 14:30:41 +0000728unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
729 return serialization::ComputeHash(Sel);
730}
731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732std::pair<unsigned, unsigned>
733ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000734 using namespace llvm::support;
735 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
736 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 return std::make_pair(KeyLen, DataLen);
738}
739
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000740ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000741ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000742 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000744 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
745 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
746 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 if (N == 0)
748 return SelTable.getNullarySelector(FirstII);
749 else if (N == 1)
750 return SelTable.getUnarySelector(FirstII);
751
752 SmallVector<IdentifierInfo *, 16> Args;
753 Args.push_back(FirstII);
754 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000755 Args.push_back(Reader.getLocalIdentifier(
756 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000757
758 return SelTable.getSelector(N, Args.data());
759}
760
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000761ASTSelectorLookupTrait::data_type
762ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000764 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000765
766 data_type Result;
767
Justin Bogner57ba0b22014-03-28 22:03:24 +0000768 Result.ID = Reader.getGlobalSelectorID(
769 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000770 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
772 Result.InstanceBits = FullInstanceBits & 0x3;
773 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
774 Result.FactoryBits = FullFactoryBits & 0x3;
775 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
776 unsigned NumInstanceMethods = FullInstanceBits >> 3;
777 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000778
779 // Load instance methods
780 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000781 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
782 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000783 Result.Instance.push_back(Method);
784 }
785
786 // Load factory methods
787 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000788 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
789 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 Result.Factory.push_back(Method);
791 }
792
793 return Result;
794}
795
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000796unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
797 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000798}
799
800std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000801ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000802 using namespace llvm::support;
803 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
804 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 return std::make_pair(KeyLen, DataLen);
806}
807
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000808ASTIdentifierLookupTraitBase::internal_key_type
809ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000811 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000812}
813
Douglas Gregordcf25082013-02-11 18:16:18 +0000814/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000815static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
816 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000817 return II.hadMacroDefinition() ||
818 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000819 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000820 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000821 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
822 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000823}
824
Richard Smith76c2f2c2015-07-17 20:09:43 +0000825static bool readBit(unsigned &Bits) {
826 bool Value = Bits & 0x1;
827 Bits >>= 1;
828 return Value;
829}
830
Richard Smith79bf9202015-08-24 03:33:22 +0000831IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
832 using namespace llvm::support;
833 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
834 return Reader.getGlobalIdentifierID(F, RawID >> 1);
835}
836
Richard Smitheb4b58f62016-02-05 01:40:54 +0000837static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
838 if (!II.isFromAST()) {
839 II.setIsFromAST();
840 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
841 if (isInterestingIdentifier(Reader, II, IsModule))
842 II.setChangedSinceDeserialization();
843 }
844}
845
Guy Benyei11169dd2012-12-18 14:30:41 +0000846IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
847 const unsigned char* d,
848 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000849 using namespace llvm::support;
850 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 bool IsInteresting = RawID & 0x01;
852
853 // Wipe out the "is interesting" bit.
854 RawID = RawID >> 1;
855
Richard Smith76c2f2c2015-07-17 20:09:43 +0000856 // Build the IdentifierInfo and link the identifier ID with it.
857 IdentifierInfo *II = KnownII;
858 if (!II) {
859 II = &Reader.getIdentifierTable().getOwn(k);
860 KnownII = II;
861 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000862 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000863 Reader.markIdentifierUpToDate(II);
864
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
866 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000867 // For uninteresting identifiers, there's nothing else to do. Just notify
868 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 return II;
871 }
872
Justin Bogner57ba0b22014-03-28 22:03:24 +0000873 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
874 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000875 bool CPlusPlusOperatorKeyword = readBit(Bits);
876 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000877 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000878 bool Poisoned = readBit(Bits);
879 bool ExtensionToken = readBit(Bits);
880 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000881
882 assert(Bits == 0 && "Extra bits in the identifier?");
883 DataLen -= 8;
884
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 // Set or check the various bits in the IdentifierInfo structure.
886 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000887 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000888 II->revertTokenIDToIdentifier();
889 if (!F.isModule())
890 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
891 else if (HasRevertedBuiltin && II->getBuiltinID()) {
892 II->revertBuiltin();
893 assert((II->hasRevertedBuiltin() ||
894 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
895 "Incorrect ObjC keyword or builtin ID");
896 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 assert(II->isExtensionToken() == ExtensionToken &&
898 "Incorrect extension token flag");
899 (void)ExtensionToken;
900 if (Poisoned)
901 II->setIsPoisoned(true);
902 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
903 "Incorrect C++ operator keyword flag");
904 (void)CPlusPlusOperatorKeyword;
905
906 // If this identifier is a macro, deserialize the macro
907 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000908 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 uint32_t MacroDirectivesOffset =
910 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000911 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000912
Richard Smithd7329392015-04-21 21:46:32 +0000913 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 }
915
916 Reader.SetIdentifierInfo(ID, II);
917
918 // Read all of the declarations visible at global scope with this
919 // name.
920 if (DataLen > 0) {
921 SmallVector<uint32_t, 4> DeclIDs;
922 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 DeclIDs.push_back(Reader.getGlobalDeclID(
924 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 Reader.SetGloballyVisibleDecls(II, DeclIDs);
926 }
927
928 return II;
929}
930
Richard Smitha06c7e62015-08-26 23:55:49 +0000931DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
932 : Kind(Name.getNameKind()) {
933 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000935 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 break;
937 case DeclarationName::ObjCZeroArgSelector:
938 case DeclarationName::ObjCOneArgSelector:
939 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000940 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 break;
942 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 Data = Name.getCXXOverloadedOperator();
944 break;
945 case DeclarationName::CXXLiteralOperatorName:
946 Data = (uint64_t)Name.getCXXLiteralIdentifier();
947 break;
Richard Smith35845152017-02-07 01:37:30 +0000948 case DeclarationName::CXXDeductionGuideName:
949 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
950 ->getDeclName().getAsIdentifierInfo();
951 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 case DeclarationName::CXXConstructorName:
953 case DeclarationName::CXXDestructorName:
954 case DeclarationName::CXXConversionFunctionName:
955 case DeclarationName::CXXUsingDirective:
956 Data = 0;
957 break;
958 }
959}
960
961unsigned DeclarationNameKey::getHash() const {
962 llvm::FoldingSetNodeID ID;
963 ID.AddInteger(Kind);
964
965 switch (Kind) {
966 case DeclarationName::Identifier:
967 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000968 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000969 ID.AddString(((IdentifierInfo*)Data)->getName());
970 break;
971 case DeclarationName::ObjCZeroArgSelector:
972 case DeclarationName::ObjCOneArgSelector:
973 case DeclarationName::ObjCMultiArgSelector:
974 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
975 break;
976 case DeclarationName::CXXOperatorName:
977 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 break;
979 case DeclarationName::CXXConstructorName:
980 case DeclarationName::CXXDestructorName:
981 case DeclarationName::CXXConversionFunctionName:
982 case DeclarationName::CXXUsingDirective:
983 break;
984 }
985
986 return ID.ComputeHash();
987}
988
Richard Smithd88a7f12015-09-01 20:35:42 +0000989ModuleFile *
990ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
991 using namespace llvm::support;
992 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
993 return Reader.getLocalModuleFile(F, ModuleFileID);
994}
995
Guy Benyei11169dd2012-12-18 14:30:41 +0000996std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000997ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000998 using namespace llvm::support;
999 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1000 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 return std::make_pair(KeyLen, DataLen);
1002}
1003
Richard Smitha06c7e62015-08-26 23:55:49 +00001004ASTDeclContextNameLookupTrait::internal_key_type
1005ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001006 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001007
Richard Smitha06c7e62015-08-26 23:55:49 +00001008 auto Kind = (DeclarationName::NameKind)*d++;
1009 uint64_t Data;
1010 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001012 case DeclarationName::CXXLiteralOperatorName:
1013 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001014 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001015 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::ObjCZeroArgSelector:
1018 case DeclarationName::ObjCOneArgSelector:
1019 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001021 (uint64_t)Reader.getLocalSelector(
1022 F, endian::readNext<uint32_t, little, unaligned>(
1023 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 break;
1025 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001026 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 case DeclarationName::CXXConstructorName:
1029 case DeclarationName::CXXDestructorName:
1030 case DeclarationName::CXXConversionFunctionName:
1031 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 break;
1034 }
1035
Richard Smitha06c7e62015-08-26 23:55:49 +00001036 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001037}
1038
Richard Smithd88a7f12015-09-01 20:35:42 +00001039void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1040 const unsigned char *d,
1041 unsigned DataLen,
1042 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001043 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001044 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1045 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1046 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
Richard Smith0f4e2c42015-08-06 04:23:48 +00001050bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1051 BitstreamCursor &Cursor,
1052 uint64_t Offset,
1053 DeclContext *DC) {
1054 assert(Offset != 0);
1055
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001057 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058
Richard Smith0f4e2c42015-08-06 04:23:48 +00001059 RecordData Record;
1060 StringRef Blob;
1061 unsigned Code = Cursor.ReadCode();
1062 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1063 if (RecCode != DECL_CONTEXT_LEXICAL) {
1064 Error("Expected lexical block");
1065 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 }
1067
Richard Smith82f8fcd2015-08-06 22:07:25 +00001068 assert(!isa<TranslationUnitDecl>(DC) &&
1069 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001070 // If we are handling a C++ class template instantiation, we can see multiple
1071 // lexical updates for the same record. It's important that we select only one
1072 // of them, so that field numbering works properly. Just pick the first one we
1073 // see.
1074 auto &Lex = LexicalDecls[DC];
1075 if (!Lex.first) {
1076 Lex = std::make_pair(
1077 &M, llvm::makeArrayRef(
1078 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1079 Blob.data()),
1080 Blob.size() / 4));
1081 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001082 DC->setHasExternalLexicalStorage(true);
1083 return false;
1084}
Guy Benyei11169dd2012-12-18 14:30:41 +00001085
Richard Smith0f4e2c42015-08-06 04:23:48 +00001086bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1087 BitstreamCursor &Cursor,
1088 uint64_t Offset,
1089 DeclID ID) {
1090 assert(Offset != 0);
1091
1092 SavedStreamPosition SavedPosition(Cursor);
1093 Cursor.JumpToBit(Offset);
1094
1095 RecordData Record;
1096 StringRef Blob;
1097 unsigned Code = Cursor.ReadCode();
1098 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1099 if (RecCode != DECL_CONTEXT_VISIBLE) {
1100 Error("Expected visible lookup table block");
1101 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 }
1103
Richard Smith0f4e2c42015-08-06 04:23:48 +00001104 // We can't safely determine the primary context yet, so delay attaching the
1105 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001106 auto *Data = (const unsigned char*)Blob.data();
1107 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 return false;
1109}
1110
Richard Smith37a93df2017-02-18 00:32:02 +00001111void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001113 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1114 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001115 Diag(diag::note_module_cache_path)
1116 << PP.getHeaderSearchInfo().getModuleCachePath();
1117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001118}
1119
1120void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001121 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 if (Diags.isDiagnosticInFlight())
1123 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1124 else
1125 Diag(DiagID) << Arg1 << Arg2;
1126}
1127
1128//===----------------------------------------------------------------------===//
1129// Source Manager Deserialization
1130//===----------------------------------------------------------------------===//
1131
1132/// \brief Read the line table in the source manager block.
1133/// \returns true if there was an error.
1134bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001135 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 unsigned Idx = 0;
1137 LineTableInfo &LineTable = SourceMgr.getLineTable();
1138
1139 // Parse the file names
1140 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001141 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001143 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1145 }
Richard Smith63078492015-09-01 07:41:55 +00001146 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001147
1148 // Parse the line entries
1149 std::vector<LineEntry> Entries;
1150 while (Idx < Record.size()) {
1151 int FID = Record[Idx++];
1152 assert(FID >= 0 && "Serialized line entries for non-local file.");
1153 // Remap FileID from 1-based old view.
1154 FID += F.SLocEntryBaseID - 1;
1155
1156 // Extract the line entries
1157 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001158 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 Entries.clear();
1160 Entries.reserve(NumEntries);
1161 for (unsigned I = 0; I != NumEntries; ++I) {
1162 unsigned FileOffset = Record[Idx++];
1163 unsigned LineNo = Record[Idx++];
1164 int FilenameID = FileIDs[Record[Idx++]];
1165 SrcMgr::CharacteristicKind FileKind
1166 = (SrcMgr::CharacteristicKind)Record[Idx++];
1167 unsigned IncludeOffset = Record[Idx++];
1168 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1169 FileKind, IncludeOffset));
1170 }
1171 LineTable.AddEntry(FileID::get(FID), Entries);
1172 }
1173
1174 return false;
1175}
1176
1177/// \brief Read a source manager block
1178bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1179 using namespace SrcMgr;
1180
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001181 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001182
1183 // Set the source-location entry cursor to the current position in
1184 // the stream. This cursor will be used to read the contents of the
1185 // source manager block initially, and then lazily read
1186 // source-location entries as needed.
1187 SLocEntryCursor = F.Stream;
1188
1189 // The stream itself is going to skip over the source manager block.
1190 if (F.Stream.SkipBlock()) {
1191 Error("malformed block record in AST file");
1192 return true;
1193 }
1194
1195 // Enter the source manager block.
1196 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1197 Error("malformed source manager block record in AST file");
1198 return true;
1199 }
1200
1201 RecordData Record;
1202 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001203 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001204
Chris Lattnere7b154b2013-01-19 21:39:22 +00001205 switch (E.Kind) {
1206 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1207 case llvm::BitstreamEntry::Error:
1208 Error("malformed block record in AST file");
1209 return true;
1210 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001212 case llvm::BitstreamEntry::Record:
1213 // The interesting case.
1214 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001216
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001219 StringRef Blob;
1220 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 default: // Default behavior: ignore.
1222 break;
1223
1224 case SM_SLOC_FILE_ENTRY:
1225 case SM_SLOC_BUFFER_ENTRY:
1226 case SM_SLOC_EXPANSION_ENTRY:
1227 // Once we hit one of the source location entries, we're done.
1228 return false;
1229 }
1230 }
1231}
1232
1233/// \brief If a header file is not found at the path that we expect it to be
1234/// and the PCH file was moved from its original location, try to resolve the
1235/// file by assuming that header+PCH were moved together and the header is in
1236/// the same place relative to the PCH.
1237static std::string
1238resolveFileRelativeToOriginalDir(const std::string &Filename,
1239 const std::string &OriginalDir,
1240 const std::string &CurrDir) {
1241 assert(OriginalDir != CurrDir &&
1242 "No point trying to resolve the file if the PCH dir didn't change");
1243 using namespace llvm::sys;
1244 SmallString<128> filePath(Filename);
1245 fs::make_absolute(filePath);
1246 assert(path::is_absolute(OriginalDir));
1247 SmallString<128> currPCHPath(CurrDir);
1248
1249 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1250 fileDirE = path::end(path::parent_path(filePath));
1251 path::const_iterator origDirI = path::begin(OriginalDir),
1252 origDirE = path::end(OriginalDir);
1253 // Skip the common path components from filePath and OriginalDir.
1254 while (fileDirI != fileDirE && origDirI != origDirE &&
1255 *fileDirI == *origDirI) {
1256 ++fileDirI;
1257 ++origDirI;
1258 }
1259 for (; origDirI != origDirE; ++origDirI)
1260 path::append(currPCHPath, "..");
1261 path::append(currPCHPath, fileDirI, fileDirE);
1262 path::append(currPCHPath, path::filename(Filename));
1263 return currPCHPath.str();
1264}
1265
1266bool ASTReader::ReadSLocEntry(int ID) {
1267 if (ID == 0)
1268 return false;
1269
1270 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1271 Error("source location entry ID out-of-range for AST file");
1272 return true;
1273 }
1274
Richard Smithaada85c2016-02-06 02:06:43 +00001275 // Local helper to read the (possibly-compressed) buffer data following the
1276 // entry record.
1277 auto ReadBuffer = [this](
1278 BitstreamCursor &SLocEntryCursor,
1279 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1280 RecordData Record;
1281 StringRef Blob;
1282 unsigned Code = SLocEntryCursor.ReadCode();
1283 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1284
1285 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001286 if (!llvm::zlib::isAvailable()) {
1287 Error("zlib is not available");
1288 return nullptr;
1289 }
Richard Smithaada85c2016-02-06 02:06:43 +00001290 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001291 if (llvm::Error E =
1292 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1293 Error("could not decompress embedded file contents: " +
1294 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001295 return nullptr;
1296 }
1297 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1298 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1299 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1300 } else {
1301 Error("AST record has invalid code");
1302 return nullptr;
1303 }
1304 };
1305
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1307 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 unsigned BaseOffset = F->SLocEntryBaseOffset;
1310
1311 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001312 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1313 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 Error("incorrectly-formatted source location entry in AST file");
1315 return true;
1316 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001317
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001319 StringRef Blob;
1320 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 default:
1322 Error("incorrectly-formatted source location entry in AST file");
1323 return true;
1324
1325 case SM_SLOC_FILE_ENTRY: {
1326 // We will detect whether a file changed and return 'Failure' for it, but
1327 // we will also try to fail gracefully by setting up the SLocEntry.
1328 unsigned InputID = Record[4];
1329 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001330 const FileEntry *File = IF.getFile();
1331 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001332
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001333 // Note that we only check if a File was returned. If it was out-of-date
1334 // we have complained but we will continue creating a FileID to recover
1335 // gracefully.
1336 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 return true;
1338
1339 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1340 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1341 // This is the module's main file.
1342 IncludeLoc = getImportLocation(F);
1343 }
1344 SrcMgr::CharacteristicKind
1345 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1346 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1347 ID, BaseOffset + Record[0]);
1348 SrcMgr::FileInfo &FileInfo =
1349 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1350 FileInfo.NumCreatedFIDs = Record[5];
1351 if (Record[3])
1352 FileInfo.setHasLineDirectives();
1353
1354 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1355 unsigned NumFileDecls = Record[7];
1356 if (NumFileDecls) {
1357 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1358 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1359 NumFileDecls));
1360 }
Richard Smithaada85c2016-02-06 02:06:43 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 const SrcMgr::ContentCache *ContentCache
1363 = SourceMgr.getOrCreateContentCache(File,
1364 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1365 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001366 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1367 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001368 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1369 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001371 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 }
1373
1374 break;
1375 }
1376
1377 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001378 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 unsigned Offset = Record[0];
1380 SrcMgr::CharacteristicKind
1381 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1382 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001383 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 IncludeLoc = getImportLocation(F);
1385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001386
Richard Smithaada85c2016-02-06 02:06:43 +00001387 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1388 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001390 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001391 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 break;
1393 }
1394
1395 case SM_SLOC_EXPANSION_ENTRY: {
1396 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1397 SourceMgr.createExpansionLoc(SpellingLoc,
1398 ReadSourceLocation(*F, Record[2]),
1399 ReadSourceLocation(*F, Record[3]),
1400 Record[4],
1401 ID,
1402 BaseOffset + Record[0]);
1403 break;
1404 }
1405 }
1406
1407 return false;
1408}
1409
1410std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1411 if (ID == 0)
1412 return std::make_pair(SourceLocation(), "");
1413
1414 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1415 Error("source location entry ID out-of-range for AST file");
1416 return std::make_pair(SourceLocation(), "");
1417 }
1418
1419 // Find which module file this entry lands in.
1420 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001421 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 return std::make_pair(SourceLocation(), "");
1423
1424 // FIXME: Can we map this down to a particular submodule? That would be
1425 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001426 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001427}
1428
1429/// \brief Find the location where the module F is imported.
1430SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1431 if (F->ImportLoc.isValid())
1432 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001433
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 // Otherwise we have a PCH. It's considered to be "imported" at the first
1435 // location of its includer.
1436 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001437 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001438 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001439 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 return F->ImportedBy[0]->FirstLoc;
1442}
1443
1444/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1445/// specified cursor. Read the abbreviations that are at the top of the block
1446/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001447bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001448 if (Cursor.EnterSubBlock(BlockID))
1449 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001450
1451 while (true) {
1452 uint64_t Offset = Cursor.GetCurrentBitNo();
1453 unsigned Code = Cursor.ReadCode();
1454
1455 // We expect all abbrevs to be at the start of the block.
1456 if (Code != llvm::bitc::DEFINE_ABBREV) {
1457 Cursor.JumpToBit(Offset);
1458 return false;
1459 }
1460 Cursor.ReadAbbrevRecord();
1461 }
1462}
1463
Richard Smithe40f2ba2013-08-07 21:41:30 +00001464Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001465 unsigned &Idx) {
1466 Token Tok;
1467 Tok.startToken();
1468 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1469 Tok.setLength(Record[Idx++]);
1470 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1471 Tok.setIdentifierInfo(II);
1472 Tok.setKind((tok::TokenKind)Record[Idx++]);
1473 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1474 return Tok;
1475}
1476
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001477MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001478 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001479
1480 // Keep track of where we are in the stream, then jump back there
1481 // after reading this macro.
1482 SavedStreamPosition SavedPosition(Stream);
1483
1484 Stream.JumpToBit(Offset);
1485 RecordData Record;
1486 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001487 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001490 // Advance to the next record, but if we get to the end of the block, don't
1491 // pop it (removing all the abbreviations from the cursor) since we want to
1492 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001493 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001494 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001495
Chris Lattnerefa77172013-01-20 00:00:22 +00001496 switch (Entry.Kind) {
1497 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1498 case llvm::BitstreamEntry::Error:
1499 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001500 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001501 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001502 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001503 case llvm::BitstreamEntry::Record:
1504 // The interesting case.
1505 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 }
1507
1508 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 Record.clear();
1510 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001511 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001513 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001514 case PP_MACRO_DIRECTIVE_HISTORY:
1515 return Macro;
1516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 case PP_MACRO_OBJECT_LIKE:
1518 case PP_MACRO_FUNCTION_LIKE: {
1519 // If we already have a macro, that means that we've hit the end
1520 // of the definition of the macro we were looking for. We're
1521 // done.
1522 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001523 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001524
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001525 unsigned NextIndex = 1; // Skip identifier ID.
1526 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001528 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001529 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001531 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1534 // Decode function-like macro info.
1535 bool isC99VarArgs = Record[NextIndex++];
1536 bool isGNUVarArgs = Record[NextIndex++];
1537 bool hasCommaPasting = Record[NextIndex++];
1538 MacroArgs.clear();
1539 unsigned NumArgs = Record[NextIndex++];
1540 for (unsigned i = 0; i != NumArgs; ++i)
1541 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1542
1543 // Install function-like macro info.
1544 MI->setIsFunctionLike();
1545 if (isC99VarArgs) MI->setIsC99Varargs();
1546 if (isGNUVarArgs) MI->setIsGNUVarargs();
1547 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001548 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 }
1550
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 // Remember that we saw this macro last so that we add the tokens that
1552 // form its body to it.
1553 Macro = MI;
1554
1555 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1556 Record[NextIndex]) {
1557 // We have a macro definition. Register the association
1558 PreprocessedEntityID
1559 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1560 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001561 PreprocessingRecord::PPEntityID PPID =
1562 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1563 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1564 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001565 if (PPDef)
1566 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001567 }
1568
1569 ++NumMacrosRead;
1570 break;
1571 }
1572
1573 case PP_TOKEN: {
1574 // If we see a TOKEN before a PP_MACRO_*, then the file is
1575 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001576 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001577
John McCallf413f5e2013-05-03 00:10:13 +00001578 unsigned Idx = 0;
1579 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 Macro->AddTokenToBody(Tok);
1581 break;
1582 }
1583 }
1584 }
1585}
1586
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001587PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001588ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1589 unsigned LocalID) const {
1590 if (!M.ModuleOffsetMap.empty())
1591 ReadModuleOffsetMap(M);
1592
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001593 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001595 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001597
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 return LocalID + I->second;
1599}
1600
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001601unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1602 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001603}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001604
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001605HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001606HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001607 internal_key_type ikey = {FE->getSize(),
1608 M.HasTimestamps ? FE->getModificationTime() : 0,
1609 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001610 return ikey;
1611}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001612
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001613bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001614 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 return false;
1616
Mehdi Amini004b9c72016-10-10 22:52:47 +00001617 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001618 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001619
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001621 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001622 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1623 if (!Key.Imported)
1624 return FileMgr.getFile(Key.Filename);
1625
1626 std::string Resolved = Key.Filename;
1627 Reader.ResolveImportedPath(M, Resolved);
1628 return FileMgr.getFile(Resolved);
1629 };
1630
1631 const FileEntry *FEA = GetFile(a);
1632 const FileEntry *FEB = GetFile(b);
1633 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001635
Guy Benyei11169dd2012-12-18 14:30:41 +00001636std::pair<unsigned, unsigned>
1637HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001638 using namespace llvm::support;
1639 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001641 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001642}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001643
1644HeaderFileInfoTrait::internal_key_type
1645HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001646 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001647 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001648 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1649 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001650 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001651 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001652 return ikey;
1653}
1654
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001655HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001656HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 unsigned DataLen) {
1658 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001659 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 HeaderFileInfo HFI;
1661 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001662 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1663 HFI.isImport |= (Flags >> 4) & 0x01;
1664 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1665 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001667 // FIXME: Find a better way to handle this. Maybe just store a
1668 // "has been included" flag?
1669 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1670 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001671 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1672 M, endian::readNext<uint32_t, little, unaligned>(d));
1673 if (unsigned FrameworkOffset =
1674 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001675 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 // since 0 is used as an indicator for "no framework name".
1677 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1678 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1679 }
Richard Smith386bb072015-08-18 23:42:23 +00001680
1681 assert((End - d) % 4 == 0 &&
1682 "Wrong data length in HeaderFileInfo deserialization");
1683 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001684 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001685 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1686 LocalSMID >>= 2;
1687
1688 // This header is part of a module. Associate it with the module to enable
1689 // implicit module import.
1690 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1691 Module *Mod = Reader.getSubmodule(GlobalSMID);
1692 FileManager &FileMgr = Reader.getFileManager();
1693 ModuleMap &ModMap =
1694 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1695
1696 std::string Filename = key.Filename;
1697 if (key.Imported)
1698 Reader.ResolveImportedPath(M, Filename);
1699 // FIXME: This is not always the right filename-as-written, but we're not
1700 // going to use this information to rebuild the module, so it doesn't make
1701 // a lot of difference.
1702 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001703 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1704 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001705 }
1706
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 // This HeaderFileInfo was externally loaded.
1708 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001709 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 return HFI;
1711}
1712
Richard Smithd7329392015-04-21 21:46:32 +00001713void ASTReader::addPendingMacro(IdentifierInfo *II,
1714 ModuleFile *M,
1715 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001716 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1717 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001718}
1719
1720void ASTReader::ReadDefinedMacros() {
1721 // Note that we are loading defined macros.
1722 Deserializing Macros(this);
1723
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001724 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1725 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001726
1727 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001728 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 continue;
1730
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001731 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001732 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001733
1734 RecordData Record;
1735 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001736 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001737
Chris Lattnere7b154b2013-01-19 21:39:22 +00001738 switch (E.Kind) {
1739 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1740 case llvm::BitstreamEntry::Error:
1741 Error("malformed block record in AST file");
1742 return;
1743 case llvm::BitstreamEntry::EndBlock:
1744 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001745
Chris Lattnere7b154b2013-01-19 21:39:22 +00001746 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001748 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 default: // Default behavior: ignore.
1750 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001751
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001753 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001754 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001755 if (II->isOutOfDate())
1756 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001757 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001758 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001759
Chris Lattnere7b154b2013-01-19 21:39:22 +00001760 case PP_TOKEN:
1761 // Ignore tokens.
1762 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 break;
1765 }
1766 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001767 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 }
1769}
1770
1771namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001772
Guy Benyei11169dd2012-12-18 14:30:41 +00001773 /// \brief Visitor class used to look up identifirs in an AST file.
1774 class IdentifierLookupVisitor {
1775 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001776 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001778 unsigned &NumIdentifierLookups;
1779 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001781
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001783 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1784 unsigned &NumIdentifierLookups,
1785 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001786 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1787 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001788 NumIdentifierLookups(NumIdentifierLookups),
1789 NumIdentifierLookupHits(NumIdentifierLookupHits),
1790 Found()
1791 {
1792 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001793
1794 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001796 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001798
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 ASTIdentifierLookupTable *IdTable
1800 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1801 if (!IdTable)
1802 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001803
1804 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001805 Found);
1806 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001807 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001808 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 if (Pos == IdTable->end())
1810 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001811
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 // Dereferencing the iterator has the effect of building the
1813 // IdentifierInfo node and populating it with the various
1814 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001815 ++NumIdentifierLookupHits;
1816 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 return true;
1818 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001819
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 // \brief Retrieve the identifier info found within the module
1821 // files.
1822 IdentifierInfo *getIdentifierInfo() const { return Found; }
1823 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001824
1825} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001826
1827void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1828 // Note that we are loading an identifier.
1829 Deserializing AnIdentifier(this);
1830
1831 unsigned PriorGeneration = 0;
1832 if (getContext().getLangOpts().Modules)
1833 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001834
1835 // If there is a global index, look there first to determine which modules
1836 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001837 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001838 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001839 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001840 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1841 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001842 }
1843 }
1844
Douglas Gregor7211ac12013-01-25 23:32:03 +00001845 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001846 NumIdentifierLookups,
1847 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001848 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 markIdentifierUpToDate(&II);
1850}
1851
1852void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1853 if (!II)
1854 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001855
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 II->setOutOfDate(false);
1857
1858 // Update the generation for this identifier.
1859 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001860 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001861}
1862
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1864 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001865 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001866
1867 BitstreamCursor &Cursor = M.MacroCursor;
1868 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001869 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001870
Richard Smith713369b2015-04-23 20:40:50 +00001871 struct ModuleMacroRecord {
1872 SubmoduleID SubModID;
1873 MacroInfo *MI;
1874 SmallVector<SubmoduleID, 8> Overrides;
1875 };
1876 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
Richard Smithd7329392015-04-21 21:46:32 +00001878 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1879 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1880 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001881 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001882 while (true) {
1883 llvm::BitstreamEntry Entry =
1884 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1885 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1886 Error("malformed block record in AST file");
1887 return;
1888 }
1889
1890 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001891 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001892 case PP_MACRO_DIRECTIVE_HISTORY:
1893 break;
1894
1895 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001896 ModuleMacros.push_back(ModuleMacroRecord());
1897 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001898 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1899 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001900 for (int I = 2, N = Record.size(); I != N; ++I)
1901 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001902 continue;
1903 }
1904
1905 default:
1906 Error("malformed block record in AST file");
1907 return;
1908 }
1909
1910 // We found the macro directive history; that's the last record
1911 // for this macro.
1912 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001913 }
1914
Richard Smithd7329392015-04-21 21:46:32 +00001915 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001916 {
1917 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001918 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001919 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001920 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001921 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001922 Module *Mod = getSubmodule(ModID);
1923 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001924 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001925 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001926 }
1927
1928 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001929 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001930 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001931 }
1932 }
1933
1934 // Don't read the directive history for a module; we don't have anywhere
1935 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001936 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001937 return;
1938
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001939 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001940 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001941 unsigned Idx = 0, N = Record.size();
1942 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001943 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001944 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1946 switch (K) {
1947 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001948 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001949 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001950 break;
1951 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001952 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001953 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001954 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001955 }
1956 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001957 bool isPublic = Record[Idx++];
1958 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1959 break;
1960 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001961
1962 if (!Latest)
1963 Latest = MD;
1964 if (Earliest)
1965 Earliest->setPrevious(MD);
1966 Earliest = MD;
1967 }
1968
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001969 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001970 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001971}
1972
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001973ASTReader::InputFileInfo
1974ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 // Go find this input file.
1976 BitstreamCursor &Cursor = F.InputFilesCursor;
1977 SavedStreamPosition SavedPosition(Cursor);
1978 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1979
1980 unsigned Code = Cursor.ReadCode();
1981 RecordData Record;
1982 StringRef Blob;
1983
1984 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1985 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1986 "invalid record type for input file");
1987 (void)Result;
1988
1989 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001990 InputFileInfo R;
1991 R.StoredSize = static_cast<off_t>(Record[1]);
1992 R.StoredTime = static_cast<time_t>(Record[2]);
1993 R.Overridden = static_cast<bool>(Record[3]);
1994 R.Transient = static_cast<bool>(Record[4]);
1995 R.Filename = Blob;
1996 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001997 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001998}
1999
Manman Renc8c94152016-10-21 23:35:03 +00002000static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002001InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 // If this ID is bogus, just return an empty input file.
2003 if (ID == 0 || ID > F.InputFilesLoaded.size())
2004 return InputFile();
2005
2006 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002007 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 return F.InputFilesLoaded[ID-1];
2009
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002010 if (F.InputFilesLoaded[ID-1].isNotFound())
2011 return InputFile();
2012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002014 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 SavedStreamPosition SavedPosition(Cursor);
2016 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002017
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002018 InputFileInfo FI = readInputFileInfo(F, ID);
2019 off_t StoredSize = FI.StoredSize;
2020 time_t StoredTime = FI.StoredTime;
2021 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002022 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002023 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002024
Richard Smitha8cfffa2015-11-26 02:04:16 +00002025 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002026
2027 // If we didn't find the file, resolve it relative to the
2028 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002029 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002030 F.OriginalDir != CurrentDir) {
2031 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2032 F.OriginalDir,
2033 CurrentDir);
2034 if (!Resolved.empty())
2035 File = FileMgr.getFile(Resolved);
2036 }
2037
2038 // For an overridden file, create a virtual file with the stored
2039 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002040 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002042
Craig Toppera13603a2014-05-22 05:54:18 +00002043 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002044 if (Complain) {
2045 std::string ErrorStr = "could not find file '";
2046 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002047 ErrorStr += "' referenced by AST file '";
2048 ErrorStr += F.FileName;
2049 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002050 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 // Record that we didn't find the file.
2053 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2054 return InputFile();
2055 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002056
Ben Langmuir198c1682014-03-07 07:27:49 +00002057 // Check if there was a request to override the contents of the file
2058 // that was part of the precompiled header. Overridding such a file
2059 // can lead to problems when lexing using the source locations from the
2060 // PCH.
2061 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002062 // FIXME: Reject if the overrides are different.
2063 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002064 if (Complain)
2065 Error(diag::err_fe_pch_file_overridden, Filename);
2066 // After emitting the diagnostic, recover by disabling the override so
2067 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002068 //
2069 // FIXME: This recovery is just as broken as the original state; there may
2070 // be another precompiled module that's using the overridden contents, or
2071 // we might be half way through parsing it. Instead, we should treat the
2072 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 SM.disableFileContentsOverride(File);
2074 // The FileEntry is a virtual file entry with the size of the contents
2075 // that would override the original contents. Set it to the original's
2076 // size/time.
2077 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2078 StoredSize, StoredTime);
2079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002080
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 bool IsOutOfDate = false;
2082
2083 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002084 if (!Overridden && //
2085 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002086 (StoredTime && StoredTime != File->getModificationTime() &&
2087 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002088 )) {
2089 if (Complain) {
2090 // Build a list of the PCH imports that got us here (in reverse).
2091 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2092 while (ImportStack.back()->ImportedBy.size() > 0)
2093 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002094
Ben Langmuir198c1682014-03-07 07:27:49 +00002095 // The top-level PCH is stale.
2096 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002097 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2098 if (DiagnosticKind == 0)
2099 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2100 else if (DiagnosticKind == 1)
2101 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2102 else
2103 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002104
Ben Langmuir198c1682014-03-07 07:27:49 +00002105 // Print the import stack.
2106 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2107 Diag(diag::note_pch_required_by)
2108 << Filename << ImportStack[0]->FileName;
2109 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002110 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002111 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002112 }
2113
Ben Langmuir198c1682014-03-07 07:27:49 +00002114 if (!Diags.isDiagnosticInFlight())
2115 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
2117
Ben Langmuir198c1682014-03-07 07:27:49 +00002118 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002120 // FIXME: If the file is overridden and we've already opened it,
2121 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002122
Richard Smitha8cfffa2015-11-26 02:04:16 +00002123 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002124
2125 // Note that we've loaded this input file.
2126 F.InputFilesLoaded[ID-1] = IF;
2127 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002128}
2129
Richard Smith7ed1bc92014-12-05 22:42:13 +00002130/// \brief If we are loading a relocatable PCH or module file, and the filename
2131/// is not an absolute path, add the system or module root to the beginning of
2132/// the file name.
2133void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2134 // Resolve relative to the base directory, if we have one.
2135 if (!M.BaseDirectory.empty())
2136 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002137}
2138
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002140 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2141 return;
2142
Richard Smith7ed1bc92014-12-05 22:42:13 +00002143 SmallString<128> Buffer;
2144 llvm::sys::path::append(Buffer, Prefix, Filename);
2145 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002146}
2147
Richard Smith0f99d6a2015-08-09 08:48:41 +00002148static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2149 switch (ARR) {
2150 case ASTReader::Failure: return true;
2151 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2152 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2153 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2154 case ASTReader::ConfigurationMismatch:
2155 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2156 case ASTReader::HadErrors: return true;
2157 case ASTReader::Success: return false;
2158 }
2159
2160 llvm_unreachable("unknown ASTReadResult");
2161}
2162
Richard Smith0516b182015-09-08 19:40:14 +00002163ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2164 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2165 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002166 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002167 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2168 return Failure;
2169
2170 // Read all of the records in the options block.
2171 RecordData Record;
2172 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002173 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002174 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002175
Richard Smith0516b182015-09-08 19:40:14 +00002176 switch (Entry.Kind) {
2177 case llvm::BitstreamEntry::Error:
2178 case llvm::BitstreamEntry::SubBlock:
2179 return Failure;
2180
2181 case llvm::BitstreamEntry::EndBlock:
2182 return Result;
2183
2184 case llvm::BitstreamEntry::Record:
2185 // The interesting case.
2186 break;
2187 }
2188
2189 // Read and process a record.
2190 Record.clear();
2191 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2192 case LANGUAGE_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2194 if (ParseLanguageOptions(Record, Complain, Listener,
2195 AllowCompatibleConfigurationMismatch))
2196 Result = ConfigurationMismatch;
2197 break;
2198 }
2199
2200 case TARGET_OPTIONS: {
2201 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2202 if (ParseTargetOptions(Record, Complain, Listener,
2203 AllowCompatibleConfigurationMismatch))
2204 Result = ConfigurationMismatch;
2205 break;
2206 }
2207
2208 case DIAGNOSTIC_OPTIONS: {
2209 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002210 if (ValidateDiagnosticOptions &&
2211 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002212 ParseDiagnosticOptions(Record, Complain, Listener))
2213 return OutOfDate;
2214 break;
2215 }
2216
2217 case FILE_SYSTEM_OPTIONS: {
2218 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2219 if (!AllowCompatibleConfigurationMismatch &&
2220 ParseFileSystemOptions(Record, Complain, Listener))
2221 Result = ConfigurationMismatch;
2222 break;
2223 }
2224
2225 case HEADER_SEARCH_OPTIONS: {
2226 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2227 if (!AllowCompatibleConfigurationMismatch &&
2228 ParseHeaderSearchOptions(Record, Complain, Listener))
2229 Result = ConfigurationMismatch;
2230 break;
2231 }
2232
2233 case PREPROCESSOR_OPTIONS:
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2235 if (!AllowCompatibleConfigurationMismatch &&
2236 ParsePreprocessorOptions(Record, Complain, Listener,
2237 SuggestedPredefines))
2238 Result = ConfigurationMismatch;
2239 break;
2240 }
2241 }
2242}
2243
Guy Benyei11169dd2012-12-18 14:30:41 +00002244ASTReader::ASTReadResult
2245ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002246 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002247 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002248 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002249 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002250 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002251
2252 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2253 Error("malformed block record in AST file");
2254 return Failure;
2255 }
2256
2257 // Read all of the records and blocks in the control block.
2258 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002259 unsigned NumInputs = 0;
2260 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002261 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002262 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002263
Chris Lattnere7b154b2013-01-19 21:39:22 +00002264 switch (Entry.Kind) {
2265 case llvm::BitstreamEntry::Error:
2266 Error("malformed block record in AST file");
2267 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002268 case llvm::BitstreamEntry::EndBlock: {
2269 // Validate input files.
2270 const HeaderSearchOptions &HSOpts =
2271 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002272
Richard Smitha1825302014-10-23 22:18:29 +00002273 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002274 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2275 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002276 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2277 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002279
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002280 // If we are reading a module, we will create a verification timestamp,
2281 // so we verify all input files. Otherwise, verify only user input
2282 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002283
2284 unsigned N = NumUserInputs;
2285 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002286 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002287 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002288 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002289 N = NumInputs;
2290
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002291 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002292 InputFile IF = getInputFile(F, I+1, Complain);
2293 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002295 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002297
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002298 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002299 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002300
Ben Langmuircb69b572014-03-07 06:40:32 +00002301 if (Listener && Listener->needsInputFileVisitation()) {
2302 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2303 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002304 for (unsigned I = 0; I < N; ++I) {
2305 bool IsSystem = I >= NumUserInputs;
2306 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002307 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002308 F.Kind == MK_ExplicitModule ||
2309 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002310 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002311 }
2312
Richard Smith8a308ec2015-11-05 00:54:55 +00002313 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002314 }
2315
Chris Lattnere7b154b2013-01-19 21:39:22 +00002316 case llvm::BitstreamEntry::SubBlock:
2317 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 case INPUT_FILES_BLOCK_ID:
2319 F.InputFilesCursor = Stream;
2320 if (Stream.SkipBlock() || // Skip with the main cursor
2321 // Read the abbreviations
2322 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2323 Error("malformed block record in AST file");
2324 return Failure;
2325 }
2326 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002327
2328 case OPTIONS_BLOCK_ID:
2329 // If we're reading the first module for this group, check its options
2330 // are compatible with ours. For modules it imports, no further checking
2331 // is required, because we checked them when we built it.
2332 if (Listener && !ImportedBy) {
2333 // Should we allow the configuration of the module file to differ from
2334 // the configuration of the current translation unit in a compatible
2335 // way?
2336 //
2337 // FIXME: Allow this for files explicitly specified with -include-pch.
2338 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002339 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002340 const HeaderSearchOptions &HSOpts =
2341 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002342
Richard Smith8a308ec2015-11-05 00:54:55 +00002343 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2344 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002345 *Listener, SuggestedPredefines,
2346 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002347 if (Result == Failure) {
2348 Error("malformed block record in AST file");
2349 return Result;
2350 }
2351
Richard Smith8a308ec2015-11-05 00:54:55 +00002352 if (DisableValidation ||
2353 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2354 Result = Success;
2355
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002356 // If we can't load the module, exit early since we likely
2357 // will rebuild the module anyway. The stream may be in the
2358 // middle of a block.
2359 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002360 return Result;
2361 } else if (Stream.SkipBlock()) {
2362 Error("malformed block record in AST file");
2363 return Failure;
2364 }
2365 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002366
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002368 if (Stream.SkipBlock()) {
2369 Error("malformed block record in AST file");
2370 return Failure;
2371 }
2372 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002374
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375 case llvm::BitstreamEntry::Record:
2376 // The interesting case.
2377 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 }
2379
2380 // Read and process a record.
2381 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002382 StringRef Blob;
2383 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 case METADATA: {
2385 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2386 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002387 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2388 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 return VersionMismatch;
2390 }
2391
Richard Smithe75ee0f2015-08-17 07:13:32 +00002392 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2394 Diag(diag::err_pch_with_compiler_errors);
2395 return HadErrors;
2396 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002397 if (hasErrors) {
2398 Diags.ErrorOccurred = true;
2399 Diags.UncompilableErrorOccurred = true;
2400 Diags.UnrecoverableErrorOccurred = true;
2401 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002402
2403 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002404 // Relative paths in a relocatable PCH are relative to our sysroot.
2405 if (F.RelocatablePCH)
2406 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407
Richard Smithe75ee0f2015-08-17 07:13:32 +00002408 F.HasTimestamps = Record[5];
2409
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002411 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2413 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002414 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 return VersionMismatch;
2416 }
2417 break;
2418 }
2419
Ben Langmuir487ea142014-10-23 18:05:36 +00002420 case SIGNATURE:
2421 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2422 F.Signature = Record[0];
2423 break;
2424
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002426 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 unsigned Idx = 0, N = Record.size();
2428 while (Idx < N) {
2429 // Read information about the AST file.
2430 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2431 // The import location will be the local one for now; we will adjust
2432 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002433 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002435 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002436 off_t StoredSize = (off_t)Record[Idx++];
2437 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002438 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002439 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002440
Richard Smith0f99d6a2015-08-09 08:48:41 +00002441 // If our client can't cope with us being out of date, we can't cope with
2442 // our dependency being missing.
2443 unsigned Capabilities = ClientLoadCapabilities;
2444 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2445 Capabilities &= ~ARR_Missing;
2446
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002448 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2449 Loaded, StoredSize, StoredModTime,
2450 StoredSignature, Capabilities);
2451
2452 // If we diagnosed a problem, produce a backtrace.
2453 if (isDiagnosedResult(Result, Capabilities))
2454 Diag(diag::note_module_file_imported_by)
2455 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2456
2457 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 case Failure: return Failure;
2459 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002460 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 case OutOfDate: return OutOfDate;
2462 case VersionMismatch: return VersionMismatch;
2463 case ConfigurationMismatch: return ConfigurationMismatch;
2464 case HadErrors: return HadErrors;
2465 case Success: break;
2466 }
2467 }
2468 break;
2469 }
2470
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 case ORIGINAL_FILE:
2472 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002475 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 break;
2477
2478 case ORIGINAL_FILE_ID:
2479 F.OriginalSourceFileID = FileID::get(Record[0]);
2480 break;
2481
2482 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002483 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 break;
2485
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002486 case MODULE_NAME:
2487 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002488 if (Listener)
2489 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002490 break;
2491
Richard Smith223d3f22014-12-06 03:21:08 +00002492 case MODULE_DIRECTORY: {
2493 assert(!F.ModuleName.empty() &&
2494 "MODULE_DIRECTORY found before MODULE_NAME");
2495 // If we've already loaded a module map file covering this module, we may
2496 // have a better path for it (relative to the current build).
2497 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2498 if (M && M->Directory) {
2499 // If we're implicitly loading a module, the base directory can't
2500 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002501 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002502 const DirectoryEntry *BuildDir =
2503 PP.getFileManager().getDirectory(Blob);
2504 if (!BuildDir || BuildDir != M->Directory) {
2505 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2506 Diag(diag::err_imported_module_relocated)
2507 << F.ModuleName << Blob << M->Directory->getName();
2508 return OutOfDate;
2509 }
2510 }
2511 F.BaseDirectory = M->Directory->getName();
2512 } else {
2513 F.BaseDirectory = Blob;
2514 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002515 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002516 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002517
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002518 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002519 if (ASTReadResult Result =
2520 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2521 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002522 break;
2523
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002524 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002525 NumInputs = Record[0];
2526 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002527 F.InputFileOffsets =
2528 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002529 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002530 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 break;
2532 }
2533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002534}
2535
Ben Langmuir2c9af442014-04-10 17:57:43 +00002536ASTReader::ASTReadResult
2537ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002538 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539
2540 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2541 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 }
2544
2545 // Read all of the records and blocks for the AST file.
2546 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002547 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002548 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002549
Chris Lattnere7b154b2013-01-19 21:39:22 +00002550 switch (Entry.Kind) {
2551 case llvm::BitstreamEntry::Error:
2552 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002553 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002554 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002555 // Outside of C++, we do not store a lookup map for the translation unit.
2556 // Instead, mark it as needing a lookup map to be built if this module
2557 // contains any declarations lexically within it (which it always does!).
2558 // This usually has no cost, since we very rarely need the lookup map for
2559 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002561 if (DC->hasExternalLexicalStorage() &&
2562 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002564
Ben Langmuir2c9af442014-04-10 17:57:43 +00002565 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002567 case llvm::BitstreamEntry::SubBlock:
2568 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 case DECLTYPES_BLOCK_ID:
2570 // We lazily load the decls block, but we want to set up the
2571 // DeclsCursor cursor to point into it. Clone our current bitcode
2572 // cursor to it, enter the block and read the abbrevs in that block.
2573 // With the main cursor, we just skip over it.
2574 F.DeclsCursor = Stream;
2575 if (Stream.SkipBlock() || // Skip with the main cursor.
2576 // Read the abbrevs.
2577 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2578 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002579 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
2581 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case PREPROCESSOR_BLOCK_ID:
2584 F.MacroCursor = Stream;
2585 if (!PP.getExternalSource())
2586 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 if (Stream.SkipBlock() ||
2589 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2590 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 }
2593 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2594 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 case PREPROCESSOR_DETAIL_BLOCK_ID:
2597 F.PreprocessorDetailCursor = Stream;
2598 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002599 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002602 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002606
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 if (!PP.getPreprocessingRecord())
2608 PP.createPreprocessingRecord();
2609 if (!PP.getPreprocessingRecord()->getExternalSource())
2610 PP.getPreprocessingRecord()->SetExternalSource(*this);
2611 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 case SOURCE_MANAGER_BLOCK_ID:
2614 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002617
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002619 if (ASTReadResult Result =
2620 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002625 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 if (Stream.SkipBlock() ||
2627 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2628 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002629 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 }
2631 CommentsCursors.push_back(std::make_pair(C, &F));
2632 break;
2633 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002636 if (Stream.SkipBlock()) {
2637 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002638 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639 }
2640 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 }
2642 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002643
Chris Lattnere7b154b2013-01-19 21:39:22 +00002644 case llvm::BitstreamEntry::Record:
2645 // The interesting case.
2646 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 }
2648
2649 // Read and process a record.
2650 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002651 StringRef Blob;
2652 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 default: // Default behavior: ignore.
2654 break;
2655
2656 case TYPE_OFFSET: {
2657 if (F.LocalNumTypes != 0) {
2658 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002659 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002661 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 F.LocalNumTypes = Record[0];
2663 unsigned LocalBaseTypeIndex = Record[1];
2664 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002665
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 if (F.LocalNumTypes > 0) {
2667 // Introduce the global -> local mapping for types within this module.
2668 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002669
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 // Introduce the local -> global mapping for types within this module.
2671 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002672 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002674
2675 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 }
2677 break;
2678 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 case DECL_OFFSET: {
2681 if (F.LocalNumDecls != 0) {
2682 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002683 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002685 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 F.LocalNumDecls = Record[0];
2687 unsigned LocalBaseDeclID = Record[1];
2688 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002689
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002691 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 // module.
2693 GlobalDeclMap.insert(
2694 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 // Introduce the local -> global mapping for declarations within this
2697 // module.
2698 F.DeclRemap.insertOrReplace(
2699 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 // Introduce the global -> local mapping for declarations within this
2702 // module.
2703 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002704
Ben Langmuir52ca6782014-10-20 16:27:32 +00002705 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 break;
2708 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002709
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 case TU_UPDATE_LEXICAL: {
2711 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002712 LexicalContents Contents(
2713 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2714 Blob.data()),
2715 static_cast<unsigned int>(Blob.size() / 4));
2716 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 TU->setHasExternalLexicalStorage(true);
2718 break;
2719 }
2720
2721 case UPDATE_VISIBLE: {
2722 unsigned Idx = 0;
2723 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002724 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002725 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002726 // If we've already loaded the decl, perform the updates when we finish
2727 // loading this block.
2728 if (Decl *D = GetExistingDecl(ID))
2729 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 break;
2731 }
2732
2733 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002734 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002736 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2737 (const unsigned char *)F.IdentifierTableData + Record[0],
2738 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2739 (const unsigned char *)F.IdentifierTableData,
2740 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002741
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2743 }
2744 break;
2745
2746 case IDENTIFIER_OFFSET: {
2747 if (F.LocalNumIdentifiers != 0) {
2748 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002749 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002751 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 F.LocalNumIdentifiers = Record[0];
2753 unsigned LocalBaseIdentifierID = Record[1];
2754 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002755
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 if (F.LocalNumIdentifiers > 0) {
2757 // Introduce the global -> local mapping for identifiers within this
2758 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002759 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 // Introduce the local -> global mapping for identifiers within this
2763 // module.
2764 F.IdentifierRemap.insertOrReplace(
2765 std::make_pair(LocalBaseIdentifierID,
2766 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002767
Ben Langmuir52ca6782014-10-20 16:27:32 +00002768 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2769 + F.LocalNumIdentifiers);
2770 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 break;
2772 }
2773
Richard Smith33e0f7e2015-07-22 02:08:40 +00002774 case INTERESTING_IDENTIFIERS:
2775 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2776 break;
2777
Ben Langmuir332aafe2014-01-31 01:06:56 +00002778 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002779 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2780 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002782 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 break;
2784
David Blaikie9ffe5a32017-01-30 05:00:26 +00002785 case MODULAR_CODEGEN_DECLS:
2786 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2787 // them (ie: if we're not codegenerating this module).
2788 if (F.Kind == MK_MainFile)
2789 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2790 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2791 break;
2792
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002794 if (SpecialTypes.empty()) {
2795 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2796 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2797 break;
2798 }
2799
2800 if (SpecialTypes.size() != Record.size()) {
2801 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002802 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002803 }
2804
2805 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2806 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2807 if (!SpecialTypes[I])
2808 SpecialTypes[I] = ID;
2809 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2810 // merge step?
2811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 break;
2813
2814 case STATISTICS:
2815 TotalNumStatements += Record[0];
2816 TotalNumMacros += Record[1];
2817 TotalLexicalDeclContexts += Record[2];
2818 TotalVisibleDeclContexts += Record[3];
2819 break;
2820
2821 case UNUSED_FILESCOPED_DECLS:
2822 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2823 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2824 break;
2825
2826 case DELEGATING_CTORS:
2827 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2828 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2829 break;
2830
2831 case WEAK_UNDECLARED_IDENTIFIERS:
2832 if (Record.size() % 4 != 0) {
2833 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002834 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002836
2837 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 // files. This isn't the way to do it :)
2839 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002840
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 // Translate the weak, undeclared identifiers into global IDs.
2842 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2843 WeakUndeclaredIdentifiers.push_back(
2844 getGlobalIdentifierID(F, Record[I++]));
2845 WeakUndeclaredIdentifiers.push_back(
2846 getGlobalIdentifierID(F, Record[I++]));
2847 WeakUndeclaredIdentifiers.push_back(
2848 ReadSourceLocation(F, Record, I).getRawEncoding());
2849 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2850 }
2851 break;
2852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002854 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 F.LocalNumSelectors = Record[0];
2856 unsigned LocalBaseSelectorID = Record[1];
2857 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002858
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002860 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 // module.
2862 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002863
2864 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 // module.
2866 F.SelectorRemap.insertOrReplace(
2867 std::make_pair(LocalBaseSelectorID,
2868 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002869
2870 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 }
2872 break;
2873 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002874
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002876 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 if (Record[0])
2878 F.SelectorLookupTable
2879 = ASTSelectorLookupTable::Create(
2880 F.SelectorLookupTableData + Record[0],
2881 F.SelectorLookupTableData,
2882 ASTSelectorLookupTrait(*this, F));
2883 TotalNumMethodPoolEntries += Record[1];
2884 break;
2885
2886 case REFERENCED_SELECTOR_POOL:
2887 if (!Record.empty()) {
2888 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002889 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 Record[Idx++]));
2891 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2892 getRawEncoding());
2893 }
2894 }
2895 break;
2896
2897 case PP_COUNTER_VALUE:
2898 if (!Record.empty() && Listener)
2899 Listener->ReadCounter(F, Record[0]);
2900 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002901
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002903 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 F.NumFileSortedDecls = Record[0];
2905 break;
2906
2907 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002908 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 F.LocalNumSLocEntries = Record[0];
2910 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002911 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002912 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002914 if (!F.SLocEntryBaseID) {
2915 Error("ran out of source locations");
2916 break;
2917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 // Make our entry in the range map. BaseID is negative and growing, so
2919 // we invert it. Because we invert it, though, we need the other end of
2920 // the range.
2921 unsigned RangeStart =
2922 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2923 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2924 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2925
2926 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2927 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2928 GlobalSLocOffsetMap.insert(
2929 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2930 - SLocSpaceSize,&F));
2931
2932 // Initialize the remapping table.
2933 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002934 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002936 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 TotalNumSLocEntries += F.LocalNumSLocEntries;
2940 break;
2941 }
2942
Richard Smith37a93df2017-02-18 00:32:02 +00002943 case MODULE_OFFSET_MAP:
2944 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002946
2947 case SOURCE_MANAGER_LINE_TABLE:
2948 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002949 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 break;
2951
2952 case SOURCE_LOCATION_PRELOADS: {
2953 // Need to transform from the local view (1-based IDs) to the global view,
2954 // which is based off F.SLocEntryBaseID.
2955 if (!F.PreloadSLocEntries.empty()) {
2956 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002957 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002959
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 F.PreloadSLocEntries.swap(Record);
2961 break;
2962 }
2963
2964 case EXT_VECTOR_DECLS:
2965 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2966 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2967 break;
2968
2969 case VTABLE_USES:
2970 if (Record.size() % 3 != 0) {
2971 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002974
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 // Later tables overwrite earlier ones.
2976 // FIXME: Modules will have some trouble with this. This is clearly not
2977 // the right way to do this.
2978 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002979
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2981 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2982 VTableUses.push_back(
2983 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2984 VTableUses.push_back(Record[Idx++]);
2985 }
2986 break;
2987
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 case PENDING_IMPLICIT_INSTANTIATIONS:
2989 if (PendingInstantiations.size() % 2 != 0) {
2990 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002991 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 }
2993
2994 if (Record.size() % 2 != 0) {
2995 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002996 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 }
2998
2999 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3000 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3001 PendingInstantiations.push_back(
3002 ReadSourceLocation(F, Record, I).getRawEncoding());
3003 }
3004 break;
3005
3006 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003007 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003008 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003009 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003010 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3012 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3013 break;
3014
3015 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003016 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3017 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3018 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003019
3020 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003021
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 unsigned StartingID;
3023 if (!PP.getPreprocessingRecord())
3024 PP.createPreprocessingRecord();
3025 if (!PP.getPreprocessingRecord()->getExternalSource())
3026 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003027 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003029 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 F.BasePreprocessedEntityID = StartingID;
3031
3032 if (F.NumPreprocessedEntities > 0) {
3033 // Introduce the global -> local mapping for preprocessed entities in
3034 // this module.
3035 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 // Introduce the local -> global mapping for preprocessed entities in
3038 // this module.
3039 F.PreprocessedEntityRemap.insertOrReplace(
3040 std::make_pair(LocalBasePreprocessedEntityID,
3041 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3042 }
3043
3044 break;
3045 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003046
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 case DECL_UPDATE_OFFSETS: {
3048 if (Record.size() % 2 != 0) {
3049 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003050 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003052 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3053 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3054 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3055
3056 // If we've already loaded the decl, perform the updates when we finish
3057 // loading this block.
3058 if (Decl *D = GetExistingDecl(ID))
3059 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 break;
3062 }
3063
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 case OBJC_CATEGORIES_MAP: {
3065 if (F.LocalNumObjCCategoriesInMap != 0) {
3066 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003067 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003069
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003071 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 break;
3073 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003074
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 case OBJC_CATEGORIES:
3076 F.ObjCCategories.swap(Record);
3077 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003078
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 case DIAG_PRAGMA_MAPPINGS:
3080 if (F.PragmaDiagMappings.empty())
3081 F.PragmaDiagMappings.swap(Record);
3082 else
3083 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3084 Record.begin(), Record.end());
3085 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003086
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 case CUDA_SPECIAL_DECL_REFS:
3088 // Later tables overwrite earlier ones.
3089 // FIXME: Modules will have trouble with this.
3090 CUDASpecialDeclRefs.clear();
3091 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3092 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3093 break;
3094
3095 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003096 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 if (Record[0]) {
3099 F.HeaderFileInfoTable
3100 = HeaderFileInfoLookupTable::Create(
3101 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3102 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003103 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003105 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003106
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 PP.getHeaderSearchInfo().SetExternalSource(this);
3108 if (!PP.getHeaderSearchInfo().getExternalLookup())
3109 PP.getHeaderSearchInfo().SetExternalLookup(this);
3110 }
3111 break;
3112 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003113
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 case FP_PRAGMA_OPTIONS:
3115 // Later tables overwrite earlier ones.
3116 FPPragmaOptions.swap(Record);
3117 break;
3118
3119 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003120 for (unsigned I = 0, E = Record.size(); I != E; ) {
3121 auto Name = ReadString(Record, I);
3122 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003123 Opt.Supported = Record[I++] != 0;
3124 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003125 Opt.Avail = Record[I++];
3126 Opt.Core = Record[I++];
3127 }
3128 break;
3129
3130 case OPENCL_EXTENSION_TYPES:
3131 for (unsigned I = 0, E = Record.size(); I != E;) {
3132 auto TypeID = static_cast<::TypeID>(Record[I++]);
3133 auto *Type = GetType(TypeID).getTypePtr();
3134 auto NumExt = static_cast<unsigned>(Record[I++]);
3135 for (unsigned II = 0; II != NumExt; ++II) {
3136 auto Ext = ReadString(Record, I);
3137 OpenCLTypeExtMap[Type].insert(Ext);
3138 }
3139 }
3140 break;
3141
3142 case OPENCL_EXTENSION_DECLS:
3143 for (unsigned I = 0, E = Record.size(); I != E;) {
3144 auto DeclID = static_cast<::DeclID>(Record[I++]);
3145 auto *Decl = GetDecl(DeclID);
3146 auto NumExt = static_cast<unsigned>(Record[I++]);
3147 for (unsigned II = 0; II != NumExt; ++II) {
3148 auto Ext = ReadString(Record, I);
3149 OpenCLDeclExtMap[Decl].insert(Ext);
3150 }
3151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 break;
3153
3154 case TENTATIVE_DEFINITIONS:
3155 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3156 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3157 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 case KNOWN_NAMESPACES:
3160 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3161 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3162 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003163
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003164 case UNDEFINED_BUT_USED:
3165 if (UndefinedButUsed.size() % 2 != 0) {
3166 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003167 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003168 }
3169
3170 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003171 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003172 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003173 }
3174 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003175 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3176 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003177 ReadSourceLocation(F, Record, I).getRawEncoding());
3178 }
3179 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003180 case DELETE_EXPRS_TO_ANALYZE:
3181 for (unsigned I = 0, N = Record.size(); I != N;) {
3182 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3183 const uint64_t Count = Record[I++];
3184 DelayedDeleteExprs.push_back(Count);
3185 for (uint64_t C = 0; C < Count; ++C) {
3186 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3187 bool IsArrayForm = Record[I++] == 1;
3188 DelayedDeleteExprs.push_back(IsArrayForm);
3189 }
3190 }
3191 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003192
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003194 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 // If we aren't loading a module (which has its own exports), make
3196 // all of the imported modules visible.
3197 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003198 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3199 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3200 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003201 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003202 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003203 if (DeserializationListener)
3204 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3205 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 }
3207 }
3208 break;
3209 }
3210
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 case MACRO_OFFSET: {
3212 if (F.LocalNumMacros != 0) {
3213 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003214 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003216 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003217 F.LocalNumMacros = Record[0];
3218 unsigned LocalBaseMacroID = Record[1];
3219 F.BaseMacroID = getTotalNumMacros();
3220
3221 if (F.LocalNumMacros > 0) {
3222 // Introduce the global -> local mapping for macros within this module.
3223 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3224
3225 // Introduce the local -> global mapping for macros within this module.
3226 F.MacroRemap.insertOrReplace(
3227 std::make_pair(LocalBaseMacroID,
3228 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003229
3230 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 }
3232 break;
3233 }
3234
Richard Smithe40f2ba2013-08-07 21:41:30 +00003235 case LATE_PARSED_TEMPLATE: {
3236 LateParsedTemplates.append(Record.begin(), Record.end());
3237 break;
3238 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003239
3240 case OPTIMIZE_PRAGMA_OPTIONS:
3241 if (Record.size() != 1) {
3242 Error("invalid pragma optimize record");
3243 return Failure;
3244 }
3245 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3246 break;
Nico Weber72889432014-09-06 01:25:55 +00003247
Nico Weber779355f2016-03-02 23:22:00 +00003248 case MSSTRUCT_PRAGMA_OPTIONS:
3249 if (Record.size() != 1) {
3250 Error("invalid pragma ms_struct record");
3251 return Failure;
3252 }
3253 PragmaMSStructState = Record[0];
3254 break;
3255
Nico Weber42932312016-03-03 00:17:35 +00003256 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3257 if (Record.size() != 2) {
3258 Error("invalid pragma ms_struct record");
3259 return Failure;
3260 }
3261 PragmaMSPointersToMembersState = Record[0];
3262 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3263 break;
3264
Nico Weber72889432014-09-06 01:25:55 +00003265 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3266 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3267 UnusedLocalTypedefNameCandidates.push_back(
3268 getGlobalDeclID(F, Record[I]));
3269 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003270
3271 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3272 if (Record.size() != 1) {
3273 Error("invalid cuda pragma options record");
3274 return Failure;
3275 }
3276 ForceCUDAHostDeviceDepth = Record[0];
3277 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 }
3279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003280}
3281
Richard Smith37a93df2017-02-18 00:32:02 +00003282void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3283 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3284
3285 // Additional remapping information.
3286 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3287 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3288 F.ModuleOffsetMap = StringRef();
3289
3290 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3291 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3292 F.SLocRemap.insert(std::make_pair(0U, 0));
3293 F.SLocRemap.insert(std::make_pair(2U, 1));
3294 }
3295
3296 // Continuous range maps we may be updating in our module.
3297 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3298 RemapBuilder;
3299 RemapBuilder SLocRemap(F.SLocRemap);
3300 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3301 RemapBuilder MacroRemap(F.MacroRemap);
3302 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3303 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3304 RemapBuilder SelectorRemap(F.SelectorRemap);
3305 RemapBuilder DeclRemap(F.DeclRemap);
3306 RemapBuilder TypeRemap(F.TypeRemap);
3307
3308 while (Data < DataEnd) {
3309 // FIXME: Looking up dependency modules by filename is horrible.
3310 using namespace llvm::support;
3311 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3312 StringRef Name = StringRef((const char*)Data, Len);
3313 Data += Len;
3314 ModuleFile *OM = ModuleMgr.lookup(Name);
3315 if (!OM) {
3316 std::string Msg =
3317 "SourceLocation remap refers to unknown module, cannot find ";
3318 Msg.append(Name);
3319 Error(Msg);
3320 return;
3321 }
3322
3323 uint32_t SLocOffset =
3324 endian::readNext<uint32_t, little, unaligned>(Data);
3325 uint32_t IdentifierIDOffset =
3326 endian::readNext<uint32_t, little, unaligned>(Data);
3327 uint32_t MacroIDOffset =
3328 endian::readNext<uint32_t, little, unaligned>(Data);
3329 uint32_t PreprocessedEntityIDOffset =
3330 endian::readNext<uint32_t, little, unaligned>(Data);
3331 uint32_t SubmoduleIDOffset =
3332 endian::readNext<uint32_t, little, unaligned>(Data);
3333 uint32_t SelectorIDOffset =
3334 endian::readNext<uint32_t, little, unaligned>(Data);
3335 uint32_t DeclIDOffset =
3336 endian::readNext<uint32_t, little, unaligned>(Data);
3337 uint32_t TypeIndexOffset =
3338 endian::readNext<uint32_t, little, unaligned>(Data);
3339
3340 uint32_t None = std::numeric_limits<uint32_t>::max();
3341
3342 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3343 RemapBuilder &Remap) {
3344 if (Offset != None)
3345 Remap.insert(std::make_pair(Offset,
3346 static_cast<int>(BaseOffset - Offset)));
3347 };
3348 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3349 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3350 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3351 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3352 PreprocessedEntityRemap);
3353 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3354 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3355 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3356 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3357
3358 // Global -> local mappings.
3359 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3360 }
3361}
3362
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003363ASTReader::ASTReadResult
3364ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3365 const ModuleFile *ImportedBy,
3366 unsigned ClientLoadCapabilities) {
3367 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003368 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003369
Manman Ren11f2a472016-08-18 17:42:15 +00003370 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003371 // For an explicitly-loaded module, we don't care whether the original
3372 // module map file exists or matches.
3373 return Success;
3374 }
3375
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003376 // Try to resolve ModuleName in the current header search context and
3377 // verify that it is found in the same module map file as we saved. If the
3378 // top-level AST file is a main file, skip this check because there is no
3379 // usable header search context.
3380 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003381 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003382 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003383 // An implicitly-loaded module file should have its module listed in some
3384 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003385 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003386 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3387 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3388 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003389 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003390 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3391 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3392 // This module was defined by an imported (explicit) module.
3393 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3394 << ASTFE->getName();
3395 else
3396 // This module was built with a different module map.
3397 Diag(diag::err_imported_module_not_found)
3398 << F.ModuleName << F.FileName << ImportedBy->FileName
3399 << F.ModuleMapPath;
3400 }
3401 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003402 }
3403
Richard Smithe842a472014-10-22 02:05:46 +00003404 assert(M->Name == F.ModuleName && "found module with different name");
3405
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003406 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3409 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003410 assert(ImportedBy && "top-level import should be verified");
3411 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3412 Diag(diag::err_imported_module_modmap_changed)
3413 << F.ModuleName << ImportedBy->FileName
3414 << ModMap->getName() << F.ModuleMapPath;
3415 return OutOfDate;
3416 }
3417
3418 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3419 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3420 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003421 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003422 const FileEntry *F =
3423 FileMgr.getFile(Filename, false, false);
3424 if (F == nullptr) {
3425 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3426 Error("could not find file '" + Filename +"' referenced by AST file");
3427 return OutOfDate;
3428 }
3429 AdditionalStoredMaps.insert(F);
3430 }
3431
3432 // Check any additional module map files (e.g. module.private.modulemap)
3433 // that are not in the pcm.
3434 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3435 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3436 // Remove files that match
3437 // Note: SmallPtrSet::erase is really remove
3438 if (!AdditionalStoredMaps.erase(ModMap)) {
3439 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3440 Diag(diag::err_module_different_modmap)
3441 << F.ModuleName << /*new*/0 << ModMap->getName();
3442 return OutOfDate;
3443 }
3444 }
3445 }
3446
3447 // Check any additional module map files that are in the pcm, but not
3448 // found in header search. Cases that match are already removed.
3449 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3450 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3451 Diag(diag::err_module_different_modmap)
3452 << F.ModuleName << /*not new*/1 << ModMap->getName();
3453 return OutOfDate;
3454 }
3455 }
3456
3457 if (Listener)
3458 Listener->ReadModuleMapFile(F.ModuleMapPath);
3459 return Success;
3460}
3461
3462
Douglas Gregorc1489562013-02-12 23:36:21 +00003463/// \brief Move the given method to the back of the global list of methods.
3464static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3465 // Find the entry for this selector in the method pool.
3466 Sema::GlobalMethodPool::iterator Known
3467 = S.MethodPool.find(Method->getSelector());
3468 if (Known == S.MethodPool.end())
3469 return;
3470
3471 // Retrieve the appropriate method list.
3472 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3473 : Known->second.second;
3474 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003475 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003476 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003477 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003478 Found = true;
3479 } else {
3480 // Keep searching.
3481 continue;
3482 }
3483 }
3484
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003485 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003486 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003487 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003488 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003489 }
3490}
3491
Richard Smithde711422015-04-23 21:20:19 +00003492void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003493 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003494 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003495 bool wasHidden = D->Hidden;
3496 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
Richard Smith49f906a2014-03-01 00:08:04 +00003498 if (wasHidden && SemaObj) {
3499 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3500 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 }
3503 }
3504}
3505
Richard Smith49f906a2014-03-01 00:08:04 +00003506void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003507 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003508 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003510 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003511 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003513 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003514
3515 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003516 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 // there is nothing more to do.
3518 continue;
3519 }
Richard Smith49f906a2014-03-01 00:08:04 +00003520
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 if (!Mod->isAvailable()) {
3522 // Modules that aren't available cannot be made visible.
3523 continue;
3524 }
3525
3526 // Update the module's name visibility.
3527 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003528
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 // If we've already deserialized any names from this module,
3530 // mark them as visible.
3531 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3532 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003533 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003535 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003536 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3537 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003539
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003541 SmallVector<Module *, 16> Exports;
3542 Mod->getExportedModules(Exports);
3543 for (SmallVectorImpl<Module *>::iterator
3544 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3545 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003546 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003547 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003548 }
3549 }
3550}
3551
Richard Smith6561f922016-09-12 21:06:40 +00003552/// We've merged the definition \p MergedDef into the existing definition
3553/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3554/// visible.
3555void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3556 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003557 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3558 // in modules other than its owning module. We should instead give the
3559 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003560 if (Def->isHidden()) {
3561 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003562 if (!MergedDef->isHidden())
3563 Def->Hidden = false;
3564 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3565 getContext().mergeDefinitionIntoModule(
3566 Def, MergedDef->getImportedOwningModule(),
3567 /*NotifyListeners*/ false);
3568 PendingMergedDefinitionsToDeduplicate.insert(Def);
3569 } else {
3570 auto SubmoduleID = MergedDef->getOwningModuleID();
3571 assert(SubmoduleID && "hidden definition in no module");
3572 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3573 }
Richard Smith6561f922016-09-12 21:06:40 +00003574 }
3575}
3576
Douglas Gregore060e572013-01-25 01:03:03 +00003577bool ASTReader::loadGlobalIndex() {
3578 if (GlobalIndex)
3579 return false;
3580
3581 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3582 !Context.getLangOpts().Modules)
3583 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003584
Douglas Gregore060e572013-01-25 01:03:03 +00003585 // Try to load the global index.
3586 TriedLoadingGlobalIndex = true;
3587 StringRef ModuleCachePath
3588 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3589 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003590 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003591 if (!Result.first)
3592 return true;
3593
3594 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003595 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003596 return false;
3597}
3598
3599bool ASTReader::isGlobalIndexUnavailable() const {
3600 return Context.getLangOpts().Modules && UseGlobalIndex &&
3601 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3602}
3603
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003604static void updateModuleTimestamp(ModuleFile &MF) {
3605 // Overwrite the timestamp file contents so that file's mtime changes.
3606 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003607 std::error_code EC;
3608 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3609 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003610 return;
3611 OS << "Timestamp file\n";
3612}
3613
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003614/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3615/// cursor into the start of the given block ID, returning false on success and
3616/// true on failure.
3617static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003618 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003619 llvm::BitstreamEntry Entry = Cursor.advance();
3620 switch (Entry.Kind) {
3621 case llvm::BitstreamEntry::Error:
3622 case llvm::BitstreamEntry::EndBlock:
3623 return true;
3624
3625 case llvm::BitstreamEntry::Record:
3626 // Ignore top-level records.
3627 Cursor.skipRecord(Entry.ID);
3628 break;
3629
3630 case llvm::BitstreamEntry::SubBlock:
3631 if (Entry.ID == BlockID) {
3632 if (Cursor.EnterSubBlock(BlockID))
3633 return true;
3634 // Found it!
3635 return false;
3636 }
3637
3638 if (Cursor.SkipBlock())
3639 return true;
3640 }
3641 }
3642}
3643
Benjamin Kramer0772c422016-02-13 13:42:54 +00003644ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 ModuleKind Type,
3646 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003647 unsigned ClientLoadCapabilities,
3648 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003649 llvm::SaveAndRestore<SourceLocation>
3650 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3651
Richard Smithd1c46742014-04-30 02:24:17 +00003652 // Defer any pending actions until we get to the end of reading the AST file.
3653 Deserializing AnASTFile(this);
3654
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003656 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003657
3658 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003659 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003660 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003661 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003662 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 ClientLoadCapabilities)) {
3664 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003665 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 case OutOfDate:
3667 case VersionMismatch:
3668 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003669 case HadErrors: {
3670 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3671 for (const ImportedModule &IM : Loaded)
3672 LoadedSet.insert(IM.Mod);
3673
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003674 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003675 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003676 ? &PP.getHeaderSearchInfo().getModuleMap()
3677 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003678
3679 // If we find that any modules are unusable, the global index is going
3680 // to be out-of-date. Just remove it.
3681 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003682 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003684 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003685 case Success:
3686 break;
3687 }
3688
3689 // Here comes stuff that we only do once the entire chain is loaded.
3690
3691 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003692 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3693 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 M != MEnd; ++M) {
3695 ModuleFile &F = *M->Mod;
3696
3697 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003698 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3699 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003700
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003701 // Read the extension blocks.
3702 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3703 if (ASTReadResult Result = ReadExtensionBlock(F))
3704 return Result;
3705 }
3706
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003707 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 // bits of all files we've seen.
3709 F.GlobalBitOffset = TotalModulesSizeInBits;
3710 TotalModulesSizeInBits += F.SizeInBits;
3711 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003712
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 // Preload SLocEntries.
3714 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3715 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3716 // Load it through the SourceManager and don't call ReadSLocEntry()
3717 // directly because the entry may have already been loaded in which case
3718 // calling ReadSLocEntry() directly would trigger an assertion in
3719 // SourceManager.
3720 SourceMgr.getLoadedSLocEntryByID(Index);
3721 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003722
3723 // Preload all the pending interesting identifiers by marking them out of
3724 // date.
3725 for (auto Offset : F.PreloadIdentifierOffsets) {
3726 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3727 F.IdentifierTableData + Offset);
3728
3729 ASTIdentifierLookupTrait Trait(*this, F);
3730 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3731 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003732 auto &II = PP.getIdentifierTable().getOwn(Key);
3733 II.setOutOfDate(true);
3734
3735 // Mark this identifier as being from an AST file so that we can track
3736 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003737 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003738
3739 // Associate the ID with the identifier so that the writer can reuse it.
3740 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3741 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003742 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 }
3744
Douglas Gregor603cd862013-03-22 18:50:14 +00003745 // Setup the import locations and notify the module manager that we've
3746 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003747 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3748 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 M != MEnd; ++M) {
3750 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003751
3752 ModuleMgr.moduleFileAccepted(&F);
3753
3754 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003755 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003756 // FIXME: We assume that locations from PCH / preamble do not need
3757 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 if (!M->ImportedBy)
3759 F.ImportLoc = M->ImportLoc;
3760 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003761 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 }
3763
Richard Smith33e0f7e2015-07-22 02:08:40 +00003764 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003765 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3766 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003767 // Mark all of the identifiers in the identifier table as being out of date,
3768 // so that various accessors know to check the loaded modules when the
3769 // identifier is used.
3770 //
3771 // For C++ modules, we don't need information on many identifiers (just
3772 // those that provide macros or are poisoned), so we mark all of
3773 // the interesting ones via PreloadIdentifierOffsets.
3774 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3775 IdEnd = PP.getIdentifierTable().end();
3776 Id != IdEnd; ++Id)
3777 Id->second->setOutOfDate(true);
3778 }
Manman Rena0f31a02016-04-29 19:04:05 +00003779 // Mark selectors as out of date.
3780 for (auto Sel : SelectorGeneration)
3781 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003782
Guy Benyei11169dd2012-12-18 14:30:41 +00003783 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003784 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3785 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3787 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003788
3789 switch (Unresolved.Kind) {
3790 case UnresolvedModuleRef::Conflict:
3791 if (ResolvedMod) {
3792 Module::Conflict Conflict;
3793 Conflict.Other = ResolvedMod;
3794 Conflict.Message = Unresolved.String.str();
3795 Unresolved.Mod->Conflicts.push_back(Conflict);
3796 }
3797 continue;
3798
3799 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003801 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003803
Douglas Gregorfb912652013-03-20 21:10:35 +00003804 case UnresolvedModuleRef::Export:
3805 if (ResolvedMod || Unresolved.IsWildcard)
3806 Unresolved.Mod->Exports.push_back(
3807 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3808 continue;
3809 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003810 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003811 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003812
Graydon Hoaree7196af2016-12-09 21:45:49 +00003813 if (Imported)
3814 Imported->append(ImportedModules.begin(),
3815 ImportedModules.end());
3816
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003817 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3818 // Might be unnecessary as use declarations are only used to build the
3819 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003820
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 InitializeContext();
3822
Richard Smith3d8e97e2013-10-18 06:54:39 +00003823 if (SemaObj)
3824 UpdateSema();
3825
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 if (DeserializationListener)
3827 DeserializationListener->ReaderInitialized(this);
3828
3829 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003830 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003831 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 = FileID::get(PrimaryModule.SLocEntryBaseID
3833 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3834
3835 // If this AST file is a precompiled preamble, then set the
3836 // preamble file ID of the source manager to the file source file
3837 // from which the preamble was built.
3838 if (Type == MK_Preamble) {
3839 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3840 } else if (Type == MK_MainFile) {
3841 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3842 }
3843 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003844
Guy Benyei11169dd2012-12-18 14:30:41 +00003845 // For any Objective-C class definitions we have already loaded, make sure
3846 // that we load any additional categories.
3847 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003848 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 ObjCClassesLoaded[I],
3850 PreviousGeneration);
3851 }
Douglas Gregore060e572013-01-25 01:03:03 +00003852
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003853 if (PP.getHeaderSearchInfo()
3854 .getHeaderSearchOpts()
3855 .ModulesValidateOncePerBuildSession) {
3856 // Now we are certain that the module and all modules it depends on are
3857 // up to date. Create or update timestamp files for modules that are
3858 // located in the module cache (not for PCH files that could be anywhere
3859 // in the filesystem).
3860 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3861 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003862 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003863 updateModuleTimestamp(*M.Mod);
3864 }
3865 }
3866 }
3867
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 return Success;
3869}
3870
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003871static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003872
Ben Langmuir70a1b812015-03-24 04:43:52 +00003873/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3874static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003875 return Stream.canSkipToPos(4) &&
3876 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003877 Stream.Read(8) == 'P' &&
3878 Stream.Read(8) == 'C' &&
3879 Stream.Read(8) == 'H';
3880}
3881
Richard Smith0f99d6a2015-08-09 08:48:41 +00003882static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3883 switch (Kind) {
3884 case MK_PCH:
3885 return 0; // PCH
3886 case MK_ImplicitModule:
3887 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003888 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003889 return 1; // module
3890 case MK_MainFile:
3891 case MK_Preamble:
3892 return 2; // main source file
3893 }
3894 llvm_unreachable("unknown module kind");
3895}
3896
Guy Benyei11169dd2012-12-18 14:30:41 +00003897ASTReader::ASTReadResult
3898ASTReader::ReadASTCore(StringRef FileName,
3899 ModuleKind Type,
3900 SourceLocation ImportLoc,
3901 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003902 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003903 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003904 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 unsigned ClientLoadCapabilities) {
3906 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003908 ModuleManager::AddModuleResult AddResult
3909 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003910 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003911 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003912 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003913
Douglas Gregor7029ce12013-03-19 00:28:20 +00003914 switch (AddResult) {
3915 case ModuleManager::AlreadyLoaded:
3916 return Success;
3917
3918 case ModuleManager::NewlyLoaded:
3919 // Load module file below.
3920 break;
3921
3922 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003923 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003924 // it.
3925 if (ClientLoadCapabilities & ARR_Missing)
3926 return Missing;
3927
3928 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003929 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003930 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003931 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003932 return Failure;
3933
3934 case ModuleManager::OutOfDate:
3935 // We couldn't load the module file because it is out-of-date. If the
3936 // client can handle out-of-date, return it.
3937 if (ClientLoadCapabilities & ARR_OutOfDate)
3938 return OutOfDate;
3939
3940 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003941 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003942 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003943 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 return Failure;
3945 }
3946
Douglas Gregor7029ce12013-03-19 00:28:20 +00003947 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003948
3949 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3950 // module?
3951 if (FileName != "-") {
3952 CurrentDir = llvm::sys::path::parent_path(FileName);
3953 if (CurrentDir.empty()) CurrentDir = ".";
3954 }
3955
3956 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003957 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003958 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003959 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003960
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003962 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003963 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3964 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 return Failure;
3966 }
3967
3968 // This is used for compatibility with older PCH formats.
3969 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003970 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003971 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003972
Chris Lattnerefa77172013-01-20 00:00:22 +00003973 switch (Entry.Kind) {
3974 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003975 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003976 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 Error("invalid record at top-level of AST file");
3978 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003979
Chris Lattnerefa77172013-01-20 00:00:22 +00003980 case llvm::BitstreamEntry::SubBlock:
3981 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 }
3983
Chris Lattnerefa77172013-01-20 00:00:22 +00003984 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 case CONTROL_BLOCK_ID:
3986 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003987 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003989 // Check that we didn't try to load a non-module AST file as a module.
3990 //
3991 // FIXME: Should we also perform the converse check? Loading a module as
3992 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003993 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3994 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003995 F.ModuleName.empty()) {
3996 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3997 if (Result != OutOfDate ||
3998 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3999 Diag(diag::err_module_file_not_module) << FileName;
4000 return Result;
4001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 break;
4003
4004 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004005 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 case OutOfDate: return OutOfDate;
4007 case VersionMismatch: return VersionMismatch;
4008 case ConfigurationMismatch: return ConfigurationMismatch;
4009 case HadErrors: return HadErrors;
4010 }
4011 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004012
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 case AST_BLOCK_ID:
4014 if (!HaveReadControlBlock) {
4015 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004016 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 return VersionMismatch;
4018 }
4019
4020 // Record that we've loaded this module.
4021 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4022 return Success;
4023
4024 default:
4025 if (Stream.SkipBlock()) {
4026 Error("malformed block record in AST file");
4027 return Failure;
4028 }
4029 break;
4030 }
4031 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004032
4033 return Success;
4034}
4035
4036/// Parse a record and blob containing module file extension metadata.
4037static bool parseModuleFileExtensionMetadata(
4038 const SmallVectorImpl<uint64_t> &Record,
4039 StringRef Blob,
4040 ModuleFileExtensionMetadata &Metadata) {
4041 if (Record.size() < 4) return true;
4042
4043 Metadata.MajorVersion = Record[0];
4044 Metadata.MinorVersion = Record[1];
4045
4046 unsigned BlockNameLen = Record[2];
4047 unsigned UserInfoLen = Record[3];
4048
4049 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4050
4051 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4052 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4053 Blob.data() + BlockNameLen + UserInfoLen);
4054 return false;
4055}
4056
4057ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4058 BitstreamCursor &Stream = F.Stream;
4059
4060 RecordData Record;
4061 while (true) {
4062 llvm::BitstreamEntry Entry = Stream.advance();
4063 switch (Entry.Kind) {
4064 case llvm::BitstreamEntry::SubBlock:
4065 if (Stream.SkipBlock())
4066 return Failure;
4067
4068 continue;
4069
4070 case llvm::BitstreamEntry::EndBlock:
4071 return Success;
4072
4073 case llvm::BitstreamEntry::Error:
4074 return HadErrors;
4075
4076 case llvm::BitstreamEntry::Record:
4077 break;
4078 }
4079
4080 Record.clear();
4081 StringRef Blob;
4082 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4083 switch (RecCode) {
4084 case EXTENSION_METADATA: {
4085 ModuleFileExtensionMetadata Metadata;
4086 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4087 return Failure;
4088
4089 // Find a module file extension with this block name.
4090 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4091 if (Known == ModuleFileExtensions.end()) break;
4092
4093 // Form a reader.
4094 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4095 F, Stream)) {
4096 F.ExtensionReaders.push_back(std::move(Reader));
4097 }
4098
4099 break;
4100 }
4101 }
4102 }
4103
4104 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004105}
4106
Richard Smitha7e2cc62015-05-01 01:53:09 +00004107void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 // If there's a listener, notify them that we "read" the translation unit.
4109 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004110 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 Context.getTranslationUnitDecl());
4112
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 // FIXME: Find a better way to deal with collisions between these
4114 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004115
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 // Load the special types.
4117 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4118 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4119 if (!Context.CFConstantStringTypeDecl)
4120 Context.setCFConstantStringType(GetType(String));
4121 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004122
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4124 QualType FileType = GetType(File);
4125 if (FileType.isNull()) {
4126 Error("FILE type is NULL");
4127 return;
4128 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004129
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 if (!Context.FILEDecl) {
4131 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4132 Context.setFILEDecl(Typedef->getDecl());
4133 else {
4134 const TagType *Tag = FileType->getAs<TagType>();
4135 if (!Tag) {
4136 Error("Invalid FILE type in AST file");
4137 return;
4138 }
4139 Context.setFILEDecl(Tag->getDecl());
4140 }
4141 }
4142 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004143
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4145 QualType Jmp_bufType = GetType(Jmp_buf);
4146 if (Jmp_bufType.isNull()) {
4147 Error("jmp_buf type is NULL");
4148 return;
4149 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004150
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 if (!Context.jmp_bufDecl) {
4152 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4153 Context.setjmp_bufDecl(Typedef->getDecl());
4154 else {
4155 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4156 if (!Tag) {
4157 Error("Invalid jmp_buf type in AST file");
4158 return;
4159 }
4160 Context.setjmp_bufDecl(Tag->getDecl());
4161 }
4162 }
4163 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004164
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4166 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4167 if (Sigjmp_bufType.isNull()) {
4168 Error("sigjmp_buf type is NULL");
4169 return;
4170 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004171
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 if (!Context.sigjmp_bufDecl) {
4173 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4174 Context.setsigjmp_bufDecl(Typedef->getDecl());
4175 else {
4176 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4177 assert(Tag && "Invalid sigjmp_buf type in AST file");
4178 Context.setsigjmp_bufDecl(Tag->getDecl());
4179 }
4180 }
4181 }
4182
4183 if (unsigned ObjCIdRedef
4184 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4185 if (Context.ObjCIdRedefinitionType.isNull())
4186 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4187 }
4188
4189 if (unsigned ObjCClassRedef
4190 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4191 if (Context.ObjCClassRedefinitionType.isNull())
4192 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4193 }
4194
4195 if (unsigned ObjCSelRedef
4196 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4197 if (Context.ObjCSelRedefinitionType.isNull())
4198 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4199 }
4200
4201 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4202 QualType Ucontext_tType = GetType(Ucontext_t);
4203 if (Ucontext_tType.isNull()) {
4204 Error("ucontext_t type is NULL");
4205 return;
4206 }
4207
4208 if (!Context.ucontext_tDecl) {
4209 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4210 Context.setucontext_tDecl(Typedef->getDecl());
4211 else {
4212 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4213 assert(Tag && "Invalid ucontext_t type in AST file");
4214 Context.setucontext_tDecl(Tag->getDecl());
4215 }
4216 }
4217 }
4218 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004219
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4221
4222 // If there were any CUDA special declarations, deserialize them.
4223 if (!CUDASpecialDeclRefs.empty()) {
4224 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4225 Context.setcudaConfigureCallDecl(
4226 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4227 }
Richard Smith56be7542014-03-21 00:33:59 +00004228
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004230 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004231 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004232 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004233 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004234 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004235 if (Import.ImportLoc.isValid())
4236 PP.makeModuleVisible(Imported, Import.ImportLoc);
4237 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004238 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 }
4240 ImportedModules.clear();
4241}
4242
4243void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004244 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004245}
4246
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004247/// \brief Reads and return the signature record from \p PCH's control block, or
4248/// else returns 0.
4249static ASTFileSignature readASTFileSignature(StringRef PCH) {
4250 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004251 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004252 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004253
4254 // Scan for the CONTROL_BLOCK_ID block.
4255 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4256 return 0;
4257
4258 // Scan for SIGNATURE inside the control block.
4259 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004260 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004261 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004262 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004263 return 0;
4264
4265 Record.clear();
4266 StringRef Blob;
4267 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4268 return Record[0];
4269 }
4270}
4271
Guy Benyei11169dd2012-12-18 14:30:41 +00004272/// \brief Retrieve the name of the original source file name
4273/// directly from the AST file, without actually loading the AST
4274/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004275std::string ASTReader::getOriginalSourceFile(
4276 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004277 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004279 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004281 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4282 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 return std::string();
4284 }
4285
4286 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004287 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004288
4289 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004290 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4292 return std::string();
4293 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004294
Chris Lattnere7b154b2013-01-19 21:39:22 +00004295 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004296 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004297 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4298 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004300
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004301 // Scan for ORIGINAL_FILE inside the control block.
4302 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004303 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004304 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004305 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4306 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004307
Chris Lattnere7b154b2013-01-19 21:39:22 +00004308 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4309 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4310 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004312
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004314 StringRef Blob;
4315 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4316 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004318}
4319
4320namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004321
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 class SimplePCHValidator : public ASTReaderListener {
4323 const LangOptions &ExistingLangOpts;
4324 const TargetOptions &ExistingTargetOpts;
4325 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004326 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004328
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 public:
4330 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4331 const TargetOptions &ExistingTargetOpts,
4332 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004333 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 FileManager &FileMgr)
4335 : ExistingLangOpts(ExistingLangOpts),
4336 ExistingTargetOpts(ExistingTargetOpts),
4337 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004338 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 FileMgr(FileMgr)
4340 {
4341 }
4342
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004343 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4344 bool AllowCompatibleDifferences) override {
4345 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4346 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004348
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004349 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4350 bool AllowCompatibleDifferences) override {
4351 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4352 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004354
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004355 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4356 StringRef SpecificModuleCachePath,
4357 bool Complain) override {
4358 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4359 ExistingModuleCachePath,
4360 nullptr, ExistingLangOpts);
4361 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004362
Craig Topper3e89dfe2014-03-13 02:13:41 +00004363 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4364 bool Complain,
4365 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004366 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004367 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 }
4369 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004370
4371} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004372
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004373bool ASTReader::readASTFileControlBlock(
4374 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004375 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004376 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004377 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004379 // FIXME: This allows use of the VFS; we do not allow use of the
4380 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004381 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 if (!Buffer) {
4383 return true;
4384 }
4385
4386 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004387 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004388
4389 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004390 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004392
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004393 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004394 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004395 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004396
4397 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004398 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004399 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004400 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004401
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004403 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004404 bool DoneWithControlBlock = false;
4405 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004406 llvm::BitstreamEntry Entry = Stream.advance();
4407
4408 switch (Entry.Kind) {
4409 case llvm::BitstreamEntry::SubBlock: {
4410 switch (Entry.ID) {
4411 case OPTIONS_BLOCK_ID: {
4412 std::string IgnoredSuggestedPredefines;
4413 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4414 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004415 Listener, IgnoredSuggestedPredefines,
4416 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004417 return true;
4418 break;
4419 }
4420
4421 case INPUT_FILES_BLOCK_ID:
4422 InputFilesCursor = Stream;
4423 if (Stream.SkipBlock() ||
4424 (NeedsInputFiles &&
4425 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4426 return true;
4427 break;
4428
4429 default:
4430 if (Stream.SkipBlock())
4431 return true;
4432 break;
4433 }
4434
4435 continue;
4436 }
4437
4438 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004439 DoneWithControlBlock = true;
4440 break;
Richard Smith0516b182015-09-08 19:40:14 +00004441
4442 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004443 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004444
4445 case llvm::BitstreamEntry::Record:
4446 break;
4447 }
4448
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004449 if (DoneWithControlBlock) break;
4450
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004452 StringRef Blob;
4453 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004454 switch ((ControlRecordTypes)RecCode) {
4455 case METADATA: {
4456 if (Record[0] != VERSION_MAJOR)
4457 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004459 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004460 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004461
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004462 break;
4463 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004464 case MODULE_NAME:
4465 Listener.ReadModuleName(Blob);
4466 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004467 case MODULE_DIRECTORY:
4468 ModuleDir = Blob;
4469 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004470 case MODULE_MAP_FILE: {
4471 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004472 auto Path = ReadString(Record, Idx);
4473 ResolveImportedPath(Path, ModuleDir);
4474 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004475 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004476 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004477 case INPUT_FILE_OFFSETS: {
4478 if (!NeedsInputFiles)
4479 break;
4480
4481 unsigned NumInputFiles = Record[0];
4482 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004483 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004484 for (unsigned I = 0; I != NumInputFiles; ++I) {
4485 // Go find this input file.
4486 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004487
4488 if (isSystemFile && !NeedsSystemInputFiles)
4489 break; // the rest are system input files
4490
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004491 BitstreamCursor &Cursor = InputFilesCursor;
4492 SavedStreamPosition SavedPosition(Cursor);
4493 Cursor.JumpToBit(InputFileOffs[I]);
4494
4495 unsigned Code = Cursor.ReadCode();
4496 RecordData Record;
4497 StringRef Blob;
4498 bool shouldContinue = false;
4499 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4500 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004501 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004502 std::string Filename = Blob;
4503 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004504 shouldContinue = Listener.visitInputFile(
4505 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004506 break;
4507 }
4508 if (!shouldContinue)
4509 break;
4510 }
4511 break;
4512 }
4513
Richard Smithd4b230b2014-10-27 23:01:16 +00004514 case IMPORTS: {
4515 if (!NeedsImports)
4516 break;
4517
4518 unsigned Idx = 0, N = Record.size();
4519 while (Idx < N) {
4520 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004521 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004522 std::string Filename = ReadString(Record, Idx);
4523 ResolveImportedPath(Filename, ModuleDir);
4524 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004525 }
4526 break;
4527 }
4528
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004529 default:
4530 // No other validation to perform.
4531 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 }
4533 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004534
4535 // Look for module file extension blocks, if requested.
4536 if (FindModuleFileExtensions) {
4537 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4538 bool DoneWithExtensionBlock = false;
4539 while (!DoneWithExtensionBlock) {
4540 llvm::BitstreamEntry Entry = Stream.advance();
4541
4542 switch (Entry.Kind) {
4543 case llvm::BitstreamEntry::SubBlock:
4544 if (Stream.SkipBlock())
4545 return true;
4546
4547 continue;
4548
4549 case llvm::BitstreamEntry::EndBlock:
4550 DoneWithExtensionBlock = true;
4551 continue;
4552
4553 case llvm::BitstreamEntry::Error:
4554 return true;
4555
4556 case llvm::BitstreamEntry::Record:
4557 break;
4558 }
4559
4560 Record.clear();
4561 StringRef Blob;
4562 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4563 switch (RecCode) {
4564 case EXTENSION_METADATA: {
4565 ModuleFileExtensionMetadata Metadata;
4566 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4567 return true;
4568
4569 Listener.readModuleFileExtension(Metadata);
4570 break;
4571 }
4572 }
4573 }
4574 }
4575 }
4576
4577 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578}
4579
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004580bool ASTReader::isAcceptableASTFile(
4581 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004582 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004583 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4584 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004585 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4586 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004587 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004588 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004589 validator,
4590 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004591}
4592
Ben Langmuir2c9af442014-04-10 17:57:43 +00004593ASTReader::ASTReadResult
4594ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 // Enter the submodule block.
4596 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4597 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004598 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 }
4600
4601 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4602 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004603 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 RecordData Record;
4605 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004606 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004607
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004608 switch (Entry.Kind) {
4609 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4610 case llvm::BitstreamEntry::Error:
4611 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004612 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004613 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004614 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004615 case llvm::BitstreamEntry::Record:
4616 // The interesting case.
4617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004619
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004621 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004623 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4624
4625 if ((Kind == SUBMODULE_METADATA) != First) {
4626 Error("submodule metadata record should be at beginning of block");
4627 return Failure;
4628 }
4629 First = false;
4630
4631 // Submodule information is only valid if we have a current module.
4632 // FIXME: Should we error on these cases?
4633 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4634 Kind != SUBMODULE_DEFINITION)
4635 continue;
4636
4637 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 default: // Default behavior: ignore.
4639 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004640
Richard Smith03478d92014-10-23 22:12:14 +00004641 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004642 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004644 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
Richard Smith03478d92014-10-23 22:12:14 +00004646
Chris Lattner0e6c9402013-01-20 02:38:54 +00004647 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004648 unsigned Idx = 0;
4649 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4650 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4651 bool IsFramework = Record[Idx++];
4652 bool IsExplicit = Record[Idx++];
4653 bool IsSystem = Record[Idx++];
4654 bool IsExternC = Record[Idx++];
4655 bool InferSubmodules = Record[Idx++];
4656 bool InferExplicitSubmodules = Record[Idx++];
4657 bool InferExportWildcard = Record[Idx++];
4658 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004659 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004660
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004661 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004662 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004664
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 // Retrieve this (sub)module from the module map, creating it if
4666 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004667 CurrentModule =
4668 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4669 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004670
4671 // FIXME: set the definition loc for CurrentModule, or call
4672 // ModMap.setInferredModuleAllowedBy()
4673
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4675 if (GlobalIndex >= SubmodulesLoaded.size() ||
4676 SubmodulesLoaded[GlobalIndex]) {
4677 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004678 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004680
Douglas Gregor7029ce12013-03-19 00:28:20 +00004681 if (!ParentModule) {
4682 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4683 if (CurFile != F.File) {
4684 if (!Diags.isDiagnosticInFlight()) {
4685 Diag(diag::err_module_file_conflict)
4686 << CurrentModule->getTopLevelModuleName()
4687 << CurFile->getName()
4688 << F.File->getName();
4689 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004690 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004691 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004692 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004693
4694 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004695 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004696
Adrian Prantl15bcf702015-06-30 17:39:43 +00004697 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 CurrentModule->IsFromModuleFile = true;
4699 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004700 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 CurrentModule->InferSubmodules = InferSubmodules;
4702 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4703 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004704 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004705 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 if (DeserializationListener)
4707 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004708
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004710
Richard Smith8a3e39a2016-03-28 21:31:09 +00004711 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004712 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004713 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004714 CurrentModule->UnresolvedConflicts.clear();
4715 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004716
4717 // The module is available unless it's missing a requirement; relevant
4718 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4719 // Missing headers that were present when the module was built do not
4720 // make it unavailable -- if we got this far, this must be an explicitly
4721 // imported module file.
4722 CurrentModule->Requirements.clear();
4723 CurrentModule->MissingHeaders.clear();
4724 CurrentModule->IsMissingRequirement =
4725 ParentModule && ParentModule->IsMissingRequirement;
4726 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 break;
4728 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004729
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004731 std::string Filename = Blob;
4732 ResolveImportedPath(F, Filename);
4733 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004735 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4736 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004737 // This can be a spurious difference caused by changing the VFS to
4738 // point to a different copy of the file, and it is too late to
4739 // to rebuild safely.
4740 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4741 // after input file validation only real problems would remain and we
4742 // could just error. For now, assume it's okay.
4743 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 }
4745 }
4746 break;
4747 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004748
Richard Smith202210b2014-10-24 20:23:01 +00004749 case SUBMODULE_HEADER:
4750 case SUBMODULE_EXCLUDED_HEADER:
4751 case SUBMODULE_PRIVATE_HEADER:
4752 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004753 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4754 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004755 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004756
Richard Smith202210b2014-10-24 20:23:01 +00004757 case SUBMODULE_TEXTUAL_HEADER:
4758 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4759 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4760 // them here.
4761 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004762
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004764 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 break;
4766 }
4767
4768 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004769 std::string Dirname = Blob;
4770 ResolveImportedPath(F, Dirname);
4771 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004773 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4774 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004775 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4776 Error("mismatched umbrella directories in submodule");
4777 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 }
4779 }
4780 break;
4781 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004782
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 F.BaseSubmoduleID = getTotalNumSubmodules();
4785 F.LocalNumSubmodules = Record[0];
4786 unsigned LocalBaseSubmoduleID = Record[1];
4787 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004788 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 // module.
4790 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004791
4792 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 // module.
4794 F.SubmoduleRemap.insertOrReplace(
4795 std::make_pair(LocalBaseSubmoduleID,
4796 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004797
Ben Langmuir52ca6782014-10-20 16:27:32 +00004798 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4799 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 break;
4801 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004802
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004805 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 Unresolved.File = &F;
4807 Unresolved.Mod = CurrentModule;
4808 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004809 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004811 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 }
4813 break;
4814 }
4815
4816 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004818 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 Unresolved.File = &F;
4820 Unresolved.Mod = CurrentModule;
4821 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004822 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004824 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004826
4827 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 // the parsed, unresolved exports around.
4829 CurrentModule->UnresolvedExports.clear();
4830 break;
4831 }
4832 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004833 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 Context.getTargetInfo());
4835 break;
4836 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004837
4838 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004839 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004840 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004841 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004842
4843 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004844 CurrentModule->ConfigMacros.push_back(Blob.str());
4845 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004846
4847 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004848 UnresolvedModuleRef Unresolved;
4849 Unresolved.File = &F;
4850 Unresolved.Mod = CurrentModule;
4851 Unresolved.ID = Record[0];
4852 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4853 Unresolved.IsWildcard = false;
4854 Unresolved.String = Blob;
4855 UnresolvedModuleRefs.push_back(Unresolved);
4856 break;
4857 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004858
4859 case SUBMODULE_INITIALIZERS:
4860 SmallVector<uint32_t, 16> Inits;
4861 for (auto &ID : Record)
4862 Inits.push_back(getGlobalDeclID(F, ID));
4863 Context.addLazyModuleInitializers(CurrentModule, Inits);
4864 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 }
4866 }
4867}
4868
4869/// \brief Parse the record that corresponds to a LangOptions data
4870/// structure.
4871///
4872/// This routine parses the language options from the AST file and then gives
4873/// them to the AST listener if one is set.
4874///
4875/// \returns true if the listener deems the file unacceptable, false otherwise.
4876bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4877 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004878 ASTReaderListener &Listener,
4879 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 LangOptions LangOpts;
4881 unsigned Idx = 0;
4882#define LANGOPT(Name, Bits, Default, Description) \
4883 LangOpts.Name = Record[Idx++];
4884#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4885 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4886#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004887#define SANITIZER(NAME, ID) \
4888 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004889#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004890
Ben Langmuircd98cb72015-06-23 18:20:18 +00004891 for (unsigned N = Record[Idx++]; N; --N)
4892 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4893
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4895 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4896 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004897
Ben Langmuird4a667a2015-06-23 18:20:23 +00004898 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004899
4900 // Comment options.
4901 for (unsigned N = Record[Idx++]; N; --N) {
4902 LangOpts.CommentOpts.BlockCommandNames.push_back(
4903 ReadString(Record, Idx));
4904 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004905 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004906
Samuel Antaoee8fb302016-01-06 13:42:12 +00004907 // OpenMP offloading options.
4908 for (unsigned N = Record[Idx++]; N; --N) {
4909 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4910 }
4911
4912 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4913
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004914 return Listener.ReadLanguageOptions(LangOpts, Complain,
4915 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004916}
4917
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004918bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4919 ASTReaderListener &Listener,
4920 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 unsigned Idx = 0;
4922 TargetOptions TargetOpts;
4923 TargetOpts.Triple = ReadString(Record, Idx);
4924 TargetOpts.CPU = ReadString(Record, Idx);
4925 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 for (unsigned N = Record[Idx++]; N; --N) {
4927 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4928 }
4929 for (unsigned N = Record[Idx++]; N; --N) {
4930 TargetOpts.Features.push_back(ReadString(Record, Idx));
4931 }
4932
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004933 return Listener.ReadTargetOptions(TargetOpts, Complain,
4934 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004935}
4936
4937bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4938 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004939 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004941#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004942#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004943 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004944#include "clang/Basic/DiagnosticOptions.def"
4945
Richard Smith3be1cb22014-08-07 00:24:21 +00004946 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004947 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004948 for (unsigned N = Record[Idx++]; N; --N)
4949 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004950
4951 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4952}
4953
4954bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4955 ASTReaderListener &Listener) {
4956 FileSystemOptions FSOpts;
4957 unsigned Idx = 0;
4958 FSOpts.WorkingDir = ReadString(Record, Idx);
4959 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4960}
4961
4962bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4963 bool Complain,
4964 ASTReaderListener &Listener) {
4965 HeaderSearchOptions HSOpts;
4966 unsigned Idx = 0;
4967 HSOpts.Sysroot = ReadString(Record, Idx);
4968
4969 // Include entries.
4970 for (unsigned N = Record[Idx++]; N; --N) {
4971 std::string Path = ReadString(Record, Idx);
4972 frontend::IncludeDirGroup Group
4973 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 bool IsFramework = Record[Idx++];
4975 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004976 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4977 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 }
4979
4980 // System header prefixes.
4981 for (unsigned N = Record[Idx++]; N; --N) {
4982 std::string Prefix = ReadString(Record, Idx);
4983 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004984 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 }
4986
4987 HSOpts.ResourceDir = ReadString(Record, Idx);
4988 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004989 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 HSOpts.DisableModuleHash = Record[Idx++];
4991 HSOpts.UseBuiltinIncludes = Record[Idx++];
4992 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4993 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4994 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004995 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004996
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004997 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4998 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004999}
5000
5001bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5002 bool Complain,
5003 ASTReaderListener &Listener,
5004 std::string &SuggestedPredefines) {
5005 PreprocessorOptions PPOpts;
5006 unsigned Idx = 0;
5007
5008 // Macro definitions/undefs
5009 for (unsigned N = Record[Idx++]; N; --N) {
5010 std::string Macro = ReadString(Record, Idx);
5011 bool IsUndef = Record[Idx++];
5012 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5013 }
5014
5015 // Includes
5016 for (unsigned N = Record[Idx++]; N; --N) {
5017 PPOpts.Includes.push_back(ReadString(Record, Idx));
5018 }
5019
5020 // Macro Includes
5021 for (unsigned N = Record[Idx++]; N; --N) {
5022 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5023 }
5024
5025 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005026 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5028 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5029 PPOpts.ObjCXXARCStandardLibrary =
5030 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5031 SuggestedPredefines.clear();
5032 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5033 SuggestedPredefines);
5034}
5035
5036std::pair<ModuleFile *, unsigned>
5037ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5038 GlobalPreprocessedEntityMapType::iterator
5039 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005040 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 "Corrupted global preprocessed entity map");
5042 ModuleFile *M = I->second;
5043 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5044 return std::make_pair(M, LocalIndex);
5045}
5046
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005047llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005048ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5049 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5050 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5051 Mod.NumPreprocessedEntities);
5052
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005053 return llvm::make_range(PreprocessingRecord::iterator(),
5054 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005055}
5056
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005057llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005058ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005059 return llvm::make_range(
5060 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5061 ModuleDeclIterator(this, &Mod,
5062 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005063}
5064
5065PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5066 PreprocessedEntityID PPID = Index+1;
5067 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5068 ModuleFile &M = *PPInfo.first;
5069 unsigned LocalIndex = PPInfo.second;
5070 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5071
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 if (!PP.getPreprocessingRecord()) {
5073 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005074 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005076
5077 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005078 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5079
5080 llvm::BitstreamEntry Entry =
5081 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5082 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005083 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005084
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005086 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5087 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005089 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 RecordData Record;
5091 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005092 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5093 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 switch (RecType) {
5095 case PPD_MACRO_EXPANSION: {
5096 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005097 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005098 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 if (isBuiltin)
5100 Name = getLocalIdentifier(M, Record[1]);
5101 else {
Richard Smith66a81862015-05-04 02:25:31 +00005102 PreprocessedEntityID GlobalID =
5103 getGlobalPreprocessedEntityID(M, Record[1]);
5104 Def = cast<MacroDefinitionRecord>(
5105 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 }
5107
5108 MacroExpansion *ME;
5109 if (isBuiltin)
5110 ME = new (PPRec) MacroExpansion(Name, Range);
5111 else
5112 ME = new (PPRec) MacroExpansion(Def, Range);
5113
5114 return ME;
5115 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005116
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case PPD_MACRO_DEFINITION: {
5118 // Decode the identifier info and then check again; if the macro is
5119 // still defined and associated with the identifier,
5120 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005121 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005122
5123 if (DeserializationListener)
5124 DeserializationListener->MacroDefinitionRead(PPID, MD);
5125
5126 return MD;
5127 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005128
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005130 const char *FullFileNameStart = Blob.data() + Record[0];
5131 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005132 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 if (!FullFileName.empty())
5134 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005135
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 // FIXME: Stable encoding
5137 InclusionDirective::InclusionKind Kind
5138 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5139 InclusionDirective *ID
5140 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005141 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 Record[1], Record[3],
5143 File,
5144 Range);
5145 return ID;
5146 }
5147 }
5148
5149 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5150}
5151
5152/// \brief \arg SLocMapI points at a chunk of a module that contains no
5153/// preprocessed entities or the entities it contains are not the ones we are
5154/// looking for. Find the next module that contains entities and return the ID
5155/// of the first entry.
5156PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5157 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5158 ++SLocMapI;
5159 for (GlobalSLocOffsetMapType::const_iterator
5160 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5161 ModuleFile &M = *SLocMapI->second;
5162 if (M.NumPreprocessedEntities)
5163 return M.BasePreprocessedEntityID;
5164 }
5165
5166 return getTotalNumPreprocessedEntities();
5167}
5168
5169namespace {
5170
Guy Benyei11169dd2012-12-18 14:30:41 +00005171struct PPEntityComp {
5172 const ASTReader &Reader;
5173 ModuleFile &M;
5174
5175 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5176
5177 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5178 SourceLocation LHS = getLoc(L);
5179 SourceLocation RHS = getLoc(R);
5180 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5181 }
5182
5183 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5184 SourceLocation LHS = getLoc(L);
5185 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5186 }
5187
5188 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5189 SourceLocation RHS = getLoc(R);
5190 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5191 }
5192
5193 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005194 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 }
5196};
5197
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005198} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005199
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005200PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5201 bool EndsAfter) const {
5202 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 return getTotalNumPreprocessedEntities();
5204
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005205 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5206 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5208 "Corrupted global sloc offset map");
5209
5210 if (SLocMapI->second->NumPreprocessedEntities == 0)
5211 return findNextPreprocessedEntity(SLocMapI);
5212
5213 ModuleFile &M = *SLocMapI->second;
5214 typedef const PPEntityOffset *pp_iterator;
5215 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5216 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5217
5218 size_t Count = M.NumPreprocessedEntities;
5219 size_t Half;
5220 pp_iterator First = pp_begin;
5221 pp_iterator PPI;
5222
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005223 if (EndsAfter) {
5224 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005225 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005226 } else {
5227 // Do a binary search manually instead of using std::lower_bound because
5228 // The end locations of entities may be unordered (when a macro expansion
5229 // is inside another macro argument), but for this case it is not important
5230 // whether we get the first macro expansion or its containing macro.
5231 while (Count > 0) {
5232 Half = Count / 2;
5233 PPI = First;
5234 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005235 if (SourceMgr.isBeforeInTranslationUnit(
5236 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005237 First = PPI;
5238 ++First;
5239 Count = Count - Half - 1;
5240 } else
5241 Count = Half;
5242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 }
5244
5245 if (PPI == pp_end)
5246 return findNextPreprocessedEntity(SLocMapI);
5247
5248 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5249}
5250
Guy Benyei11169dd2012-12-18 14:30:41 +00005251/// \brief Returns a pair of [Begin, End) indices of preallocated
5252/// preprocessed entities that \arg Range encompasses.
5253std::pair<unsigned, unsigned>
5254 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5255 if (Range.isInvalid())
5256 return std::make_pair(0,0);
5257 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5258
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005259 PreprocessedEntityID BeginID =
5260 findPreprocessedEntity(Range.getBegin(), false);
5261 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 return std::make_pair(BeginID, EndID);
5263}
5264
5265/// \brief Optionally returns true or false if the preallocated preprocessed
5266/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005267Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 FileID FID) {
5269 if (FID.isInvalid())
5270 return false;
5271
5272 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5273 ModuleFile &M = *PPInfo.first;
5274 unsigned LocalIndex = PPInfo.second;
5275 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005276
Richard Smithcb34bd32016-03-27 07:28:06 +00005277 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 if (Loc.isInvalid())
5279 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005280
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5282 return true;
5283 else
5284 return false;
5285}
5286
5287namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005288
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 /// \brief Visitor used to search for information about a header file.
5290 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005292
David Blaikie05785d12013-02-20 22:23:23 +00005293 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005294
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005296 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5297 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005298
5299 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 HeaderFileInfoLookupTable *Table
5301 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5302 if (!Table)
5303 return false;
5304
5305 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005306 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 if (Pos == Table->end())
5308 return false;
5309
Richard Smithbdf2d932015-07-30 03:37:16 +00005310 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 return true;
5312 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005313
David Blaikie05785d12013-02-20 22:23:23 +00005314 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005316
5317} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005318
5319HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005320 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005321 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005322 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005324
Guy Benyei11169dd2012-12-18 14:30:41 +00005325 return HeaderFileInfo();
5326}
5327
5328void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005329 using DiagState = DiagnosticsEngine::DiagState;
5330 SmallVector<DiagState *, 32> DiagStates;
5331
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005332 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005334 auto &Record = F.PragmaDiagMappings;
5335 if (Record.empty())
5336 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005337
Richard Smithd230de22017-01-26 01:01:01 +00005338 DiagStates.clear();
5339
5340 auto ReadDiagState =
5341 [&](const DiagState &BasedOn, SourceLocation Loc,
5342 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5343 unsigned BackrefID = Record[Idx++];
5344 if (BackrefID != 0)
5345 return DiagStates[BackrefID - 1];
5346
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005348 Diag.DiagStates.push_back(BasedOn);
5349 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005351 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5352 unsigned DiagID = Record[Idx++];
5353 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005354 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005355 if (Mapping.isPragma() || IncludeNonPragmaStates)
5356 NewState->setMapping(DiagID, Mapping);
5357 }
5358 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5359 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5360 ++Idx;
5361 return NewState;
5362 };
5363
5364 auto *FirstState = ReadDiagState(
5365 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5366 SourceLocation(), F.isModule());
5367 SourceLocation CurStateLoc =
5368 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5369 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5370
5371 if (!F.isModule()) {
5372 Diag.DiagStatesByLoc.CurDiagState = CurState;
5373 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5374
5375 // Preserve the property that the imaginary root file describes the
5376 // current state.
5377 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5378 if (T.empty())
5379 T.push_back({CurState, 0});
5380 else
5381 T[0].State = CurState;
5382 }
5383
5384 while (Idx < Record.size()) {
5385 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5386 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5387 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5388 unsigned Transitions = Record[Idx++];
5389
5390 // Note that we don't need to set up Parent/ParentOffset here, because
5391 // we won't be changing the diagnostic state within imported FileIDs
5392 // (other than perhaps appending to the main source file, which has no
5393 // parent).
5394 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5395 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5396 for (unsigned I = 0; I != Transitions; ++I) {
5397 unsigned Offset = Record[Idx++];
5398 auto *State =
5399 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5400 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005401 }
5402 }
Richard Smithd230de22017-01-26 01:01:01 +00005403
5404 // Don't try to read these mappings again.
5405 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 }
5407}
5408
5409/// \brief Get the correct cursor and offset for loading a type.
5410ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5411 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5412 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5413 ModuleFile *M = I->second;
5414 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5415}
5416
5417/// \brief Read and return the type with the given index..
5418///
5419/// The index is the type ID, shifted and minus the number of predefs. This
5420/// routine actually reads the record corresponding to the type at the given
5421/// location. It is a helper routine for GetType, which deals with reading type
5422/// IDs.
5423QualType ASTReader::readTypeRecord(unsigned Index) {
5424 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005425 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005426
5427 // Keep track of where we are in the stream, then jump back there
5428 // after reading this type.
5429 SavedStreamPosition SavedPosition(DeclsCursor);
5430
5431 ReadingKindTracker ReadingKind(Read_Type, *this);
5432
5433 // Note that we are loading a type record.
5434 Deserializing AType(this);
5435
5436 unsigned Idx = 0;
5437 DeclsCursor.JumpToBit(Loc.Offset);
5438 RecordData Record;
5439 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005440 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 case TYPE_EXT_QUAL: {
5442 if (Record.size() != 2) {
5443 Error("Incorrect encoding of extended qualifier type");
5444 return QualType();
5445 }
5446 QualType Base = readType(*Loc.F, Record, Idx);
5447 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5448 return Context.getQualifiedType(Base, Quals);
5449 }
5450
5451 case TYPE_COMPLEX: {
5452 if (Record.size() != 1) {
5453 Error("Incorrect encoding of complex type");
5454 return QualType();
5455 }
5456 QualType ElemType = readType(*Loc.F, Record, Idx);
5457 return Context.getComplexType(ElemType);
5458 }
5459
5460 case TYPE_POINTER: {
5461 if (Record.size() != 1) {
5462 Error("Incorrect encoding of pointer type");
5463 return QualType();
5464 }
5465 QualType PointeeType = readType(*Loc.F, Record, Idx);
5466 return Context.getPointerType(PointeeType);
5467 }
5468
Reid Kleckner8a365022013-06-24 17:51:48 +00005469 case TYPE_DECAYED: {
5470 if (Record.size() != 1) {
5471 Error("Incorrect encoding of decayed type");
5472 return QualType();
5473 }
5474 QualType OriginalType = readType(*Loc.F, Record, Idx);
5475 QualType DT = Context.getAdjustedParameterType(OriginalType);
5476 if (!isa<DecayedType>(DT))
5477 Error("Decayed type does not decay");
5478 return DT;
5479 }
5480
Reid Kleckner0503a872013-12-05 01:23:43 +00005481 case TYPE_ADJUSTED: {
5482 if (Record.size() != 2) {
5483 Error("Incorrect encoding of adjusted type");
5484 return QualType();
5485 }
5486 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5487 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5488 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5489 }
5490
Guy Benyei11169dd2012-12-18 14:30:41 +00005491 case TYPE_BLOCK_POINTER: {
5492 if (Record.size() != 1) {
5493 Error("Incorrect encoding of block pointer type");
5494 return QualType();
5495 }
5496 QualType PointeeType = readType(*Loc.F, Record, Idx);
5497 return Context.getBlockPointerType(PointeeType);
5498 }
5499
5500 case TYPE_LVALUE_REFERENCE: {
5501 if (Record.size() != 2) {
5502 Error("Incorrect encoding of lvalue reference type");
5503 return QualType();
5504 }
5505 QualType PointeeType = readType(*Loc.F, Record, Idx);
5506 return Context.getLValueReferenceType(PointeeType, Record[1]);
5507 }
5508
5509 case TYPE_RVALUE_REFERENCE: {
5510 if (Record.size() != 1) {
5511 Error("Incorrect encoding of rvalue reference type");
5512 return QualType();
5513 }
5514 QualType PointeeType = readType(*Loc.F, Record, Idx);
5515 return Context.getRValueReferenceType(PointeeType);
5516 }
5517
5518 case TYPE_MEMBER_POINTER: {
5519 if (Record.size() != 2) {
5520 Error("Incorrect encoding of member pointer type");
5521 return QualType();
5522 }
5523 QualType PointeeType = readType(*Loc.F, Record, Idx);
5524 QualType ClassType = readType(*Loc.F, Record, Idx);
5525 if (PointeeType.isNull() || ClassType.isNull())
5526 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005527
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5529 }
5530
5531 case TYPE_CONSTANT_ARRAY: {
5532 QualType ElementType = readType(*Loc.F, Record, Idx);
5533 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5534 unsigned IndexTypeQuals = Record[2];
5535 unsigned Idx = 3;
5536 llvm::APInt Size = ReadAPInt(Record, Idx);
5537 return Context.getConstantArrayType(ElementType, Size,
5538 ASM, IndexTypeQuals);
5539 }
5540
5541 case TYPE_INCOMPLETE_ARRAY: {
5542 QualType ElementType = readType(*Loc.F, Record, Idx);
5543 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5544 unsigned IndexTypeQuals = Record[2];
5545 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5546 }
5547
5548 case TYPE_VARIABLE_ARRAY: {
5549 QualType ElementType = readType(*Loc.F, Record, Idx);
5550 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5551 unsigned IndexTypeQuals = Record[2];
5552 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5553 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5554 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5555 ASM, IndexTypeQuals,
5556 SourceRange(LBLoc, RBLoc));
5557 }
5558
5559 case TYPE_VECTOR: {
5560 if (Record.size() != 3) {
5561 Error("incorrect encoding of vector type in AST file");
5562 return QualType();
5563 }
5564
5565 QualType ElementType = readType(*Loc.F, Record, Idx);
5566 unsigned NumElements = Record[1];
5567 unsigned VecKind = Record[2];
5568 return Context.getVectorType(ElementType, NumElements,
5569 (VectorType::VectorKind)VecKind);
5570 }
5571
5572 case TYPE_EXT_VECTOR: {
5573 if (Record.size() != 3) {
5574 Error("incorrect encoding of extended vector type in AST file");
5575 return QualType();
5576 }
5577
5578 QualType ElementType = readType(*Loc.F, Record, Idx);
5579 unsigned NumElements = Record[1];
5580 return Context.getExtVectorType(ElementType, NumElements);
5581 }
5582
5583 case TYPE_FUNCTION_NO_PROTO: {
5584 if (Record.size() != 6) {
5585 Error("incorrect encoding of no-proto function type");
5586 return QualType();
5587 }
5588 QualType ResultType = readType(*Loc.F, Record, Idx);
5589 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5590 (CallingConv)Record[4], Record[5]);
5591 return Context.getFunctionNoProtoType(ResultType, Info);
5592 }
5593
5594 case TYPE_FUNCTION_PROTO: {
5595 QualType ResultType = readType(*Loc.F, Record, Idx);
5596
5597 FunctionProtoType::ExtProtoInfo EPI;
5598 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5599 /*hasregparm*/ Record[2],
5600 /*regparm*/ Record[3],
5601 static_cast<CallingConv>(Record[4]),
5602 /*produces*/ Record[5]);
5603
5604 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005605
5606 EPI.Variadic = Record[Idx++];
5607 EPI.HasTrailingReturn = Record[Idx++];
5608 EPI.TypeQuals = Record[Idx++];
5609 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005610 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005611 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005612
5613 unsigned NumParams = Record[Idx++];
5614 SmallVector<QualType, 16> ParamTypes;
5615 for (unsigned I = 0; I != NumParams; ++I)
5616 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5617
John McCall18afab72016-03-01 00:49:02 +00005618 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5619 if (Idx != Record.size()) {
5620 for (unsigned I = 0; I != NumParams; ++I)
5621 ExtParameterInfos.push_back(
5622 FunctionProtoType::ExtParameterInfo
5623 ::getFromOpaqueValue(Record[Idx++]));
5624 EPI.ExtParameterInfos = ExtParameterInfos.data();
5625 }
5626
5627 assert(Idx == Record.size());
5628
Jordan Rose5c382722013-03-08 21:51:21 +00005629 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 }
5631
5632 case TYPE_UNRESOLVED_USING: {
5633 unsigned Idx = 0;
5634 return Context.getTypeDeclType(
5635 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5636 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005637
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 case TYPE_TYPEDEF: {
5639 if (Record.size() != 2) {
5640 Error("incorrect encoding of typedef type");
5641 return QualType();
5642 }
5643 unsigned Idx = 0;
5644 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5645 QualType Canonical = readType(*Loc.F, Record, Idx);
5646 if (!Canonical.isNull())
5647 Canonical = Context.getCanonicalType(Canonical);
5648 return Context.getTypedefType(Decl, Canonical);
5649 }
5650
5651 case TYPE_TYPEOF_EXPR:
5652 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5653
5654 case TYPE_TYPEOF: {
5655 if (Record.size() != 1) {
5656 Error("incorrect encoding of typeof(type) in AST file");
5657 return QualType();
5658 }
5659 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5660 return Context.getTypeOfType(UnderlyingType);
5661 }
5662
5663 case TYPE_DECLTYPE: {
5664 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5665 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5666 }
5667
5668 case TYPE_UNARY_TRANSFORM: {
5669 QualType BaseType = readType(*Loc.F, Record, Idx);
5670 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5671 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5672 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5673 }
5674
Richard Smith74aeef52013-04-26 16:15:35 +00005675 case TYPE_AUTO: {
5676 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005677 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005678 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005679 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005680 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005681
Richard Smith600b5262017-01-26 20:40:47 +00005682 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5683 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5684 QualType Deduced = readType(*Loc.F, Record, Idx);
5685 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5686 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5687 IsDependent);
5688 }
5689
Guy Benyei11169dd2012-12-18 14:30:41 +00005690 case TYPE_RECORD: {
5691 if (Record.size() != 2) {
5692 Error("incorrect encoding of record type");
5693 return QualType();
5694 }
5695 unsigned Idx = 0;
5696 bool IsDependent = Record[Idx++];
5697 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5698 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5699 QualType T = Context.getRecordType(RD);
5700 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5701 return T;
5702 }
5703
5704 case TYPE_ENUM: {
5705 if (Record.size() != 2) {
5706 Error("incorrect encoding of enum type");
5707 return QualType();
5708 }
5709 unsigned Idx = 0;
5710 bool IsDependent = Record[Idx++];
5711 QualType T
5712 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5713 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5714 return T;
5715 }
5716
5717 case TYPE_ATTRIBUTED: {
5718 if (Record.size() != 3) {
5719 Error("incorrect encoding of attributed type");
5720 return QualType();
5721 }
5722 QualType modifiedType = readType(*Loc.F, Record, Idx);
5723 QualType equivalentType = readType(*Loc.F, Record, Idx);
5724 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5725 return Context.getAttributedType(kind, modifiedType, equivalentType);
5726 }
5727
5728 case TYPE_PAREN: {
5729 if (Record.size() != 1) {
5730 Error("incorrect encoding of paren type");
5731 return QualType();
5732 }
5733 QualType InnerType = readType(*Loc.F, Record, Idx);
5734 return Context.getParenType(InnerType);
5735 }
5736
5737 case TYPE_PACK_EXPANSION: {
5738 if (Record.size() != 2) {
5739 Error("incorrect encoding of pack expansion type");
5740 return QualType();
5741 }
5742 QualType Pattern = readType(*Loc.F, Record, Idx);
5743 if (Pattern.isNull())
5744 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005745 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005746 if (Record[1])
5747 NumExpansions = Record[1] - 1;
5748 return Context.getPackExpansionType(Pattern, NumExpansions);
5749 }
5750
5751 case TYPE_ELABORATED: {
5752 unsigned Idx = 0;
5753 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5754 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5755 QualType NamedType = readType(*Loc.F, Record, Idx);
5756 return Context.getElaboratedType(Keyword, NNS, NamedType);
5757 }
5758
5759 case TYPE_OBJC_INTERFACE: {
5760 unsigned Idx = 0;
5761 ObjCInterfaceDecl *ItfD
5762 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5763 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5764 }
5765
Manman Rene6be26c2016-09-13 17:25:08 +00005766 case TYPE_OBJC_TYPE_PARAM: {
5767 unsigned Idx = 0;
5768 ObjCTypeParamDecl *Decl
5769 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5770 unsigned NumProtos = Record[Idx++];
5771 SmallVector<ObjCProtocolDecl*, 4> Protos;
5772 for (unsigned I = 0; I != NumProtos; ++I)
5773 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5774 return Context.getObjCTypeParamType(Decl, Protos);
5775 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 case TYPE_OBJC_OBJECT: {
5777 unsigned Idx = 0;
5778 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005779 unsigned NumTypeArgs = Record[Idx++];
5780 SmallVector<QualType, 4> TypeArgs;
5781 for (unsigned I = 0; I != NumTypeArgs; ++I)
5782 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 unsigned NumProtos = Record[Idx++];
5784 SmallVector<ObjCProtocolDecl*, 4> Protos;
5785 for (unsigned I = 0; I != NumProtos; ++I)
5786 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005787 bool IsKindOf = Record[Idx++];
5788 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 }
5790
5791 case TYPE_OBJC_OBJECT_POINTER: {
5792 unsigned Idx = 0;
5793 QualType Pointee = readType(*Loc.F, Record, Idx);
5794 return Context.getObjCObjectPointerType(Pointee);
5795 }
5796
5797 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5798 unsigned Idx = 0;
5799 QualType Parm = readType(*Loc.F, Record, Idx);
5800 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005801 return Context.getSubstTemplateTypeParmType(
5802 cast<TemplateTypeParmType>(Parm),
5803 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 }
5805
5806 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5807 unsigned Idx = 0;
5808 QualType Parm = readType(*Loc.F, Record, Idx);
5809 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5810 return Context.getSubstTemplateTypeParmPackType(
5811 cast<TemplateTypeParmType>(Parm),
5812 ArgPack);
5813 }
5814
5815 case TYPE_INJECTED_CLASS_NAME: {
5816 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5817 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5818 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5819 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005820 const Type *T = nullptr;
5821 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5822 if (const Type *Existing = DI->getTypeForDecl()) {
5823 T = Existing;
5824 break;
5825 }
5826 }
5827 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005828 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005829 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5830 DI->setTypeForDecl(T);
5831 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005832 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 }
5834
5835 case TYPE_TEMPLATE_TYPE_PARM: {
5836 unsigned Idx = 0;
5837 unsigned Depth = Record[Idx++];
5838 unsigned Index = Record[Idx++];
5839 bool Pack = Record[Idx++];
5840 TemplateTypeParmDecl *D
5841 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5842 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5843 }
5844
5845 case TYPE_DEPENDENT_NAME: {
5846 unsigned Idx = 0;
5847 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5848 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005849 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005850 QualType Canon = readType(*Loc.F, Record, Idx);
5851 if (!Canon.isNull())
5852 Canon = Context.getCanonicalType(Canon);
5853 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5854 }
5855
5856 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5857 unsigned Idx = 0;
5858 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5859 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005860 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 unsigned NumArgs = Record[Idx++];
5862 SmallVector<TemplateArgument, 8> Args;
5863 Args.reserve(NumArgs);
5864 while (NumArgs--)
5865 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5866 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005867 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 }
5869
5870 case TYPE_DEPENDENT_SIZED_ARRAY: {
5871 unsigned Idx = 0;
5872
5873 // ArrayType
5874 QualType ElementType = readType(*Loc.F, Record, Idx);
5875 ArrayType::ArraySizeModifier ASM
5876 = (ArrayType::ArraySizeModifier)Record[Idx++];
5877 unsigned IndexTypeQuals = Record[Idx++];
5878
5879 // DependentSizedArrayType
5880 Expr *NumElts = ReadExpr(*Loc.F);
5881 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5882
5883 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5884 IndexTypeQuals, Brackets);
5885 }
5886
5887 case TYPE_TEMPLATE_SPECIALIZATION: {
5888 unsigned Idx = 0;
5889 bool IsDependent = Record[Idx++];
5890 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5891 SmallVector<TemplateArgument, 8> Args;
5892 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5893 QualType Underlying = readType(*Loc.F, Record, Idx);
5894 QualType T;
5895 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005896 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005898 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005899 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5900 return T;
5901 }
5902
5903 case TYPE_ATOMIC: {
5904 if (Record.size() != 1) {
5905 Error("Incorrect encoding of atomic type");
5906 return QualType();
5907 }
5908 QualType ValueType = readType(*Loc.F, Record, Idx);
5909 return Context.getAtomicType(ValueType);
5910 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005911
Joey Goulye3c85de2016-12-01 11:30:49 +00005912 case TYPE_PIPE: {
5913 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005914 Error("Incorrect encoding of pipe type");
5915 return QualType();
5916 }
5917
5918 // Reading the pipe element type.
5919 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005920 unsigned ReadOnly = Record[1];
5921 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005922 }
5923
Guy Benyei11169dd2012-12-18 14:30:41 +00005924 }
5925 llvm_unreachable("Invalid TypeCode!");
5926}
5927
Richard Smith564417a2014-03-20 21:47:22 +00005928void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5929 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005930 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005931 const RecordData &Record, unsigned &Idx) {
5932 ExceptionSpecificationType EST =
5933 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005934 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005935 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005936 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005937 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005938 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005939 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005940 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005941 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005942 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5943 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005944 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005945 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005946 }
5947}
5948
Guy Benyei11169dd2012-12-18 14:30:41 +00005949class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005950 ModuleFile *F;
5951 ASTReader *Reader;
5952 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 unsigned &Idx;
5954
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005955 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005956 return Reader->ReadSourceLocation(*F, Record, Idx);
5957 }
5958
5959 TypeSourceInfo *GetTypeSourceInfo() {
5960 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5961 }
5962
5963 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5964 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 }
5966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005968 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005970 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005971
5972 // We want compile-time assurance that we've enumerated all of
5973 // these, so unfortunately we have to declare them first, then
5974 // define them out-of-line.
5975#define ABSTRACT_TYPELOC(CLASS, PARENT)
5976#define TYPELOC(CLASS, PARENT) \
5977 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5978#include "clang/AST/TypeLocNodes.def"
5979
5980 void VisitFunctionTypeLoc(FunctionTypeLoc);
5981 void VisitArrayTypeLoc(ArrayTypeLoc);
5982};
5983
5984void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5985 // nothing to do
5986}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005987
Guy Benyei11169dd2012-12-18 14:30:41 +00005988void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005989 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005990 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005991 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5992 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5993 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5994 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005995 }
5996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005999 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006000}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006001
Guy Benyei11169dd2012-12-18 14:30:41 +00006002void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006003 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006004}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006005
Reid Kleckner8a365022013-06-24 17:51:48 +00006006void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6007 // nothing to do
6008}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006009
Reid Kleckner0503a872013-12-05 01:23:43 +00006010void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6011 // nothing to do
6012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006015 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006016}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006017
Guy Benyei11169dd2012-12-18 14:30:41 +00006018void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006019 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006020}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006021
Guy Benyei11169dd2012-12-18 14:30:41 +00006022void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006023 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006024}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006025
Guy Benyei11169dd2012-12-18 14:30:41 +00006026void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006027 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006028 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006029}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006030
Guy Benyei11169dd2012-12-18 14:30:41 +00006031void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006032 TL.setLBracketLoc(ReadSourceLocation());
6033 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006034 if (Record[Idx++])
6035 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 else
Craig Toppera13603a2014-05-22 05:54:18 +00006037 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006038}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006039
Guy Benyei11169dd2012-12-18 14:30:41 +00006040void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6041 VisitArrayTypeLoc(TL);
6042}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006043
Guy Benyei11169dd2012-12-18 14:30:41 +00006044void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6045 VisitArrayTypeLoc(TL);
6046}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006047
Guy Benyei11169dd2012-12-18 14:30:41 +00006048void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6049 VisitArrayTypeLoc(TL);
6050}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006051
Guy Benyei11169dd2012-12-18 14:30:41 +00006052void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6053 DependentSizedArrayTypeLoc TL) {
6054 VisitArrayTypeLoc(TL);
6055}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6058 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006059 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006060}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006061
Guy Benyei11169dd2012-12-18 14:30:41 +00006062void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006063 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006064}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006065
Guy Benyei11169dd2012-12-18 14:30:41 +00006066void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006067 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006068}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006069
Guy Benyei11169dd2012-12-18 14:30:41 +00006070void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006071 TL.setLocalRangeBegin(ReadSourceLocation());
6072 TL.setLParenLoc(ReadSourceLocation());
6073 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006074 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6075 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006076 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006077 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006078 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 }
6080}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6083 VisitFunctionTypeLoc(TL);
6084}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6087 VisitFunctionTypeLoc(TL);
6088}
6089void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006090 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006091}
6092void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006093 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006094}
6095void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006096 TL.setTypeofLoc(ReadSourceLocation());
6097 TL.setLParenLoc(ReadSourceLocation());
6098 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006099}
6100void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006101 TL.setTypeofLoc(ReadSourceLocation());
6102 TL.setLParenLoc(ReadSourceLocation());
6103 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006104 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006105}
6106void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006107 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006108}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006109
Guy Benyei11169dd2012-12-18 14:30:41 +00006110void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006111 TL.setKWLoc(ReadSourceLocation());
6112 TL.setLParenLoc(ReadSourceLocation());
6113 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006114 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006115}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006116
Guy Benyei11169dd2012-12-18 14:30:41 +00006117void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006118 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006119}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006120
Richard Smith600b5262017-01-26 20:40:47 +00006121void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6122 DeducedTemplateSpecializationTypeLoc TL) {
6123 TL.setTemplateNameLoc(ReadSourceLocation());
6124}
6125
Guy Benyei11169dd2012-12-18 14:30:41 +00006126void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006127 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006128}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006129
Guy Benyei11169dd2012-12-18 14:30:41 +00006130void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006131 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006133
Guy Benyei11169dd2012-12-18 14:30:41 +00006134void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006135 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 if (TL.hasAttrOperand()) {
6137 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006138 range.setBegin(ReadSourceLocation());
6139 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 TL.setAttrOperandParensRange(range);
6141 }
6142 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006143 if (Record[Idx++])
6144 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 else
Craig Toppera13603a2014-05-22 05:54:18 +00006146 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006148 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006149}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006150
Guy Benyei11169dd2012-12-18 14:30:41 +00006151void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006152 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006154
Guy Benyei11169dd2012-12-18 14:30:41 +00006155void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6156 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006157 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006158}
6159void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6160 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006161 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006162}
6163void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6164 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006165 TL.setTemplateKeywordLoc(ReadSourceLocation());
6166 TL.setTemplateNameLoc(ReadSourceLocation());
6167 TL.setLAngleLoc(ReadSourceLocation());
6168 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006170 TL.setArgLocInfo(
6171 i,
6172 Reader->GetTemplateArgumentLocInfo(
6173 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006174}
6175void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006176 TL.setLParenLoc(ReadSourceLocation());
6177 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006178}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006179
Guy Benyei11169dd2012-12-18 14:30:41 +00006180void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006181 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006182 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006184
Guy Benyei11169dd2012-12-18 14:30:41 +00006185void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006186 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006187}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006188
Guy Benyei11169dd2012-12-18 14:30:41 +00006189void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006190 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006191 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006192 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006193}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006194
Guy Benyei11169dd2012-12-18 14:30:41 +00006195void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6196 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006197 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006198 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006199 TL.setTemplateKeywordLoc(ReadSourceLocation());
6200 TL.setTemplateNameLoc(ReadSourceLocation());
6201 TL.setLAngleLoc(ReadSourceLocation());
6202 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006204 TL.setArgLocInfo(
6205 I,
6206 Reader->GetTemplateArgumentLocInfo(
6207 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006208}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006209
Guy Benyei11169dd2012-12-18 14:30:41 +00006210void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006211 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006212}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006213
Guy Benyei11169dd2012-12-18 14:30:41 +00006214void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006215 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006216}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006217
Manman Rene6be26c2016-09-13 17:25:08 +00006218void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6219 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006220 TL.setProtocolLAngleLoc(ReadSourceLocation());
6221 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006222 }
6223 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006224 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006225}
6226
Guy Benyei11169dd2012-12-18 14:30:41 +00006227void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006228 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006229 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6230 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006231 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006232 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006233 TL.setProtocolLAngleLoc(ReadSourceLocation());
6234 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006236 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006237}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006238
Guy Benyei11169dd2012-12-18 14:30:41 +00006239void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006240 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006241}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006242
Guy Benyei11169dd2012-12-18 14:30:41 +00006243void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006244 TL.setKWLoc(ReadSourceLocation());
6245 TL.setLParenLoc(ReadSourceLocation());
6246 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006247}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006248
Xiuli Pan9c14e282016-01-09 12:53:17 +00006249void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006250 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006251}
Guy Benyei11169dd2012-12-18 14:30:41 +00006252
David L. Jonesbe1557a2016-12-21 00:17:49 +00006253TypeSourceInfo *
6254ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6255 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 QualType InfoTy = readType(F, Record, Idx);
6257 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006258 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006259
6260 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006261 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6263 TLR.Visit(TL);
6264 return TInfo;
6265}
6266
6267QualType ASTReader::GetType(TypeID ID) {
6268 unsigned FastQuals = ID & Qualifiers::FastMask;
6269 unsigned Index = ID >> Qualifiers::FastWidth;
6270
6271 if (Index < NUM_PREDEF_TYPE_IDS) {
6272 QualType T;
6273 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006274 case PREDEF_TYPE_NULL_ID:
6275 return QualType();
6276 case PREDEF_TYPE_VOID_ID:
6277 T = Context.VoidTy;
6278 break;
6279 case PREDEF_TYPE_BOOL_ID:
6280 T = Context.BoolTy;
6281 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006282
6283 case PREDEF_TYPE_CHAR_U_ID:
6284 case PREDEF_TYPE_CHAR_S_ID:
6285 // FIXME: Check that the signedness of CharTy is correct!
6286 T = Context.CharTy;
6287 break;
6288
Alexey Baderbdf7c842015-09-15 12:18:29 +00006289 case PREDEF_TYPE_UCHAR_ID:
6290 T = Context.UnsignedCharTy;
6291 break;
6292 case PREDEF_TYPE_USHORT_ID:
6293 T = Context.UnsignedShortTy;
6294 break;
6295 case PREDEF_TYPE_UINT_ID:
6296 T = Context.UnsignedIntTy;
6297 break;
6298 case PREDEF_TYPE_ULONG_ID:
6299 T = Context.UnsignedLongTy;
6300 break;
6301 case PREDEF_TYPE_ULONGLONG_ID:
6302 T = Context.UnsignedLongLongTy;
6303 break;
6304 case PREDEF_TYPE_UINT128_ID:
6305 T = Context.UnsignedInt128Ty;
6306 break;
6307 case PREDEF_TYPE_SCHAR_ID:
6308 T = Context.SignedCharTy;
6309 break;
6310 case PREDEF_TYPE_WCHAR_ID:
6311 T = Context.WCharTy;
6312 break;
6313 case PREDEF_TYPE_SHORT_ID:
6314 T = Context.ShortTy;
6315 break;
6316 case PREDEF_TYPE_INT_ID:
6317 T = Context.IntTy;
6318 break;
6319 case PREDEF_TYPE_LONG_ID:
6320 T = Context.LongTy;
6321 break;
6322 case PREDEF_TYPE_LONGLONG_ID:
6323 T = Context.LongLongTy;
6324 break;
6325 case PREDEF_TYPE_INT128_ID:
6326 T = Context.Int128Ty;
6327 break;
6328 case PREDEF_TYPE_HALF_ID:
6329 T = Context.HalfTy;
6330 break;
6331 case PREDEF_TYPE_FLOAT_ID:
6332 T = Context.FloatTy;
6333 break;
6334 case PREDEF_TYPE_DOUBLE_ID:
6335 T = Context.DoubleTy;
6336 break;
6337 case PREDEF_TYPE_LONGDOUBLE_ID:
6338 T = Context.LongDoubleTy;
6339 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006340 case PREDEF_TYPE_FLOAT128_ID:
6341 T = Context.Float128Ty;
6342 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006343 case PREDEF_TYPE_OVERLOAD_ID:
6344 T = Context.OverloadTy;
6345 break;
6346 case PREDEF_TYPE_BOUND_MEMBER:
6347 T = Context.BoundMemberTy;
6348 break;
6349 case PREDEF_TYPE_PSEUDO_OBJECT:
6350 T = Context.PseudoObjectTy;
6351 break;
6352 case PREDEF_TYPE_DEPENDENT_ID:
6353 T = Context.DependentTy;
6354 break;
6355 case PREDEF_TYPE_UNKNOWN_ANY:
6356 T = Context.UnknownAnyTy;
6357 break;
6358 case PREDEF_TYPE_NULLPTR_ID:
6359 T = Context.NullPtrTy;
6360 break;
6361 case PREDEF_TYPE_CHAR16_ID:
6362 T = Context.Char16Ty;
6363 break;
6364 case PREDEF_TYPE_CHAR32_ID:
6365 T = Context.Char32Ty;
6366 break;
6367 case PREDEF_TYPE_OBJC_ID:
6368 T = Context.ObjCBuiltinIdTy;
6369 break;
6370 case PREDEF_TYPE_OBJC_CLASS:
6371 T = Context.ObjCBuiltinClassTy;
6372 break;
6373 case PREDEF_TYPE_OBJC_SEL:
6374 T = Context.ObjCBuiltinSelTy;
6375 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006376#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6377 case PREDEF_TYPE_##Id##_ID: \
6378 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006379 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006380#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006381 case PREDEF_TYPE_SAMPLER_ID:
6382 T = Context.OCLSamplerTy;
6383 break;
6384 case PREDEF_TYPE_EVENT_ID:
6385 T = Context.OCLEventTy;
6386 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006387 case PREDEF_TYPE_CLK_EVENT_ID:
6388 T = Context.OCLClkEventTy;
6389 break;
6390 case PREDEF_TYPE_QUEUE_ID:
6391 T = Context.OCLQueueTy;
6392 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006393 case PREDEF_TYPE_RESERVE_ID_ID:
6394 T = Context.OCLReserveIDTy;
6395 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006396 case PREDEF_TYPE_AUTO_DEDUCT:
6397 T = Context.getAutoDeductType();
6398 break;
6399
6400 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6401 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 break;
6403
6404 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6405 T = Context.ARCUnbridgedCastTy;
6406 break;
6407
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 case PREDEF_TYPE_BUILTIN_FN:
6409 T = Context.BuiltinFnTy;
6410 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006411
6412 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6413 T = Context.OMPArraySectionTy;
6414 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 }
6416
6417 assert(!T.isNull() && "Unknown predefined type");
6418 return T.withFastQualifiers(FastQuals);
6419 }
6420
6421 Index -= NUM_PREDEF_TYPE_IDS;
6422 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6423 if (TypesLoaded[Index].isNull()) {
6424 TypesLoaded[Index] = readTypeRecord(Index);
6425 if (TypesLoaded[Index].isNull())
6426 return QualType();
6427
6428 TypesLoaded[Index]->setFromAST();
6429 if (DeserializationListener)
6430 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6431 TypesLoaded[Index]);
6432 }
6433
6434 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6435}
6436
6437QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6438 return GetType(getGlobalTypeID(F, LocalID));
6439}
6440
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006441serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006442ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6443 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6444 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006445
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6447 return LocalID;
6448
Richard Smith37a93df2017-02-18 00:32:02 +00006449 if (!F.ModuleOffsetMap.empty())
6450 ReadModuleOffsetMap(F);
6451
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6453 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6454 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006455
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 unsigned GlobalIndex = LocalIndex + I->second;
6457 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6458}
6459
6460TemplateArgumentLocInfo
6461ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6462 TemplateArgument::ArgKind Kind,
6463 const RecordData &Record,
6464 unsigned &Index) {
6465 switch (Kind) {
6466 case TemplateArgument::Expression:
6467 return ReadExpr(F);
6468 case TemplateArgument::Type:
6469 return GetTypeSourceInfo(F, Record, Index);
6470 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006471 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 Index);
6473 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6474 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6475 SourceLocation());
6476 }
6477 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006478 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 Index);
6480 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6481 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006482 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 EllipsisLoc);
6484 }
6485 case TemplateArgument::Null:
6486 case TemplateArgument::Integral:
6487 case TemplateArgument::Declaration:
6488 case TemplateArgument::NullPtr:
6489 case TemplateArgument::Pack:
6490 // FIXME: Is this right?
6491 return TemplateArgumentLocInfo();
6492 }
6493 llvm_unreachable("unexpected template argument loc");
6494}
6495
6496TemplateArgumentLoc
6497ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6498 const RecordData &Record, unsigned &Index) {
6499 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6500
6501 if (Arg.getKind() == TemplateArgument::Expression) {
6502 if (Record[Index++]) // bool InfoHasSameExpr.
6503 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6504 }
6505 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6506 Record, Index));
6507}
6508
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006509const ASTTemplateArgumentListInfo*
6510ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6511 const RecordData &Record,
6512 unsigned &Index) {
6513 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6514 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6515 unsigned NumArgsAsWritten = Record[Index++];
6516 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6517 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6518 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6519 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6520}
6521
Guy Benyei11169dd2012-12-18 14:30:41 +00006522Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6523 return GetDecl(ID);
6524}
6525
Richard Smith053f6c62014-05-16 23:01:30 +00006526void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006527 if (NumCurrentElementsDeserializing) {
6528 // We arrange to not care about the complete redeclaration chain while we're
6529 // deserializing. Just remember that the AST has marked this one as complete
6530 // but that it's not actually complete yet, so we know we still need to
6531 // complete it later.
6532 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6533 return;
6534 }
6535
Richard Smith053f6c62014-05-16 23:01:30 +00006536 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6537
Richard Smith053f6c62014-05-16 23:01:30 +00006538 // If this is a named declaration, complete it by looking it up
6539 // within its context.
6540 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006541 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006542 // all mergeable entities within it.
6543 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6544 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6545 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006546 if (!getContext().getLangOpts().CPlusPlus &&
6547 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006548 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006549 // the identifier instead. (For C++ modules, we don't store decls
6550 // in the serialized identifier table, so we do the lookup in the TU.)
6551 auto *II = Name.getAsIdentifierInfo();
6552 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006553 if (II->isOutOfDate())
6554 updateOutOfDateIdentifier(*II);
6555 } else
6556 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006557 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006558 // Find all declarations of this kind from the relevant context.
6559 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6560 auto *DC = cast<DeclContext>(DCDecl);
6561 SmallVector<Decl*, 8> Decls;
6562 FindExternalLexicalDecls(
6563 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6564 }
Richard Smith053f6c62014-05-16 23:01:30 +00006565 }
6566 }
Richard Smith50895422015-01-31 03:04:55 +00006567
6568 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6569 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6570 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6571 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6572 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6573 if (auto *Template = FD->getPrimaryTemplate())
6574 Template->LoadLazySpecializations();
6575 }
Richard Smith053f6c62014-05-16 23:01:30 +00006576}
6577
Richard Smithc2bb8182015-03-24 06:36:48 +00006578CXXCtorInitializer **
6579ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6580 RecordLocation Loc = getLocalBitOffset(Offset);
6581 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6582 SavedStreamPosition SavedPosition(Cursor);
6583 Cursor.JumpToBit(Loc.Offset);
6584 ReadingKindTracker ReadingKind(Read_Decl, *this);
6585
6586 RecordData Record;
6587 unsigned Code = Cursor.ReadCode();
6588 unsigned RecCode = Cursor.readRecord(Code, Record);
6589 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6590 Error("malformed AST file: missing C++ ctor initializers");
6591 return nullptr;
6592 }
6593
6594 unsigned Idx = 0;
6595 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6596}
6597
Guy Benyei11169dd2012-12-18 14:30:41 +00006598CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6599 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006600 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 SavedStreamPosition SavedPosition(Cursor);
6602 Cursor.JumpToBit(Loc.Offset);
6603 ReadingKindTracker ReadingKind(Read_Decl, *this);
6604 RecordData Record;
6605 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006606 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006608 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006609 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 }
6611
6612 unsigned Idx = 0;
6613 unsigned NumBases = Record[Idx++];
6614 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6615 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6616 for (unsigned I = 0; I != NumBases; ++I)
6617 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6618 return Bases;
6619}
6620
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006621serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006622ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6623 if (LocalID < NUM_PREDEF_DECL_IDS)
6624 return LocalID;
6625
Richard Smith37a93df2017-02-18 00:32:02 +00006626 if (!F.ModuleOffsetMap.empty())
6627 ReadModuleOffsetMap(F);
6628
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6630 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6631 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 return LocalID + I->second;
6634}
6635
6636bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6637 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006638 // Predefined decls aren't from any module.
6639 if (ID < NUM_PREDEF_DECL_IDS)
6640 return false;
6641
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006642 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006643 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006644}
6645
Douglas Gregor9f782892013-01-21 15:25:38 +00006646ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006647 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006648 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6650 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6651 return I->second;
6652}
6653
6654SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6655 if (ID < NUM_PREDEF_DECL_IDS)
6656 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006657
Guy Benyei11169dd2012-12-18 14:30:41 +00006658 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6659
6660 if (Index > DeclsLoaded.size()) {
6661 Error("declaration ID out-of-range for AST file");
6662 return SourceLocation();
6663 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006664
Guy Benyei11169dd2012-12-18 14:30:41 +00006665 if (Decl *D = DeclsLoaded[Index])
6666 return D->getLocation();
6667
Richard Smithcb34bd32016-03-27 07:28:06 +00006668 SourceLocation Loc;
6669 DeclCursorForID(ID, Loc);
6670 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006671}
6672
Richard Smithfe620d22015-03-05 23:24:12 +00006673static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6674 switch (ID) {
6675 case PREDEF_DECL_NULL_ID:
6676 return nullptr;
6677
6678 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6679 return Context.getTranslationUnitDecl();
6680
6681 case PREDEF_DECL_OBJC_ID_ID:
6682 return Context.getObjCIdDecl();
6683
6684 case PREDEF_DECL_OBJC_SEL_ID:
6685 return Context.getObjCSelDecl();
6686
6687 case PREDEF_DECL_OBJC_CLASS_ID:
6688 return Context.getObjCClassDecl();
6689
6690 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6691 return Context.getObjCProtocolDecl();
6692
6693 case PREDEF_DECL_INT_128_ID:
6694 return Context.getInt128Decl();
6695
6696 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6697 return Context.getUInt128Decl();
6698
6699 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6700 return Context.getObjCInstanceTypeDecl();
6701
6702 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6703 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006704
Richard Smith9b88a4c2015-07-27 05:40:23 +00006705 case PREDEF_DECL_VA_LIST_TAG:
6706 return Context.getVaListTagDecl();
6707
Charles Davisc7d5c942015-09-17 20:55:33 +00006708 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6709 return Context.getBuiltinMSVaListDecl();
6710
Richard Smithf19e1272015-03-07 00:04:49 +00006711 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6712 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006713
6714 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6715 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006716
6717 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6718 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006719
6720 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6721 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006722
6723 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6724 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006725 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006726 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006727}
6728
Richard Smithcd45dbc2014-04-19 03:48:30 +00006729Decl *ASTReader::GetExistingDecl(DeclID ID) {
6730 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006731 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6732 if (D) {
6733 // Track that we have merged the declaration with ID \p ID into the
6734 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006735 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006736 if (Merged.empty())
6737 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 }
Richard Smithfe620d22015-03-05 23:24:12 +00006739 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006741
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6743
6744 if (Index >= DeclsLoaded.size()) {
6745 assert(0 && "declaration ID out-of-range for AST file");
6746 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006747 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006749
6750 return DeclsLoaded[Index];
6751}
6752
6753Decl *ASTReader::GetDecl(DeclID ID) {
6754 if (ID < NUM_PREDEF_DECL_IDS)
6755 return GetExistingDecl(ID);
6756
6757 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6758
6759 if (Index >= DeclsLoaded.size()) {
6760 assert(0 && "declaration ID out-of-range for AST file");
6761 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006762 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006763 }
6764
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 if (!DeclsLoaded[Index]) {
6766 ReadDeclRecord(ID);
6767 if (DeserializationListener)
6768 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6769 }
6770
6771 return DeclsLoaded[Index];
6772}
6773
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006774DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 DeclID GlobalID) {
6776 if (GlobalID < NUM_PREDEF_DECL_IDS)
6777 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006778
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6780 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6781 ModuleFile *Owner = I->second;
6782
6783 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6784 = M.GlobalToLocalDeclIDs.find(Owner);
6785 if (Pos == M.GlobalToLocalDeclIDs.end())
6786 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006787
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 return GlobalID - Owner->BaseDeclID + Pos->second;
6789}
6790
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006791serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006792 const RecordData &Record,
6793 unsigned &Idx) {
6794 if (Idx >= Record.size()) {
6795 Error("Corrupted AST file");
6796 return 0;
6797 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006798
Guy Benyei11169dd2012-12-18 14:30:41 +00006799 return getGlobalDeclID(F, Record[Idx++]);
6800}
6801
6802/// \brief Resolve the offset of a statement into a statement.
6803///
6804/// This operation will read a new statement from the external
6805/// source each time it is called, and is meant to be used via a
6806/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6807Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6808 // Switch case IDs are per Decl.
6809 ClearSwitchCaseIDs();
6810
6811 // Offset here is a global offset across the entire chain.
6812 RecordLocation Loc = getLocalBitOffset(Offset);
6813 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6814 return ReadStmtFromStream(*Loc.F);
6815}
6816
Richard Smith3cb15722015-08-05 22:41:45 +00006817void ASTReader::FindExternalLexicalDecls(
6818 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6819 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006820 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6821
Richard Smith9ccdd932015-08-06 22:14:12 +00006822 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006823 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6824 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6825 auto K = (Decl::Kind)+LexicalDecls[I];
6826 if (!IsKindWeWant(K))
6827 continue;
6828
6829 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6830
6831 // Don't add predefined declarations to the lexical context more
6832 // than once.
6833 if (ID < NUM_PREDEF_DECL_IDS) {
6834 if (PredefsVisited[ID])
6835 continue;
6836
6837 PredefsVisited[ID] = true;
6838 }
6839
6840 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006841 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006842 if (!DC->isDeclInLexicalTraversal(D))
6843 Decls.push_back(D);
6844 }
6845 }
6846 };
6847
6848 if (isa<TranslationUnitDecl>(DC)) {
6849 for (auto Lexical : TULexicalDecls)
6850 Visit(Lexical.first, Lexical.second);
6851 } else {
6852 auto I = LexicalDecls.find(DC);
6853 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006854 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006855 }
6856
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006858}
6859
6860namespace {
6861
6862class DeclIDComp {
6863 ASTReader &Reader;
6864 ModuleFile &Mod;
6865
6866public:
6867 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6868
6869 bool operator()(LocalDeclID L, LocalDeclID R) const {
6870 SourceLocation LHS = getLocation(L);
6871 SourceLocation RHS = getLocation(R);
6872 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6873 }
6874
6875 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6876 SourceLocation RHS = getLocation(R);
6877 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6878 }
6879
6880 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6881 SourceLocation LHS = getLocation(L);
6882 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6883 }
6884
6885 SourceLocation getLocation(LocalDeclID ID) const {
6886 return Reader.getSourceManager().getFileLoc(
6887 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6888 }
6889};
6890
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006891} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006892
6893void ASTReader::FindFileRegionDecls(FileID File,
6894 unsigned Offset, unsigned Length,
6895 SmallVectorImpl<Decl *> &Decls) {
6896 SourceManager &SM = getSourceManager();
6897
6898 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6899 if (I == FileDeclIDs.end())
6900 return;
6901
6902 FileDeclsInfo &DInfo = I->second;
6903 if (DInfo.Decls.empty())
6904 return;
6905
6906 SourceLocation
6907 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6908 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6909
6910 DeclIDComp DIDComp(*this, *DInfo.Mod);
6911 ArrayRef<serialization::LocalDeclID>::iterator
6912 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6913 BeginLoc, DIDComp);
6914 if (BeginIt != DInfo.Decls.begin())
6915 --BeginIt;
6916
6917 // If we are pointing at a top-level decl inside an objc container, we need
6918 // to backtrack until we find it otherwise we will fail to report that the
6919 // region overlaps with an objc container.
6920 while (BeginIt != DInfo.Decls.begin() &&
6921 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6922 ->isTopLevelDeclInObjCContainer())
6923 --BeginIt;
6924
6925 ArrayRef<serialization::LocalDeclID>::iterator
6926 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6927 EndLoc, DIDComp);
6928 if (EndIt != DInfo.Decls.end())
6929 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006930
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 for (ArrayRef<serialization::LocalDeclID>::iterator
6932 DIt = BeginIt; DIt != EndIt; ++DIt)
6933 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6934}
6935
Richard Smith9ce12e32013-02-07 03:30:24 +00006936bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006937ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6938 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006939 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 "DeclContext has no visible decls in storage");
6941 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006942 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006943
Richard Smithd88a7f12015-09-01 20:35:42 +00006944 auto It = Lookups.find(DC);
6945 if (It == Lookups.end())
6946 return false;
6947
Richard Smith8c913ec2014-08-14 02:21:01 +00006948 Deserializing LookupResults(this);
6949
Richard Smithd88a7f12015-09-01 20:35:42 +00006950 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006952 for (DeclID ID : It->second.Table.find(Name)) {
6953 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6954 if (ND->getDeclName() == Name)
6955 Decls.push_back(ND);
6956 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006957
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 ++NumVisibleDeclContextsRead;
6959 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006960 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006961}
6962
Guy Benyei11169dd2012-12-18 14:30:41 +00006963void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6964 if (!DC->hasExternalVisibleStorage())
6965 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006966
6967 auto It = Lookups.find(DC);
6968 assert(It != Lookups.end() &&
6969 "have external visible storage but no lookup tables");
6970
Craig Topper79be4cd2013-07-05 04:33:53 +00006971 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006972
Richard Smithd88a7f12015-09-01 20:35:42 +00006973 for (DeclID ID : It->second.Table.findAll()) {
6974 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6975 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 }
6977
Guy Benyei11169dd2012-12-18 14:30:41 +00006978 ++NumVisibleDeclContextsRead;
6979
Craig Topper79be4cd2013-07-05 04:33:53 +00006980 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6982 }
6983 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6984}
6985
Richard Smithd88a7f12015-09-01 20:35:42 +00006986const serialization::reader::DeclContextLookupTable *
6987ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6988 auto I = Lookups.find(Primary);
6989 return I == Lookups.end() ? nullptr : &I->second;
6990}
6991
Guy Benyei11169dd2012-12-18 14:30:41 +00006992/// \brief Under non-PCH compilation the consumer receives the objc methods
6993/// before receiving the implementation, and codegen depends on this.
6994/// We simulate this by deserializing and passing to consumer the methods of the
6995/// implementation before passing the deserialized implementation decl.
6996static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6997 ASTConsumer *Consumer) {
6998 assert(ImplD && Consumer);
6999
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007000 for (auto *I : ImplD->methods())
7001 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007002
7003 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7004}
7005
7006void ASTReader::PassInterestingDeclsToConsumer() {
7007 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00007008
7009 if (PassingDeclsToConsumer)
7010 return;
7011
7012 // Guard variable to avoid recursively redoing the process of passing
7013 // decls to consumer.
7014 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7015 true);
7016
Richard Smith9e2341d2015-03-23 03:25:59 +00007017 // Ensure that we've loaded all potentially-interesting declarations
7018 // that need to be eagerly loaded.
7019 for (auto ID : EagerlyDeserializedDecls)
7020 GetDecl(ID);
7021 EagerlyDeserializedDecls.clear();
7022
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 while (!InterestingDecls.empty()) {
7024 Decl *D = InterestingDecls.front();
7025 InterestingDecls.pop_front();
7026
7027 PassInterestingDeclToConsumer(D);
7028 }
7029}
7030
7031void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7032 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7033 PassObjCImplDeclToConsumer(ImplD, Consumer);
7034 else
7035 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7036}
7037
7038void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7039 this->Consumer = Consumer;
7040
Richard Smith9e2341d2015-03-23 03:25:59 +00007041 if (Consumer)
7042 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007043
7044 if (DeserializationListener)
7045 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007046}
7047
7048void ASTReader::PrintStats() {
7049 std::fprintf(stderr, "*** AST File Statistics:\n");
7050
7051 unsigned NumTypesLoaded
7052 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7053 QualType());
7054 unsigned NumDeclsLoaded
7055 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007056 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007057 unsigned NumIdentifiersLoaded
7058 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7059 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007060 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007061 unsigned NumMacrosLoaded
7062 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7063 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007064 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 unsigned NumSelectorsLoaded
7066 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7067 SelectorsLoaded.end(),
7068 Selector());
7069
7070 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7071 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7072 NumSLocEntriesRead, TotalNumSLocEntries,
7073 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7074 if (!TypesLoaded.empty())
7075 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7076 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7077 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7078 if (!DeclsLoaded.empty())
7079 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7080 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7081 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7082 if (!IdentifiersLoaded.empty())
7083 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7084 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7085 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7086 if (!MacrosLoaded.empty())
7087 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7088 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7089 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7090 if (!SelectorsLoaded.empty())
7091 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7092 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7093 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7094 if (TotalNumStatements)
7095 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7096 NumStatementsRead, TotalNumStatements,
7097 ((float)NumStatementsRead/TotalNumStatements * 100));
7098 if (TotalNumMacros)
7099 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7100 NumMacrosRead, TotalNumMacros,
7101 ((float)NumMacrosRead/TotalNumMacros * 100));
7102 if (TotalLexicalDeclContexts)
7103 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7104 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7105 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7106 * 100));
7107 if (TotalVisibleDeclContexts)
7108 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7109 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7110 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7111 * 100));
7112 if (TotalNumMethodPoolEntries) {
7113 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7114 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7115 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7116 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007118 if (NumMethodPoolLookups) {
7119 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7120 NumMethodPoolHits, NumMethodPoolLookups,
7121 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7122 }
7123 if (NumMethodPoolTableLookups) {
7124 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7125 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7126 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7127 * 100.0));
7128 }
7129
Douglas Gregor00a50f72013-01-25 00:38:33 +00007130 if (NumIdentifierLookupHits) {
7131 std::fprintf(stderr,
7132 " %u / %u identifier table lookups succeeded (%f%%)\n",
7133 NumIdentifierLookupHits, NumIdentifierLookups,
7134 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7135 }
7136
Douglas Gregore060e572013-01-25 01:03:03 +00007137 if (GlobalIndex) {
7138 std::fprintf(stderr, "\n");
7139 GlobalIndex->printStats();
7140 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007141
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 std::fprintf(stderr, "\n");
7143 dump();
7144 std::fprintf(stderr, "\n");
7145}
7146
7147template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007148LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007149dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007150 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 InitialCapacity> &Map) {
7152 if (Map.begin() == Map.end())
7153 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007154
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7156 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007157 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 I != IEnd; ++I) {
7159 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7160 << "\n";
7161 }
7162}
7163
Yaron Kerencdae9412016-01-29 19:38:18 +00007164LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7166 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7167 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7168 dumpModuleIDMap("Global type map", GlobalTypeMap);
7169 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7170 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7171 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7172 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7173 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007174 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007176
Guy Benyei11169dd2012-12-18 14:30:41 +00007177 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007178 for (ModuleFile &M : ModuleMgr)
7179 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007180}
7181
7182/// Return the amount of memory used by memory buffers, breaking down
7183/// by heap-backed versus mmap'ed memory.
7184void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007185 for (ModuleFile &I : ModuleMgr) {
7186 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 size_t bytes = buf->getBufferSize();
7188 switch (buf->getBufferKind()) {
7189 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7190 sizes.malloc_bytes += bytes;
7191 break;
7192 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7193 sizes.mmap_bytes += bytes;
7194 break;
7195 }
7196 }
7197 }
7198}
7199
7200void ASTReader::InitializeSema(Sema &S) {
7201 SemaObj = &S;
7202 S.addExternalSource(this);
7203
7204 // Makes sure any declarations that were deserialized "too early"
7205 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007206 for (uint64_t ID : PreloadedDeclIDs) {
7207 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7208 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007210 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007211
Richard Smith3d8e97e2013-10-18 06:54:39 +00007212 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007213 if (!FPPragmaOptions.empty()) {
7214 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7215 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7216 }
7217
Yaxun Liu5b746652016-12-18 05:18:55 +00007218 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7219 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7220 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007221
7222 UpdateSema();
7223}
7224
7225void ASTReader::UpdateSema() {
7226 assert(SemaObj && "no Sema to update");
7227
7228 // Load the offsets of the declarations that Sema references.
7229 // They will be lazily deserialized when needed.
7230 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007231 assert(SemaDeclRefs.size() % 3 == 0);
7232 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007233 if (!SemaObj->StdNamespace)
7234 SemaObj->StdNamespace = SemaDeclRefs[I];
7235 if (!SemaObj->StdBadAlloc)
7236 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007237 if (!SemaObj->StdAlignValT)
7238 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007239 }
7240 SemaDeclRefs.clear();
7241 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007242
Nico Weber779355f2016-03-02 23:22:00 +00007243 // Update the state of pragmas. Use the same API as if we had encountered the
7244 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007245 if(OptimizeOffPragmaLocation.isValid())
7246 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007247 if (PragmaMSStructState != -1)
7248 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007249 if (PointersToMembersPragmaLocation.isValid()) {
7250 SemaObj->ActOnPragmaMSPointersToMembers(
7251 (LangOptions::PragmaMSPointersToMembersKind)
7252 PragmaMSPointersToMembersState,
7253 PointersToMembersPragmaLocation);
7254 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007255 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007256}
7257
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007258IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 // Note that we are loading an identifier.
7260 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007261
Douglas Gregor7211ac12013-01-25 23:32:03 +00007262 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007263 NumIdentifierLookups,
7264 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007265
7266 // We don't need to do identifier table lookups in C++ modules (we preload
7267 // all interesting declarations, and don't need to use the scope for name
7268 // lookups). Perform the lookup in PCH files, though, since we don't build
7269 // a complete initial identifier table if we're carrying on from a PCH.
7270 if (Context.getLangOpts().CPlusPlus) {
7271 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007272 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007273 break;
7274 } else {
7275 // If there is a global index, look there first to determine which modules
7276 // provably do not have any results for this identifier.
7277 GlobalModuleIndex::HitSet Hits;
7278 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7279 if (!loadGlobalIndex()) {
7280 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7281 HitsPtr = &Hits;
7282 }
7283 }
7284
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007285 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007286 }
7287
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 IdentifierInfo *II = Visitor.getIdentifierInfo();
7289 markIdentifierUpToDate(II);
7290 return II;
7291}
7292
7293namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007294
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 /// \brief An identifier-lookup iterator that enumerates all of the
7296 /// identifiers stored within a set of AST files.
7297 class ASTIdentifierIterator : public IdentifierIterator {
7298 /// \brief The AST reader whose identifiers are being enumerated.
7299 const ASTReader &Reader;
7300
7301 /// \brief The current index into the chain of AST files stored in
7302 /// the AST reader.
7303 unsigned Index;
7304
7305 /// \brief The current position within the identifier lookup table
7306 /// of the current AST file.
7307 ASTIdentifierLookupTable::key_iterator Current;
7308
7309 /// \brief The end position within the identifier lookup table of
7310 /// the current AST file.
7311 ASTIdentifierLookupTable::key_iterator End;
7312
Ben Langmuir537c5b52016-05-04 00:53:13 +00007313 /// \brief Whether to skip any modules in the ASTReader.
7314 bool SkipModules;
7315
Guy Benyei11169dd2012-12-18 14:30:41 +00007316 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007317 explicit ASTIdentifierIterator(const ASTReader &Reader,
7318 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007319
Craig Topper3e89dfe2014-03-13 02:13:41 +00007320 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007321 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007322
7323} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007324
Ben Langmuir537c5b52016-05-04 00:53:13 +00007325ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7326 bool SkipModules)
7327 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007328}
7329
7330StringRef ASTIdentifierIterator::Next() {
7331 while (Current == End) {
7332 // If we have exhausted all of our AST files, we're done.
7333 if (Index == 0)
7334 return StringRef();
7335
7336 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007337 ModuleFile &F = Reader.ModuleMgr[Index];
7338 if (SkipModules && F.isModule())
7339 continue;
7340
7341 ASTIdentifierLookupTable *IdTable =
7342 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 Current = IdTable->key_begin();
7344 End = IdTable->key_end();
7345 }
7346
7347 // We have any identifiers remaining in the current AST file; return
7348 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007349 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007351 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007352}
7353
Ben Langmuir537c5b52016-05-04 00:53:13 +00007354namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007355
Ben Langmuir537c5b52016-05-04 00:53:13 +00007356/// A utility for appending two IdentifierIterators.
7357class ChainedIdentifierIterator : public IdentifierIterator {
7358 std::unique_ptr<IdentifierIterator> Current;
7359 std::unique_ptr<IdentifierIterator> Queued;
7360
7361public:
7362 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7363 std::unique_ptr<IdentifierIterator> Second)
7364 : Current(std::move(First)), Queued(std::move(Second)) {}
7365
7366 StringRef Next() override {
7367 if (!Current)
7368 return StringRef();
7369
7370 StringRef result = Current->Next();
7371 if (!result.empty())
7372 return result;
7373
7374 // Try the queued iterator, which may itself be empty.
7375 Current.reset();
7376 std::swap(Current, Queued);
7377 return Next();
7378 }
7379};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007380
Ben Langmuir537c5b52016-05-04 00:53:13 +00007381} // end anonymous namespace.
7382
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007383IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007384 if (!loadGlobalIndex()) {
7385 std::unique_ptr<IdentifierIterator> ReaderIter(
7386 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7387 std::unique_ptr<IdentifierIterator> ModulesIter(
7388 GlobalIndex->createIdentifierIterator());
7389 return new ChainedIdentifierIterator(std::move(ReaderIter),
7390 std::move(ModulesIter));
7391 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007392
Guy Benyei11169dd2012-12-18 14:30:41 +00007393 return new ASTIdentifierIterator(*this);
7394}
7395
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007396namespace clang {
7397namespace serialization {
7398
Guy Benyei11169dd2012-12-18 14:30:41 +00007399 class ReadMethodPoolVisitor {
7400 ASTReader &Reader;
7401 Selector Sel;
7402 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007403 unsigned InstanceBits;
7404 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007405 bool InstanceHasMoreThanOneDecl;
7406 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007407 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7408 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007409
7410 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007411 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007413 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007414 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7415 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007416
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007417 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 if (!M.SelectorLookupTable)
7419 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007420
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007422 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 return true;
7424
Richard Smithbdf2d932015-07-30 03:37:16 +00007425 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 ASTSelectorLookupTable *PoolTable
7427 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007428 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007429 if (Pos == PoolTable->end())
7430 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007431
Richard Smithbdf2d932015-07-30 03:37:16 +00007432 ++Reader.NumMethodPoolTableHits;
7433 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 // FIXME: Not quite happy with the statistics here. We probably should
7435 // disable this tracking when called via LoadSelector.
7436 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007437 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007439 if (Reader.DeserializationListener)
7440 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007441
Richard Smithbdf2d932015-07-30 03:37:16 +00007442 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7443 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7444 InstanceBits = Data.InstanceBits;
7445 FactoryBits = Data.FactoryBits;
7446 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7447 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007448 return true;
7449 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007450
Guy Benyei11169dd2012-12-18 14:30:41 +00007451 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007452 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7453 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 }
7455
7456 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007457 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 return FactoryMethods;
7459 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007460
7461 unsigned getInstanceBits() const { return InstanceBits; }
7462 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007463 bool instanceHasMoreThanOneDecl() const {
7464 return InstanceHasMoreThanOneDecl;
7465 }
7466 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007467 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007468
7469} // end namespace serialization
7470} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007471
7472/// \brief Add the given set of methods to the method list.
7473static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7474 ObjCMethodList &List) {
7475 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7476 S.addMethodToGlobalList(&List, Methods[I]);
7477 }
7478}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007479
Guy Benyei11169dd2012-12-18 14:30:41 +00007480void ASTReader::ReadMethodPool(Selector Sel) {
7481 // Get the selector generation and update it to the current generation.
7482 unsigned &Generation = SelectorGeneration[Sel];
7483 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007484 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007485 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007488 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007490 ModuleMgr.visit(Visitor);
7491
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007493 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007495
7496 ++NumMethodPoolHits;
7497
Guy Benyei11169dd2012-12-18 14:30:41 +00007498 if (!getSema())
7499 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007500
Guy Benyei11169dd2012-12-18 14:30:41 +00007501 Sema &S = *getSema();
7502 Sema::GlobalMethodPool::iterator Pos
7503 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007504
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007505 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007506 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007507 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007508 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007509
7510 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7511 // when building a module we keep every method individually and may need to
7512 // update hasMoreThanOneDecl as we add the methods.
7513 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7514 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007515}
7516
Manman Rena0f31a02016-04-29 19:04:05 +00007517void ASTReader::updateOutOfDateSelector(Selector Sel) {
7518 if (SelectorOutOfDate[Sel])
7519 ReadMethodPool(Sel);
7520}
7521
Guy Benyei11169dd2012-12-18 14:30:41 +00007522void ASTReader::ReadKnownNamespaces(
7523 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7524 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007525
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007527 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7529 Namespaces.push_back(Namespace);
7530 }
7531}
7532
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007533void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007534 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007535 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7536 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007537 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007538 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007539 Undefined.insert(std::make_pair(D, Loc));
7540 }
7541}
Nick Lewycky8334af82013-01-26 00:35:08 +00007542
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007543void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7544 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7545 Exprs) {
7546 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7547 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7548 uint64_t Count = DelayedDeleteExprs[Idx++];
7549 for (uint64_t C = 0; C < Count; ++C) {
7550 SourceLocation DeleteLoc =
7551 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7552 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7553 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7554 }
7555 }
7556}
7557
Guy Benyei11169dd2012-12-18 14:30:41 +00007558void ASTReader::ReadTentativeDefinitions(
7559 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7560 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7561 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7562 if (Var)
7563 TentativeDefs.push_back(Var);
7564 }
7565 TentativeDefinitions.clear();
7566}
7567
7568void ASTReader::ReadUnusedFileScopedDecls(
7569 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7570 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7571 DeclaratorDecl *D
7572 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7573 if (D)
7574 Decls.push_back(D);
7575 }
7576 UnusedFileScopedDecls.clear();
7577}
7578
7579void ASTReader::ReadDelegatingConstructors(
7580 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7581 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7582 CXXConstructorDecl *D
7583 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7584 if (D)
7585 Decls.push_back(D);
7586 }
7587 DelegatingCtorDecls.clear();
7588}
7589
7590void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7591 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7592 TypedefNameDecl *D
7593 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7594 if (D)
7595 Decls.push_back(D);
7596 }
7597 ExtVectorDecls.clear();
7598}
7599
Nico Weber72889432014-09-06 01:25:55 +00007600void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7601 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7602 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7603 ++I) {
7604 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7605 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7606 if (D)
7607 Decls.insert(D);
7608 }
7609 UnusedLocalTypedefNameCandidates.clear();
7610}
7611
Guy Benyei11169dd2012-12-18 14:30:41 +00007612void ASTReader::ReadReferencedSelectors(
7613 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7614 if (ReferencedSelectorsData.empty())
7615 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007616
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 // If there are @selector references added them to its pool. This is for
7618 // implementation of -Wselector.
7619 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7620 unsigned I = 0;
7621 while (I < DataSize) {
7622 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7623 SourceLocation SelLoc
7624 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7625 Sels.push_back(std::make_pair(Sel, SelLoc));
7626 }
7627 ReferencedSelectorsData.clear();
7628}
7629
7630void ASTReader::ReadWeakUndeclaredIdentifiers(
7631 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7632 if (WeakUndeclaredIdentifiers.empty())
7633 return;
7634
7635 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007636 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007638 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7640 SourceLocation Loc
7641 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7642 bool Used = WeakUndeclaredIdentifiers[I++];
7643 WeakInfo WI(AliasId, Loc);
7644 WI.setUsed(Used);
7645 WeakIDs.push_back(std::make_pair(WeakId, WI));
7646 }
7647 WeakUndeclaredIdentifiers.clear();
7648}
7649
7650void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7651 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7652 ExternalVTableUse VT;
7653 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7654 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7655 VT.DefinitionRequired = VTableUses[Idx++];
7656 VTables.push_back(VT);
7657 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 VTableUses.clear();
7660}
7661
7662void ASTReader::ReadPendingInstantiations(
7663 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7664 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7665 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7666 SourceLocation Loc
7667 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7668
7669 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007670 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 PendingInstantiations.clear();
7672}
7673
Richard Smithe40f2ba2013-08-07 21:41:30 +00007674void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007675 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7676 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007677 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7678 /* In loop */) {
7679 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7680
Justin Lebar28f09c52016-10-10 16:26:08 +00007681 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007682 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7683
7684 ModuleFile *F = getOwningModuleFile(LT->D);
7685 assert(F && "No module");
7686
7687 unsigned TokN = LateParsedTemplates[Idx++];
7688 LT->Toks.reserve(TokN);
7689 for (unsigned T = 0; T < TokN; ++T)
7690 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7691
Justin Lebar28f09c52016-10-10 16:26:08 +00007692 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007693 }
7694
7695 LateParsedTemplates.clear();
7696}
7697
Guy Benyei11169dd2012-12-18 14:30:41 +00007698void ASTReader::LoadSelector(Selector Sel) {
7699 // It would be complicated to avoid reading the methods anyway. So don't.
7700 ReadMethodPool(Sel);
7701}
7702
7703void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7704 assert(ID && "Non-zero identifier ID required");
7705 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7706 IdentifiersLoaded[ID - 1] = II;
7707 if (DeserializationListener)
7708 DeserializationListener->IdentifierRead(ID, II);
7709}
7710
7711/// \brief Set the globally-visible declarations associated with the given
7712/// identifier.
7713///
7714/// If the AST reader is currently in a state where the given declaration IDs
7715/// cannot safely be resolved, they are queued until it is safe to resolve
7716/// them.
7717///
7718/// \param II an IdentifierInfo that refers to one or more globally-visible
7719/// declarations.
7720///
7721/// \param DeclIDs the set of declaration IDs with the name @p II that are
7722/// visible at global scope.
7723///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007724/// \param Decls if non-null, this vector will be populated with the set of
7725/// deserialized declarations. These declarations will not be pushed into
7726/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007727void
7728ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7729 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007730 SmallVectorImpl<Decl *> *Decls) {
7731 if (NumCurrentElementsDeserializing && !Decls) {
7732 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 return;
7734 }
7735
7736 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007737 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 // Queue this declaration so that it will be added to the
7739 // translation unit scope and identifier's declaration chain
7740 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007741 PreloadedDeclIDs.push_back(DeclIDs[I]);
7742 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007744
7745 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7746
7747 // If we're simply supposed to record the declarations, do so now.
7748 if (Decls) {
7749 Decls->push_back(D);
7750 continue;
7751 }
7752
7753 // Introduce this declaration into the translation-unit scope
7754 // and add it to the declaration chain for this identifier, so
7755 // that (unqualified) name lookup will find it.
7756 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 }
7758}
7759
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007760IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007761 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007762 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007763
7764 if (IdentifiersLoaded.empty()) {
7765 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007766 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 }
7768
7769 ID -= 1;
7770 if (!IdentifiersLoaded[ID]) {
7771 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7772 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7773 ModuleFile *M = I->second;
7774 unsigned Index = ID - M->BaseIdentifierID;
7775 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7776
7777 // All of the strings in the AST file are preceded by a 16-bit length.
7778 // Extract that 16-bit length to avoid having to execute strlen().
7779 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7780 // unsigned integers. This is important to avoid integer overflow when
7781 // we cast them to 'unsigned'.
7782 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7783 unsigned StrLen = (((unsigned) StrLenPtr[0])
7784 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007785 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7786 IdentifiersLoaded[ID] = &II;
7787 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007789 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 }
7791
7792 return IdentifiersLoaded[ID];
7793}
7794
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007795IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7796 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007797}
7798
7799IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7800 if (LocalID < NUM_PREDEF_IDENT_IDS)
7801 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007802
Richard Smith37a93df2017-02-18 00:32:02 +00007803 if (!M.ModuleOffsetMap.empty())
7804 ReadModuleOffsetMap(M);
7805
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7807 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007808 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007809 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007810
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 return LocalID + I->second;
7812}
7813
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007814MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007816 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007817
7818 if (MacrosLoaded.empty()) {
7819 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007820 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007821 }
7822
7823 ID -= NUM_PREDEF_MACRO_IDS;
7824 if (!MacrosLoaded[ID]) {
7825 GlobalMacroMapType::iterator I
7826 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7827 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7828 ModuleFile *M = I->second;
7829 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007830 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007831
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007832 if (DeserializationListener)
7833 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7834 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007835 }
7836
7837 return MacrosLoaded[ID];
7838}
7839
7840MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7841 if (LocalID < NUM_PREDEF_MACRO_IDS)
7842 return LocalID;
7843
Richard Smith37a93df2017-02-18 00:32:02 +00007844 if (!M.ModuleOffsetMap.empty())
7845 ReadModuleOffsetMap(M);
7846
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7848 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7849 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7850
7851 return LocalID + I->second;
7852}
7853
7854serialization::SubmoduleID
7855ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7856 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7857 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007858
Richard Smith37a93df2017-02-18 00:32:02 +00007859 if (!M.ModuleOffsetMap.empty())
7860 ReadModuleOffsetMap(M);
7861
Guy Benyei11169dd2012-12-18 14:30:41 +00007862 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7863 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007864 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007865 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007866
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 return LocalID + I->second;
7868}
7869
7870Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7871 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7872 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007873 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 if (GlobalID > SubmodulesLoaded.size()) {
7877 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007878 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007880
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7882}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007883
7884Module *ASTReader::getModule(unsigned ID) {
7885 return getSubmodule(ID);
7886}
7887
Richard Smithd88a7f12015-09-01 20:35:42 +00007888ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7889 if (ID & 1) {
7890 // It's a module, look it up by submodule ID.
7891 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7892 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7893 } else {
7894 // It's a prefix (preamble, PCH, ...). Look it up by index.
7895 unsigned IndexFromEnd = ID >> 1;
7896 assert(IndexFromEnd && "got reference to unknown module file");
7897 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7898 }
7899}
7900
7901unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7902 if (!F)
7903 return 1;
7904
7905 // For a file representing a module, use the submodule ID of the top-level
7906 // module as the file ID. For any other kind of file, the number of such
7907 // files loaded beforehand will be the same on reload.
7908 // FIXME: Is this true even if we have an explicit module file and a PCH?
7909 if (F->isModule())
7910 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7911
7912 auto PCHModules = getModuleManager().pch_modules();
7913 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7914 assert(I != PCHModules.end() && "emitting reference to unknown file");
7915 return (I - PCHModules.end()) << 1;
7916}
7917
Adrian Prantl15bcf702015-06-30 17:39:43 +00007918llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7919ASTReader::getSourceDescriptor(unsigned ID) {
7920 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007921 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007922
7923 // If there is only a single PCH, return it instead.
7924 // Chained PCH are not suported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00007925 const auto &PCHChain = ModuleMgr.pch_modules();
7926 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00007927 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007928 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007929 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7930 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7931 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007932 }
7933 return None;
7934}
7935
David Blaikie9ffe5a32017-01-30 05:00:26 +00007936ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7937 const Module *M = getSubmodule(ID);
7938 if (!M || !M->WithCodegen)
7939 return EK_ReplyHazy;
7940
7941 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7942 assert(MF); // ?
7943 if (MF->Kind == ModuleKind::MK_MainFile)
7944 return EK_Never;
7945 return EK_Always;
7946}
7947
Guy Benyei11169dd2012-12-18 14:30:41 +00007948Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7949 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7950}
7951
7952Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7953 if (ID == 0)
7954 return Selector();
7955
7956 if (ID > SelectorsLoaded.size()) {
7957 Error("selector ID out of range in AST file");
7958 return Selector();
7959 }
7960
Craig Toppera13603a2014-05-22 05:54:18 +00007961 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 // Load this selector from the selector table.
7963 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7964 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7965 ModuleFile &M = *I->second;
7966 ASTSelectorLookupTrait Trait(*this, M);
7967 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7968 SelectorsLoaded[ID - 1] =
7969 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7970 if (DeserializationListener)
7971 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7972 }
7973
7974 return SelectorsLoaded[ID - 1];
7975}
7976
7977Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7978 return DecodeSelector(ID);
7979}
7980
7981uint32_t ASTReader::GetNumExternalSelectors() {
7982 // ID 0 (the null selector) is considered an external selector.
7983 return getTotalNumSelectors() + 1;
7984}
7985
7986serialization::SelectorID
7987ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7988 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7989 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007990
Richard Smith37a93df2017-02-18 00:32:02 +00007991 if (!M.ModuleOffsetMap.empty())
7992 ReadModuleOffsetMap(M);
7993
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7995 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007996 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007998
Guy Benyei11169dd2012-12-18 14:30:41 +00007999 return LocalID + I->second;
8000}
8001
8002DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008003ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 const RecordData &Record, unsigned &Idx) {
8005 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8006 switch (Kind) {
8007 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008008 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008009
8010 case DeclarationName::ObjCZeroArgSelector:
8011 case DeclarationName::ObjCOneArgSelector:
8012 case DeclarationName::ObjCMultiArgSelector:
8013 return DeclarationName(ReadSelector(F, Record, Idx));
8014
8015 case DeclarationName::CXXConstructorName:
8016 return Context.DeclarationNames.getCXXConstructorName(
8017 Context.getCanonicalType(readType(F, Record, Idx)));
8018
8019 case DeclarationName::CXXDestructorName:
8020 return Context.DeclarationNames.getCXXDestructorName(
8021 Context.getCanonicalType(readType(F, Record, Idx)));
8022
Richard Smith35845152017-02-07 01:37:30 +00008023 case DeclarationName::CXXDeductionGuideName:
8024 return Context.DeclarationNames.getCXXDeductionGuideName(
8025 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8026
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 case DeclarationName::CXXConversionFunctionName:
8028 return Context.DeclarationNames.getCXXConversionFunctionName(
8029 Context.getCanonicalType(readType(F, Record, Idx)));
8030
8031 case DeclarationName::CXXOperatorName:
8032 return Context.DeclarationNames.getCXXOperatorName(
8033 (OverloadedOperatorKind)Record[Idx++]);
8034
8035 case DeclarationName::CXXLiteralOperatorName:
8036 return Context.DeclarationNames.getCXXLiteralOperatorName(
8037 GetIdentifierInfo(F, Record, Idx));
8038
8039 case DeclarationName::CXXUsingDirective:
8040 return DeclarationName::getUsingDirectiveName();
8041 }
8042
8043 llvm_unreachable("Invalid NameKind!");
8044}
8045
8046void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8047 DeclarationNameLoc &DNLoc,
8048 DeclarationName Name,
8049 const RecordData &Record, unsigned &Idx) {
8050 switch (Name.getNameKind()) {
8051 case DeclarationName::CXXConstructorName:
8052 case DeclarationName::CXXDestructorName:
8053 case DeclarationName::CXXConversionFunctionName:
8054 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8055 break;
8056
8057 case DeclarationName::CXXOperatorName:
8058 DNLoc.CXXOperatorName.BeginOpNameLoc
8059 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8060 DNLoc.CXXOperatorName.EndOpNameLoc
8061 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8062 break;
8063
8064 case DeclarationName::CXXLiteralOperatorName:
8065 DNLoc.CXXLiteralOperatorName.OpNameLoc
8066 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8067 break;
8068
8069 case DeclarationName::Identifier:
8070 case DeclarationName::ObjCZeroArgSelector:
8071 case DeclarationName::ObjCOneArgSelector:
8072 case DeclarationName::ObjCMultiArgSelector:
8073 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008074 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 break;
8076 }
8077}
8078
8079void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8080 DeclarationNameInfo &NameInfo,
8081 const RecordData &Record, unsigned &Idx) {
8082 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8083 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8084 DeclarationNameLoc DNLoc;
8085 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8086 NameInfo.setInfo(DNLoc);
8087}
8088
8089void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8090 const RecordData &Record, unsigned &Idx) {
8091 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8092 unsigned NumTPLists = Record[Idx++];
8093 Info.NumTemplParamLists = NumTPLists;
8094 if (NumTPLists) {
8095 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008096 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8098 }
8099}
8100
8101TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008102ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 unsigned &Idx) {
8104 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8105 switch (Kind) {
8106 case TemplateName::Template:
8107 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8108
8109 case TemplateName::OverloadedTemplate: {
8110 unsigned size = Record[Idx++];
8111 UnresolvedSet<8> Decls;
8112 while (size--)
8113 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8114
8115 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8116 }
8117
8118 case TemplateName::QualifiedTemplate: {
8119 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8120 bool hasTemplKeyword = Record[Idx++];
8121 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8122 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8123 }
8124
8125 case TemplateName::DependentTemplate: {
8126 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8127 if (Record[Idx++]) // isIdentifier
8128 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008129 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 Idx));
8131 return Context.getDependentTemplateName(NNS,
8132 (OverloadedOperatorKind)Record[Idx++]);
8133 }
8134
8135 case TemplateName::SubstTemplateTemplateParm: {
8136 TemplateTemplateParmDecl *param
8137 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8138 if (!param) return TemplateName();
8139 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8140 return Context.getSubstTemplateTemplateParm(param, replacement);
8141 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008142
Guy Benyei11169dd2012-12-18 14:30:41 +00008143 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008144 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8146 if (!Param)
8147 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008148
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8150 if (ArgPack.getKind() != TemplateArgument::Pack)
8151 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8154 }
8155 }
8156
8157 llvm_unreachable("Unhandled template name kind!");
8158}
8159
Richard Smith2bb3c342015-08-09 01:05:31 +00008160TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8161 const RecordData &Record,
8162 unsigned &Idx,
8163 bool Canonicalize) {
8164 if (Canonicalize) {
8165 // The caller wants a canonical template argument. Sometimes the AST only
8166 // wants template arguments in canonical form (particularly as the template
8167 // argument lists of template specializations) so ensure we preserve that
8168 // canonical form across serialization.
8169 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8170 return Context.getCanonicalTemplateArgument(Arg);
8171 }
8172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8174 switch (Kind) {
8175 case TemplateArgument::Null:
8176 return TemplateArgument();
8177 case TemplateArgument::Type:
8178 return TemplateArgument(readType(F, Record, Idx));
8179 case TemplateArgument::Declaration: {
8180 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008181 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 }
8183 case TemplateArgument::NullPtr:
8184 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8185 case TemplateArgument::Integral: {
8186 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8187 QualType T = readType(F, Record, Idx);
8188 return TemplateArgument(Context, Value, T);
8189 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008190 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8192 case TemplateArgument::TemplateExpansion: {
8193 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008194 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 if (unsigned NumExpansions = Record[Idx++])
8196 NumTemplateExpansions = NumExpansions - 1;
8197 return TemplateArgument(Name, NumTemplateExpansions);
8198 }
8199 case TemplateArgument::Expression:
8200 return TemplateArgument(ReadExpr(F));
8201 case TemplateArgument::Pack: {
8202 unsigned NumArgs = Record[Idx++];
8203 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8204 for (unsigned I = 0; I != NumArgs; ++I)
8205 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008206 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 }
8208 }
8209
8210 llvm_unreachable("Unhandled template argument kind!");
8211}
8212
8213TemplateParameterList *
8214ASTReader::ReadTemplateParameterList(ModuleFile &F,
8215 const RecordData &Record, unsigned &Idx) {
8216 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8217 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8218 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8219
8220 unsigned NumParams = Record[Idx++];
8221 SmallVector<NamedDecl *, 16> Params;
8222 Params.reserve(NumParams);
8223 while (NumParams--)
8224 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8225
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008226 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 TemplateParameterList* TemplateParams =
8228 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008229 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 return TemplateParams;
8231}
8232
8233void
8234ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008235ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008237 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 unsigned NumTemplateArgs = Record[Idx++];
8239 TemplArgs.reserve(NumTemplateArgs);
8240 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008241 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008242}
8243
8244/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008245void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 const RecordData &Record, unsigned &Idx) {
8247 unsigned NumDecls = Record[Idx++];
8248 Set.reserve(Context, NumDecls);
8249 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008250 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008252 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 }
8254}
8255
8256CXXBaseSpecifier
8257ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8258 const RecordData &Record, unsigned &Idx) {
8259 bool isVirtual = static_cast<bool>(Record[Idx++]);
8260 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8261 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8262 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8263 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8264 SourceRange Range = ReadSourceRange(F, Record, Idx);
8265 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008266 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 EllipsisLoc);
8268 Result.setInheritConstructors(inheritConstructors);
8269 return Result;
8270}
8271
Richard Smithc2bb8182015-03-24 06:36:48 +00008272CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008273ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8274 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008275 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008276 assert(NumInitializers && "wrote ctor initializers but have no inits");
8277 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8278 for (unsigned i = 0; i != NumInitializers; ++i) {
8279 TypeSourceInfo *TInfo = nullptr;
8280 bool IsBaseVirtual = false;
8281 FieldDecl *Member = nullptr;
8282 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008283
Richard Smithc2bb8182015-03-24 06:36:48 +00008284 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8285 switch (Type) {
8286 case CTOR_INITIALIZER_BASE:
8287 TInfo = GetTypeSourceInfo(F, Record, Idx);
8288 IsBaseVirtual = Record[Idx++];
8289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008290
Richard Smithc2bb8182015-03-24 06:36:48 +00008291 case CTOR_INITIALIZER_DELEGATING:
8292 TInfo = GetTypeSourceInfo(F, Record, Idx);
8293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008294
Richard Smithc2bb8182015-03-24 06:36:48 +00008295 case CTOR_INITIALIZER_MEMBER:
8296 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008298
Richard Smithc2bb8182015-03-24 06:36:48 +00008299 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8300 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8301 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008303
8304 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8305 Expr *Init = ReadExpr(F);
8306 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8307 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008308
8309 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008310 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008311 BOMInit = new (Context)
8312 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8313 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008314 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008315 BOMInit = new (Context)
8316 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008317 else if (Member)
8318 BOMInit = new (Context)
8319 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8320 Init, RParenLoc);
8321 else
8322 BOMInit = new (Context)
8323 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8324 LParenLoc, Init, RParenLoc);
8325
Richard Smith418ed822016-12-14 19:45:03 +00008326 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008327 unsigned SourceOrder = Record[Idx++];
8328 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008329 }
8330
Richard Smithc2bb8182015-03-24 06:36:48 +00008331 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008332 }
8333
Richard Smithc2bb8182015-03-24 06:36:48 +00008334 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008335}
8336
8337NestedNameSpecifier *
8338ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8339 const RecordData &Record, unsigned &Idx) {
8340 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008341 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008342 for (unsigned I = 0; I != N; ++I) {
8343 NestedNameSpecifier::SpecifierKind Kind
8344 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8345 switch (Kind) {
8346 case NestedNameSpecifier::Identifier: {
8347 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8348 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8349 break;
8350 }
8351
8352 case NestedNameSpecifier::Namespace: {
8353 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8354 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8355 break;
8356 }
8357
8358 case NestedNameSpecifier::NamespaceAlias: {
8359 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8360 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8361 break;
8362 }
8363
8364 case NestedNameSpecifier::TypeSpec:
8365 case NestedNameSpecifier::TypeSpecWithTemplate: {
8366 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8367 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008368 return nullptr;
8369
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 bool Template = Record[Idx++];
8371 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8372 break;
8373 }
8374
8375 case NestedNameSpecifier::Global: {
8376 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8377 // No associated value, and there can't be a prefix.
8378 break;
8379 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008380
8381 case NestedNameSpecifier::Super: {
8382 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8383 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8384 break;
8385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008386 }
8387 Prev = NNS;
8388 }
8389 return NNS;
8390}
8391
8392NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008393ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 unsigned &Idx) {
8395 unsigned N = Record[Idx++];
8396 NestedNameSpecifierLocBuilder Builder;
8397 for (unsigned I = 0; I != N; ++I) {
8398 NestedNameSpecifier::SpecifierKind Kind
8399 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8400 switch (Kind) {
8401 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008402 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008403 SourceRange Range = ReadSourceRange(F, Record, Idx);
8404 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8405 break;
8406 }
8407
8408 case NestedNameSpecifier::Namespace: {
8409 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8410 SourceRange Range = ReadSourceRange(F, Record, Idx);
8411 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8412 break;
8413 }
8414
8415 case NestedNameSpecifier::NamespaceAlias: {
8416 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8417 SourceRange Range = ReadSourceRange(F, Record, Idx);
8418 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8419 break;
8420 }
8421
8422 case NestedNameSpecifier::TypeSpec:
8423 case NestedNameSpecifier::TypeSpecWithTemplate: {
8424 bool Template = Record[Idx++];
8425 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8426 if (!T)
8427 return NestedNameSpecifierLoc();
8428 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8429
8430 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008431 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8433 T->getTypeLoc(), ColonColonLoc);
8434 break;
8435 }
8436
8437 case NestedNameSpecifier::Global: {
8438 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8439 Builder.MakeGlobal(Context, ColonColonLoc);
8440 break;
8441 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008442
8443 case NestedNameSpecifier::Super: {
8444 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8445 SourceRange Range = ReadSourceRange(F, Record, Idx);
8446 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8447 break;
8448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008449 }
8450 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008451
Guy Benyei11169dd2012-12-18 14:30:41 +00008452 return Builder.getWithLocInContext(Context);
8453}
8454
8455SourceRange
8456ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8457 unsigned &Idx) {
8458 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8459 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8460 return SourceRange(beg, end);
8461}
8462
8463/// \brief Read an integral value
8464llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8465 unsigned BitWidth = Record[Idx++];
8466 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8467 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8468 Idx += NumWords;
8469 return Result;
8470}
8471
8472/// \brief Read a signed integral value
8473llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8474 bool isUnsigned = Record[Idx++];
8475 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8476}
8477
8478/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008479llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8480 const llvm::fltSemantics &Sem,
8481 unsigned &Idx) {
8482 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008483}
8484
8485// \brief Read a string
8486std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8487 unsigned Len = Record[Idx++];
8488 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8489 Idx += Len;
8490 return Result;
8491}
8492
Richard Smith7ed1bc92014-12-05 22:42:13 +00008493std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8494 unsigned &Idx) {
8495 std::string Filename = ReadString(Record, Idx);
8496 ResolveImportedPath(F, Filename);
8497 return Filename;
8498}
8499
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008500VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008501 unsigned &Idx) {
8502 unsigned Major = Record[Idx++];
8503 unsigned Minor = Record[Idx++];
8504 unsigned Subminor = Record[Idx++];
8505 if (Minor == 0)
8506 return VersionTuple(Major);
8507 if (Subminor == 0)
8508 return VersionTuple(Major, Minor - 1);
8509 return VersionTuple(Major, Minor - 1, Subminor - 1);
8510}
8511
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008512CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008513 const RecordData &Record,
8514 unsigned &Idx) {
8515 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8516 return CXXTemporary::Create(Context, Decl);
8517}
8518
Richard Smith37a93df2017-02-18 00:32:02 +00008519DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008520 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008521}
8522
Richard Smith37a93df2017-02-18 00:32:02 +00008523DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 return Diags.Report(Loc, DiagID);
8525}
8526
8527/// \brief Retrieve the identifier table associated with the
8528/// preprocessor.
8529IdentifierTable &ASTReader::getIdentifierTable() {
8530 return PP.getIdentifierTable();
8531}
8532
8533/// \brief Record that the given ID maps to the given switch-case
8534/// statement.
8535void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008536 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 "Already have a SwitchCase with this ID");
8538 (*CurrSwitchCaseStmts)[ID] = SC;
8539}
8540
8541/// \brief Retrieve the switch-case statement with the given ID.
8542SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008543 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008544 return (*CurrSwitchCaseStmts)[ID];
8545}
8546
8547void ASTReader::ClearSwitchCaseIDs() {
8548 CurrSwitchCaseStmts->clear();
8549}
8550
8551void ASTReader::ReadComments() {
8552 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008553 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008554 serialization::ModuleFile *> >::iterator
8555 I = CommentsCursors.begin(),
8556 E = CommentsCursors.end();
8557 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008558 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008559 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008560 serialization::ModuleFile &F = *I->second;
8561 SavedStreamPosition SavedPosition(Cursor);
8562
8563 RecordData Record;
8564 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008565 llvm::BitstreamEntry Entry =
8566 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008567
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008568 switch (Entry.Kind) {
8569 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8570 case llvm::BitstreamEntry::Error:
8571 Error("malformed block record in AST file");
8572 return;
8573 case llvm::BitstreamEntry::EndBlock:
8574 goto NextCursor;
8575 case llvm::BitstreamEntry::Record:
8576 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 }
8579
8580 // Read a record.
8581 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008582 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 case COMMENTS_RAW_COMMENT: {
8584 unsigned Idx = 0;
8585 SourceRange SR = ReadSourceRange(F, Record, Idx);
8586 RawComment::CommentKind Kind =
8587 (RawComment::CommentKind) Record[Idx++];
8588 bool IsTrailingComment = Record[Idx++];
8589 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008590 Comments.push_back(new (Context) RawComment(
8591 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8592 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008593 break;
8594 }
8595 }
8596 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008597 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008598 // De-serialized SourceLocations get negative FileIDs for other modules,
8599 // potentially invalidating the original order. Sort it again.
8600 std::sort(Comments.begin(), Comments.end(),
8601 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008602 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008604}
8605
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008606void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8607 bool IncludeSystem, bool Complain,
8608 llvm::function_ref<void(const serialization::InputFile &IF,
8609 bool isSystem)> Visitor) {
8610 unsigned NumUserInputs = MF.NumUserInputFiles;
8611 unsigned NumInputs = MF.InputFilesLoaded.size();
8612 assert(NumUserInputs <= NumInputs);
8613 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8614 for (unsigned I = 0; I < N; ++I) {
8615 bool IsSystem = I >= NumUserInputs;
8616 InputFile IF = getInputFile(MF, I+1, Complain);
8617 Visitor(IF, IsSystem);
8618 }
8619}
8620
Richard Smithcd45dbc2014-04-19 03:48:30 +00008621std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8622 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008623 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008624 return M->getFullModuleName();
8625
8626 // Otherwise, use the name of the top-level module the decl is within.
8627 if (ModuleFile *M = getOwningModuleFile(D))
8628 return M->ModuleName;
8629
8630 // Not from a module.
8631 return "";
8632}
8633
Guy Benyei11169dd2012-12-18 14:30:41 +00008634void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008635 while (!PendingIdentifierInfos.empty() ||
8636 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008637 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008638 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008639 // If any identifiers with corresponding top-level declarations have
8640 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008641 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8642 TopLevelDeclsMap;
8643 TopLevelDeclsMap TopLevelDecls;
8644
Guy Benyei11169dd2012-12-18 14:30:41 +00008645 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008646 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008647 SmallVector<uint32_t, 4> DeclIDs =
8648 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008649 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008650
8651 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008652 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008653
Richard Smith851072e2014-05-19 20:59:20 +00008654 // For each decl chain that we wanted to complete while deserializing, mark
8655 // it as "still needs to be completed".
8656 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8657 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8658 }
8659 PendingIncompleteDeclChains.clear();
8660
Guy Benyei11169dd2012-12-18 14:30:41 +00008661 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008662 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008663 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 PendingDeclChains.clear();
8665
Douglas Gregor6168bd22013-02-18 15:53:43 +00008666 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008667 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8668 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008669 IdentifierInfo *II = TLD->first;
8670 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008671 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008672 }
8673 }
8674
Guy Benyei11169dd2012-12-18 14:30:41 +00008675 // Load any pending macro definitions.
8676 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008677 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8678 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8679 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8680 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008681 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008682 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008683 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008684 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008685 resolvePendingMacro(II, Info);
8686 }
8687 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008688 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008689 ++IDIdx) {
8690 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008691 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008692 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008693 }
8694 }
8695 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008696
8697 // Wire up the DeclContexts for Decls that we delayed setting until
8698 // recursive loading is completed.
8699 while (!PendingDeclContextInfos.empty()) {
8700 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8701 PendingDeclContextInfos.pop_front();
8702 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8703 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8704 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8705 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008706
Richard Smithd1c46742014-04-30 02:24:17 +00008707 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008708 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008709 auto Update = PendingUpdateRecords.pop_back_val();
8710 ReadingKindTracker ReadingKind(Read_Decl, *this);
8711 loadDeclUpdateRecords(Update.first, Update.second);
8712 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 }
Richard Smith8a639892015-01-24 01:07:20 +00008714
8715 // At this point, all update records for loaded decls are in place, so any
8716 // fake class definitions should have become real.
8717 assert(PendingFakeDefinitionData.empty() &&
8718 "faked up a class definition but never saw the real one");
8719
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 // If we deserialized any C++ or Objective-C class definitions, any
8721 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008722 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008723 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008724 for (Decl *D : PendingDefinitions) {
8725 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008726 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 // Make sure that the TagType points at the definition.
8728 const_cast<TagType*>(TagT)->decl = TD;
8729 }
Richard Smith8ce51082015-03-11 01:44:51 +00008730
Craig Topperc6914d02014-08-25 04:15:02 +00008731 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008732 for (auto *R = getMostRecentExistingDecl(RD); R;
8733 R = R->getPreviousDecl()) {
8734 assert((R == D) ==
8735 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008736 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008737 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008738 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008739 }
8740
8741 continue;
8742 }
Richard Smith8ce51082015-03-11 01:44:51 +00008743
Craig Topperc6914d02014-08-25 04:15:02 +00008744 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008745 // Make sure that the ObjCInterfaceType points at the definition.
8746 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8747 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008748
8749 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8750 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8751
Guy Benyei11169dd2012-12-18 14:30:41 +00008752 continue;
8753 }
Richard Smith8ce51082015-03-11 01:44:51 +00008754
Craig Topperc6914d02014-08-25 04:15:02 +00008755 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008756 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8757 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8758
Guy Benyei11169dd2012-12-18 14:30:41 +00008759 continue;
8760 }
Richard Smith8ce51082015-03-11 01:44:51 +00008761
Craig Topperc6914d02014-08-25 04:15:02 +00008762 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008763 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8764 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008765 }
8766 PendingDefinitions.clear();
8767
8768 // Load the bodies of any functions or methods we've encountered. We do
8769 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008770 // have been fully wired up (hasBody relies on this).
8771 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008772 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8773 PBEnd = PendingBodies.end();
8774 PB != PBEnd; ++PB) {
8775 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8776 // FIXME: Check for =delete/=default?
8777 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008778 const FunctionDecl *Defn = nullptr;
8779 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008780 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008781 else
Richard Smith6561f922016-09-12 21:06:40 +00008782 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 continue;
8784 }
8785
8786 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8787 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8788 MD->setLazyBody(PB->second);
8789 }
8790 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008791
8792 // Do some cleanup.
8793 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8794 getContext().deduplicateMergedDefinitonsFor(ND);
8795 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008796}
8797
8798void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008799 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8800 return;
8801
Richard Smitha0ce9c42014-07-29 23:23:27 +00008802 // Trigger the import of the full definition of each class that had any
8803 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008804 // These updates may in turn find and diagnose some ODR failures, so take
8805 // ownership of the set first.
8806 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8807 PendingOdrMergeFailures.clear();
8808 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008809 Merge.first->buildLookup();
8810 Merge.first->decls_begin();
8811 Merge.first->bases_begin();
8812 Merge.first->vbases_begin();
8813 for (auto *RD : Merge.second) {
8814 RD->decls_begin();
8815 RD->bases_begin();
8816 RD->vbases_begin();
8817 }
8818 }
8819
8820 // For each declaration from a merged context, check that the canonical
8821 // definition of that context also contains a declaration of the same
8822 // entity.
8823 //
8824 // Caution: this loop does things that might invalidate iterators into
8825 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8826 while (!PendingOdrMergeChecks.empty()) {
8827 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8828
8829 // FIXME: Skip over implicit declarations for now. This matters for things
8830 // like implicitly-declared special member functions. This isn't entirely
8831 // correct; we can end up with multiple unmerged declarations of the same
8832 // implicit entity.
8833 if (D->isImplicit())
8834 continue;
8835
8836 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008837
8838 bool Found = false;
8839 const Decl *DCanon = D->getCanonicalDecl();
8840
Richard Smith01bdb7a2014-08-28 05:44:07 +00008841 for (auto RI : D->redecls()) {
8842 if (RI->getLexicalDeclContext() == CanonDef) {
8843 Found = true;
8844 break;
8845 }
8846 }
8847 if (Found)
8848 continue;
8849
Richard Smith0f4e2c42015-08-06 04:23:48 +00008850 // Quick check failed, time to do the slow thing. Note, we can't just
8851 // look up the name of D in CanonDef here, because the member that is
8852 // in CanonDef might not be found by name lookup (it might have been
8853 // replaced by a more recent declaration in the lookup table), and we
8854 // can't necessarily find it in the redeclaration chain because it might
8855 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008856 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008857 for (auto *CanonMember : CanonDef->decls()) {
8858 if (CanonMember->getCanonicalDecl() == DCanon) {
8859 // This can happen if the declaration is merely mergeable and not
8860 // actually redeclarable (we looked for redeclarations earlier).
8861 //
8862 // FIXME: We should be able to detect this more efficiently, without
8863 // pulling in all of the members of CanonDef.
8864 Found = true;
8865 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008866 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008867 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8868 if (ND->getDeclName() == D->getDeclName())
8869 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008870 }
8871
8872 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008873 // The AST doesn't like TagDecls becoming invalid after they've been
8874 // completed. We only really need to mark FieldDecls as invalid here.
8875 if (!isa<TagDecl>(D))
8876 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008877
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008878 // Ensure we don't accidentally recursively enter deserialization while
8879 // we're producing our diagnostic.
8880 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008881
8882 std::string CanonDefModule =
8883 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8884 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8885 << D << getOwningModuleNameForDiagnostic(D)
8886 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8887
8888 if (Candidates.empty())
8889 Diag(cast<Decl>(CanonDef)->getLocation(),
8890 diag::note_module_odr_violation_no_possible_decls) << D;
8891 else {
8892 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8893 Diag(Candidates[I]->getLocation(),
8894 diag::note_module_odr_violation_possible_decl)
8895 << Candidates[I];
8896 }
8897
8898 DiagnosedOdrMergeFailures.insert(CanonDef);
8899 }
8900 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008901
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008902 if (OdrMergeFailures.empty())
8903 return;
8904
8905 // Ensure we don't accidentally recursively enter deserialization while
8906 // we're producing our diagnostics.
8907 Deserializing RecursionGuard(this);
8908
Richard Smithcd45dbc2014-04-19 03:48:30 +00008909 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008910 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008911 // If we've already pointed out a specific problem with this class, don't
8912 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008913 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008914 continue;
8915
8916 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00008917 CXXRecordDecl *FirstRecord = Merge.first;
8918 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
8919 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00008920 // Multiple different declarations got merged together; tell the user
8921 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00008922 if (FirstRecord == SecondRecord)
8923 continue;
8924
8925 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
8926 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
8927 DeclHashes FirstHashes;
8928 DeclHashes SecondHashes;
8929 ODRHash Hash;
8930
8931 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
8932 CXXRecordDecl *Record) {
8933 for (auto *D : Record->decls()) {
8934 // Due to decl merging, the first CXXRecordDecl is the parent of
8935 // Decls in both records.
8936 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
8937 continue;
8938 Hash.clear();
8939 Hash.AddSubDecl(D);
8940 Hashes.emplace_back(D, Hash.CalculateHash());
8941 }
8942 };
8943 PopulateHashes(FirstHashes, FirstRecord);
8944 PopulateHashes(SecondHashes, SecondRecord);
8945
8946 // Used with err_module_odr_violation_mismatch_decl and
8947 // note_module_odr_violation_mismatch_decl
8948 enum {
8949 EndOfClass,
8950 PublicSpecifer,
8951 PrivateSpecifer,
8952 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00008953 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00008954 Field,
Richard Trieu48143742017-02-28 21:24:38 +00008955 CXXMethod,
Richard Trieue7f7ed22017-02-22 01:11:25 +00008956 Other
8957 } FirstDiffType = Other,
8958 SecondDiffType = Other;
8959
8960 auto DifferenceSelector = [](Decl *D) {
8961 assert(D && "valid Decl required");
8962 switch (D->getKind()) {
8963 default:
8964 return Other;
8965 case Decl::AccessSpec:
8966 switch (D->getAccess()) {
8967 case AS_public:
8968 return PublicSpecifer;
8969 case AS_private:
8970 return PrivateSpecifer;
8971 case AS_protected:
8972 return ProtectedSpecifer;
8973 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00008974 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00008975 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00008976 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00008977 case Decl::StaticAssert:
8978 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00008979 case Decl::Field:
8980 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00008981 case Decl::CXXMethod:
8982 return CXXMethod;
Richard Trieue7f7ed22017-02-22 01:11:25 +00008983 }
8984 };
8985
8986 Decl *FirstDecl = nullptr;
8987 Decl *SecondDecl = nullptr;
8988 auto FirstIt = FirstHashes.begin();
8989 auto SecondIt = SecondHashes.begin();
8990
8991 // If there is a diagnoseable difference, FirstDiffType and
8992 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
8993 // filled in if not EndOfClass.
8994 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00008995 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
8996 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00008997 ++FirstIt;
8998 ++SecondIt;
8999 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009000 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009001
Richard Trieue7f7ed22017-02-22 01:11:25 +00009002 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9003 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9004
9005 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9006 SecondDiffType =
9007 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9008
9009 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009010 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009011
9012 if (FirstDiffType == Other || SecondDiffType == Other) {
9013 // Reaching this point means an unexpected Decl was encountered
9014 // or no difference was detected. This causes a generic error
9015 // message to be emitted.
9016 Diag(FirstRecord->getLocation(),
9017 diag::err_module_odr_violation_different_definitions)
9018 << FirstRecord << FirstModule.empty() << FirstModule;
9019
9020 Diag(SecondRecord->getLocation(),
9021 diag::note_module_odr_violation_different_definitions)
9022 << SecondModule;
9023 Diagnosed = true;
9024 break;
9025 }
9026
9027 if (FirstDiffType != SecondDiffType) {
9028 SourceLocation FirstLoc;
9029 SourceRange FirstRange;
9030 if (FirstDiffType == EndOfClass) {
9031 FirstLoc = FirstRecord->getBraceRange().getEnd();
9032 } else {
9033 FirstLoc = FirstIt->first->getLocation();
9034 FirstRange = FirstIt->first->getSourceRange();
9035 }
9036 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9037 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9038 << FirstDiffType;
9039
9040 SourceLocation SecondLoc;
9041 SourceRange SecondRange;
9042 if (SecondDiffType == EndOfClass) {
9043 SecondLoc = SecondRecord->getBraceRange().getEnd();
9044 } else {
9045 SecondLoc = SecondDecl->getLocation();
9046 SecondRange = SecondDecl->getSourceRange();
9047 }
9048 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9049 << SecondModule << SecondRange << SecondDiffType;
9050 Diagnosed = true;
9051 break;
9052 }
9053
Richard Trieu639d7b62017-02-22 22:22:42 +00009054 assert(FirstDiffType == SecondDiffType);
9055
9056 // Used with err_module_odr_violation_mismatch_decl_diff and
9057 // note_module_odr_violation_mismatch_decl_diff
9058 enum ODRDeclDifference{
9059 StaticAssertCondition,
9060 StaticAssertMessage,
9061 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009062 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009063 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009064 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009065 FieldDifferentWidthBitField,
9066 FieldSingleMutable,
9067 FieldSingleInitializer,
9068 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009069 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009070 MethodDeleted,
9071 MethodVirtual,
9072 MethodStatic,
9073 MethodVolatile,
9074 MethodConst,
9075 MethodInline,
Richard Trieu639d7b62017-02-22 22:22:42 +00009076 };
9077
9078 // These lambdas have the common portions of the ODR diagnostics. This
9079 // has the same return as Diag(), so addition parameters can be passed
9080 // in with operator<<
9081 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9082 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9083 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9084 << FirstRecord << FirstModule.empty() << FirstModule << Range
9085 << DiffType;
9086 };
9087 auto ODRDiagNote = [&SecondModule, this](
9088 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9089 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9090 << SecondModule << Range << DiffType;
9091 };
9092
9093 auto ComputeODRHash = [&Hash](const Stmt* S) {
9094 assert(S);
9095 Hash.clear();
9096 Hash.AddStmt(S);
9097 return Hash.CalculateHash();
9098 };
9099
Richard Trieu8459ddf2017-02-24 02:59:12 +00009100 auto ComputeDeclNameODRHash = [&Hash](const DeclarationName Name) {
9101 Hash.clear();
9102 Hash.AddDeclarationName(Name);
9103 return Hash.CalculateHash();
9104 };
9105
Richard Trieu639d7b62017-02-22 22:22:42 +00009106 switch (FirstDiffType) {
9107 case Other:
9108 case EndOfClass:
9109 case PublicSpecifer:
9110 case PrivateSpecifer:
9111 case ProtectedSpecifer:
9112 llvm_unreachable("Invalid diff type");
9113
9114 case StaticAssert: {
9115 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9116 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9117
9118 Expr *FirstExpr = FirstSA->getAssertExpr();
9119 Expr *SecondExpr = SecondSA->getAssertExpr();
9120 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9121 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9122 if (FirstODRHash != SecondODRHash) {
9123 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9124 StaticAssertCondition);
9125 ODRDiagNote(SecondExpr->getLocStart(),
9126 SecondExpr->getSourceRange(), StaticAssertCondition);
9127 Diagnosed = true;
9128 break;
9129 }
9130
9131 StringLiteral *FirstStr = FirstSA->getMessage();
9132 StringLiteral *SecondStr = SecondSA->getMessage();
9133 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9134 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9135 SourceLocation FirstLoc, SecondLoc;
9136 SourceRange FirstRange, SecondRange;
9137 if (FirstStr) {
9138 FirstLoc = FirstStr->getLocStart();
9139 FirstRange = FirstStr->getSourceRange();
9140 } else {
9141 FirstLoc = FirstSA->getLocStart();
9142 FirstRange = FirstSA->getSourceRange();
9143 }
9144 if (SecondStr) {
9145 SecondLoc = SecondStr->getLocStart();
9146 SecondRange = SecondStr->getSourceRange();
9147 } else {
9148 SecondLoc = SecondSA->getLocStart();
9149 SecondRange = SecondSA->getSourceRange();
9150 }
9151 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9152 << (FirstStr == nullptr);
9153 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9154 << (SecondStr == nullptr);
9155 Diagnosed = true;
9156 break;
9157 }
9158
9159 if (FirstStr && SecondStr &&
9160 FirstStr->getString() != SecondStr->getString()) {
9161 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9162 StaticAssertMessage);
9163 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9164 StaticAssertMessage);
9165 Diagnosed = true;
9166 break;
9167 }
9168 break;
9169 }
Richard Trieud0786092017-02-23 00:23:01 +00009170 case Field: {
9171 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9172 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9173 IdentifierInfo *FirstII = FirstField->getIdentifier();
9174 IdentifierInfo *SecondII = SecondField->getIdentifier();
9175 if (FirstII->getName() != SecondII->getName()) {
9176 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9177 FieldName)
9178 << FirstII;
9179 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9180 FieldName)
9181 << SecondII;
9182
9183 Diagnosed = true;
9184 break;
9185 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009186
9187 assert(
9188 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9189
9190 QualType FirstType = FirstField->getType();
9191 QualType SecondType = SecondField->getType();
9192 const TypedefType *FirstTypedef = dyn_cast<TypedefType>(FirstType);
9193 const TypedefType *SecondTypedef = dyn_cast<TypedefType>(SecondType);
9194
9195 if ((FirstTypedef && !SecondTypedef) ||
9196 (!FirstTypedef && SecondTypedef)) {
9197 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9198 FieldTypeName)
9199 << FirstII << FirstType;
9200 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9201 FieldTypeName)
9202 << SecondII << SecondType;
9203
9204 Diagnosed = true;
9205 break;
9206 }
9207
9208 if (FirstTypedef && SecondTypedef) {
9209 unsigned FirstHash = ComputeDeclNameODRHash(
9210 FirstTypedef->getDecl()->getDeclName());
9211 unsigned SecondHash = ComputeDeclNameODRHash(
9212 SecondTypedef->getDecl()->getDeclName());
9213 if (FirstHash != SecondHash) {
9214 ODRDiagError(FirstField->getLocation(),
9215 FirstField->getSourceRange(), FieldTypeName)
9216 << FirstII << FirstType;
9217 ODRDiagNote(SecondField->getLocation(),
9218 SecondField->getSourceRange(), FieldTypeName)
9219 << SecondII << SecondType;
9220
9221 Diagnosed = true;
9222 break;
9223 }
9224 }
9225
Richard Trieu93772fc2017-02-24 20:59:28 +00009226 const bool IsFirstBitField = FirstField->isBitField();
9227 const bool IsSecondBitField = SecondField->isBitField();
9228 if (IsFirstBitField != IsSecondBitField) {
9229 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9230 FieldSingleBitField)
9231 << FirstII << IsFirstBitField;
9232 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9233 FieldSingleBitField)
9234 << SecondII << IsSecondBitField;
9235 Diagnosed = true;
9236 break;
9237 }
9238
9239 if (IsFirstBitField && IsSecondBitField) {
9240 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9241 FieldDifferentWidthBitField)
9242 << FirstII << FirstField->getBitWidth()->getSourceRange();
9243 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9244 FieldDifferentWidthBitField)
9245 << SecondII << SecondField->getBitWidth()->getSourceRange();
9246 Diagnosed = true;
9247 break;
9248 }
9249
Richard Trieu8d543e22017-02-24 23:35:37 +00009250 const bool IsFirstMutable = FirstField->isMutable();
9251 const bool IsSecondMutable = SecondField->isMutable();
9252 if (IsFirstMutable != IsSecondMutable) {
9253 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9254 FieldSingleMutable)
9255 << FirstII << IsFirstMutable;
9256 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9257 FieldSingleMutable)
9258 << SecondII << IsSecondMutable;
9259 Diagnosed = true;
9260 break;
9261 }
9262
9263 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9264 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9265 if ((!FirstInitializer && SecondInitializer) ||
9266 (FirstInitializer && !SecondInitializer)) {
9267 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9268 FieldSingleInitializer)
9269 << FirstII << (FirstInitializer != nullptr);
9270 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9271 FieldSingleInitializer)
9272 << SecondII << (SecondInitializer != nullptr);
9273 Diagnosed = true;
9274 break;
9275 }
9276
9277 if (FirstInitializer && SecondInitializer) {
9278 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9279 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9280 if (FirstInitHash != SecondInitHash) {
9281 ODRDiagError(FirstField->getLocation(),
9282 FirstField->getSourceRange(),
9283 FieldDifferentInitializers)
9284 << FirstII << FirstInitializer->getSourceRange();
9285 ODRDiagNote(SecondField->getLocation(),
9286 SecondField->getSourceRange(),
9287 FieldDifferentInitializers)
9288 << SecondII << SecondInitializer->getSourceRange();
9289 Diagnosed = true;
9290 break;
9291 }
9292 }
9293
Richard Trieud0786092017-02-23 00:23:01 +00009294 break;
9295 }
Richard Trieu48143742017-02-28 21:24:38 +00009296 case CXXMethod: {
9297 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9298 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu583e2c12017-03-04 00:08:58 +00009299 auto FirstName = FirstMethod->getDeclName();
9300 auto SecondName = SecondMethod->getDeclName();
9301 if (FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009302 ODRDiagError(FirstMethod->getLocation(),
9303 FirstMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009304 << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009305 ODRDiagNote(SecondMethod->getLocation(),
9306 SecondMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009307 << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009308
9309 Diagnosed = true;
9310 break;
9311 }
9312
Richard Trieu583e2c12017-03-04 00:08:58 +00009313 const bool FirstDeleted = FirstMethod->isDeleted();
9314 const bool SecondDeleted = SecondMethod->isDeleted();
9315 if (FirstDeleted != SecondDeleted) {
9316 ODRDiagError(FirstMethod->getLocation(),
9317 FirstMethod->getSourceRange(), MethodDeleted)
9318 << FirstName << FirstDeleted;
9319
9320 ODRDiagNote(SecondMethod->getLocation(),
9321 SecondMethod->getSourceRange(), MethodDeleted)
9322 << SecondName << SecondDeleted;
9323 Diagnosed = true;
9324 break;
9325 }
9326
9327 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9328 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9329 const bool FirstPure = FirstMethod->isPure();
9330 const bool SecondPure = SecondMethod->isPure();
9331 if ((FirstVirtual || SecondVirtual) &&
9332 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9333 ODRDiagError(FirstMethod->getLocation(),
9334 FirstMethod->getSourceRange(), MethodVirtual)
9335 << FirstName << FirstPure << FirstVirtual;
9336 ODRDiagNote(SecondMethod->getLocation(),
9337 SecondMethod->getSourceRange(), MethodVirtual)
9338 << SecondName << SecondPure << SecondVirtual;
9339 Diagnosed = true;
9340 break;
9341 }
9342
9343 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9344 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9345 // class needs to be checked instead.
9346 const auto FirstStorage = FirstMethod->getStorageClass();
9347 const auto SecondStorage = SecondMethod->getStorageClass();
9348 const bool FirstStatic = FirstStorage == SC_Static;
9349 const bool SecondStatic = SecondStorage == SC_Static;
9350 if (FirstStatic != SecondStatic) {
9351 ODRDiagError(FirstMethod->getLocation(),
9352 FirstMethod->getSourceRange(), MethodStatic)
9353 << FirstName << FirstStatic;
9354 ODRDiagNote(SecondMethod->getLocation(),
9355 SecondMethod->getSourceRange(), MethodStatic)
9356 << SecondName << SecondStatic;
9357 Diagnosed = true;
9358 break;
9359 }
9360
9361 const bool FirstVolatile = FirstMethod->isVolatile();
9362 const bool SecondVolatile = SecondMethod->isVolatile();
9363 if (FirstVolatile != SecondVolatile) {
9364 ODRDiagError(FirstMethod->getLocation(),
9365 FirstMethod->getSourceRange(), MethodVolatile)
9366 << FirstName << FirstVolatile;
9367 ODRDiagNote(SecondMethod->getLocation(),
9368 SecondMethod->getSourceRange(), MethodVolatile)
9369 << SecondName << SecondVolatile;
9370 Diagnosed = true;
9371 break;
9372 }
9373
9374 const bool FirstConst = FirstMethod->isConst();
9375 const bool SecondConst = SecondMethod->isConst();
9376 if (FirstConst != SecondConst) {
9377 ODRDiagError(FirstMethod->getLocation(),
9378 FirstMethod->getSourceRange(), MethodConst)
9379 << FirstName << FirstConst;
9380 ODRDiagNote(SecondMethod->getLocation(),
9381 SecondMethod->getSourceRange(), MethodConst)
9382 << SecondName << SecondConst;
9383 Diagnosed = true;
9384 break;
9385 }
9386
9387 const bool FirstInline = FirstMethod->isInlineSpecified();
9388 const bool SecondInline = SecondMethod->isInlineSpecified();
9389 if (FirstInline != SecondInline) {
9390 ODRDiagError(FirstMethod->getLocation(),
9391 FirstMethod->getSourceRange(), MethodInline)
9392 << FirstName << FirstInline;
9393 ODRDiagNote(SecondMethod->getLocation(),
9394 SecondMethod->getSourceRange(), MethodInline)
9395 << SecondName << SecondInline;
9396 Diagnosed = true;
9397 break;
9398 }
9399
Richard Trieu48143742017-02-28 21:24:38 +00009400 break;
9401 }
Richard Trieu639d7b62017-02-22 22:22:42 +00009402 }
9403
Richard Trieue7f7ed22017-02-22 01:11:25 +00009404 if (Diagnosed == true)
9405 continue;
9406
9407 Diag(FirstRecord->getLocation(),
9408 diag::err_module_odr_violation_different_definitions)
9409 << FirstRecord << FirstModule.empty() << FirstModule;
9410
9411 Diag(SecondRecord->getLocation(),
9412 diag::note_module_odr_violation_different_definitions)
9413 << SecondModule;
9414 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009415 }
9416
9417 if (!Diagnosed) {
9418 // All definitions are updates to the same declaration. This happens if a
9419 // module instantiates the declaration of a class template specialization
9420 // and two or more other modules instantiate its definition.
9421 //
9422 // FIXME: Indicate which modules had instantiations of this definition.
9423 // FIXME: How can this even happen?
9424 Diag(Merge.first->getLocation(),
9425 diag::err_module_odr_violation_different_instantiations)
9426 << Merge.first;
9427 }
9428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009429}
9430
Richard Smithce18a182015-07-14 00:26:00 +00009431void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009432 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009433 ReadTimer->startTimer();
9434}
9435
Guy Benyei11169dd2012-12-18 14:30:41 +00009436void ASTReader::FinishedDeserializing() {
9437 assert(NumCurrentElementsDeserializing &&
9438 "FinishedDeserializing not paired with StartedDeserializing");
9439 if (NumCurrentElementsDeserializing == 1) {
9440 // We decrease NumCurrentElementsDeserializing only after pending actions
9441 // are finished, to avoid recursively re-calling finishPendingActions().
9442 finishPendingActions();
9443 }
9444 --NumCurrentElementsDeserializing;
9445
Richard Smitha0ce9c42014-07-29 23:23:27 +00009446 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009447 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009448 while (!PendingExceptionSpecUpdates.empty()) {
9449 auto Updates = std::move(PendingExceptionSpecUpdates);
9450 PendingExceptionSpecUpdates.clear();
9451 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009452 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009453 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009454 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009455 if (auto *Listener = Context.getASTMutationListener())
9456 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009457 for (auto *Redecl : Update.second->redecls())
9458 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009459 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009460 }
9461
Richard Smithce18a182015-07-14 00:26:00 +00009462 if (ReadTimer)
9463 ReadTimer->stopTimer();
9464
Richard Smith0f4e2c42015-08-06 04:23:48 +00009465 diagnoseOdrViolations();
9466
Richard Smith04d05b52014-03-23 00:27:18 +00009467 // We are not in recursive loading, so it's safe to pass the "interesting"
9468 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009469 if (Consumer)
9470 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009471 }
9472}
9473
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009474void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009475 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9476 // Remove any fake results before adding any real ones.
9477 auto It = PendingFakeLookupResults.find(II);
9478 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009479 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009480 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009481 // FIXME: this works around module+PCH performance issue.
9482 // Rather than erase the result from the map, which is O(n), just clear
9483 // the vector of NamedDecls.
9484 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009485 }
9486 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009487
9488 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9489 SemaObj->TUScope->AddDecl(D);
9490 } else if (SemaObj->TUScope) {
9491 // Adding the decl to IdResolver may have failed because it was already in
9492 // (even though it was not added in scope). If it is already in, make sure
9493 // it gets in the scope as well.
9494 if (std::find(SemaObj->IdResolver.begin(Name),
9495 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9496 SemaObj->TUScope->AddDecl(D);
9497 }
9498}
9499
David Blaikie61137e12017-01-05 18:23:18 +00009500ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9501 const PCHContainerReader &PCHContainerRdr,
9502 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9503 StringRef isysroot, bool DisableValidation,
9504 bool AllowASTWithCompilerErrors,
9505 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9506 bool UseGlobalIndex,
9507 std::unique_ptr<llvm::Timer> ReadTimer)
9508 : Listener(DisableValidation
9509 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9510 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009511 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009512 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9513 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9514 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009515 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009516 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9517 AllowConfigurationMismatch(AllowConfigurationMismatch),
9518 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009519 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009520 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009521
9522 for (const auto &Ext : Extensions) {
9523 auto BlockName = Ext->getExtensionMetadata().BlockName;
9524 auto Known = ModuleFileExtensions.find(BlockName);
9525 if (Known != ModuleFileExtensions.end()) {
9526 Diags.Report(diag::warn_duplicate_module_file_extension)
9527 << BlockName;
9528 continue;
9529 }
9530
9531 ModuleFileExtensions.insert({BlockName, Ext});
9532 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009533}
9534
9535ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009536 if (OwnsDeserializationListener)
9537 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009538}
Richard Smith10379092016-05-06 23:14:07 +00009539
9540IdentifierResolver &ASTReader::getIdResolver() {
9541 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9542}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009543
9544unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9545 unsigned AbbrevID) {
9546 Idx = 0;
9547 Record.clear();
9548 return Cursor.readRecord(AbbrevID, Record);
9549}