blob: 8ce118ce7100fc0adbb033fd7e8ed0d28e3486cd [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Type.h"
31#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "clang/Basic/FileSystemOptions.h"
38#include "clang/Basic/LangOptions.h"
39#include "clang/Basic/ObjCRuntime.h"
40#include "clang/Basic/OperatorKinds.h"
41#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "clang/Basic/Version.h"
49#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "clang/Lex/HeaderSearch.h"
52#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Lex/PreprocessingRecord.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/Scope.h"
59#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000062#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ModuleManager.h"
64#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000068#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000073#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000074#include "llvm/Support/Compiler.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "llvm/Support/ErrorHandling.h"
76#include "llvm/Support/FileSystem.h"
77#include "llvm/Support/MemoryBuffer.h"
78#include "llvm/Support/Path.h"
79#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000080#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000081#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000082#include <cassert>
83#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000084#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000085#include <cstring>
86#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000087#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include <limits>
89#include <map>
90#include <memory>
91#include <new>
92#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000093#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000094#include <tuple>
95#include <utility>
96#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000097
98using namespace clang;
99using namespace clang::serialization;
100using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000101using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102
Ben Langmuircb69b572014-03-07 06:40:32 +0000103//===----------------------------------------------------------------------===//
104// ChainedASTReaderListener implementation
105//===----------------------------------------------------------------------===//
106
107bool
108ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
109 return First->ReadFullVersionInformation(FullVersion) ||
110 Second->ReadFullVersionInformation(FullVersion);
111}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000112
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000113void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
114 First->ReadModuleName(ModuleName);
115 Second->ReadModuleName(ModuleName);
116}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000117
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000118void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
119 First->ReadModuleMapFile(ModuleMapPath);
120 Second->ReadModuleMapFile(ModuleMapPath);
121}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000123bool
124ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
125 bool Complain,
126 bool AllowCompatibleDifferences) {
127 return First->ReadLanguageOptions(LangOpts, Complain,
128 AllowCompatibleDifferences) ||
129 Second->ReadLanguageOptions(LangOpts, Complain,
130 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000132
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000133bool ChainedASTReaderListener::ReadTargetOptions(
134 const TargetOptions &TargetOpts, bool Complain,
135 bool AllowCompatibleDifferences) {
136 return First->ReadTargetOptions(TargetOpts, Complain,
137 AllowCompatibleDifferences) ||
138 Second->ReadTargetOptions(TargetOpts, Complain,
139 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000140}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000141
Ben Langmuircb69b572014-03-07 06:40:32 +0000142bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000143 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000144 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
145 Second->ReadDiagnosticOptions(DiagOpts, Complain);
146}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000147
Ben Langmuircb69b572014-03-07 06:40:32 +0000148bool
149ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
150 bool Complain) {
151 return First->ReadFileSystemOptions(FSOpts, Complain) ||
152 Second->ReadFileSystemOptions(FSOpts, Complain);
153}
154
155bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000156 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
157 bool Complain) {
158 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
159 Complain) ||
160 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
161 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000162}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000163
Ben Langmuircb69b572014-03-07 06:40:32 +0000164bool ChainedASTReaderListener::ReadPreprocessorOptions(
165 const PreprocessorOptions &PPOpts, bool Complain,
166 std::string &SuggestedPredefines) {
167 return First->ReadPreprocessorOptions(PPOpts, Complain,
168 SuggestedPredefines) ||
169 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
170}
171void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
172 unsigned Value) {
173 First->ReadCounter(M, Value);
174 Second->ReadCounter(M, Value);
175}
176bool ChainedASTReaderListener::needsInputFileVisitation() {
177 return First->needsInputFileVisitation() ||
178 Second->needsInputFileVisitation();
179}
180bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
181 return First->needsSystemInputFileVisitation() ||
182 Second->needsSystemInputFileVisitation();
183}
Richard Smith216a3bd2015-08-13 17:57:10 +0000184void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
185 ModuleKind Kind) {
186 First->visitModuleFile(Filename, Kind);
187 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000188}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000189
Ben Langmuircb69b572014-03-07 06:40:32 +0000190bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000191 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000192 bool isOverridden,
193 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000194 bool Continue = false;
195 if (First->needsInputFileVisitation() &&
196 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000197 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
198 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000199 if (Second->needsInputFileVisitation() &&
200 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000201 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
202 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000203 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000204}
205
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000206void ChainedASTReaderListener::readModuleFileExtension(
207 const ModuleFileExtensionMetadata &Metadata) {
208 First->readModuleFileExtension(Metadata);
209 Second->readModuleFileExtension(Metadata);
210}
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212//===----------------------------------------------------------------------===//
213// PCH validator implementation
214//===----------------------------------------------------------------------===//
215
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000216ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000217
218/// \brief Compare the given set of language options against an existing set of
219/// language options.
220///
221/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000222/// \param AllowCompatibleDifferences If true, differences between compatible
223/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000224///
225/// \returns true if the languagae options mis-match, false otherwise.
226static bool checkLanguageOptions(const LangOptions &LangOpts,
227 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000228 DiagnosticsEngine *Diags,
229 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000230#define LANGOPT(Name, Bits, Default, Description) \
231 if (ExistingLangOpts.Name != LangOpts.Name) { \
232 if (Diags) \
233 Diags->Report(diag::err_pch_langopt_mismatch) \
234 << Description << LangOpts.Name << ExistingLangOpts.Name; \
235 return true; \
236 }
237
238#define VALUE_LANGOPT(Name, Bits, Default, Description) \
239 if (ExistingLangOpts.Name != LangOpts.Name) { \
240 if (Diags) \
241 Diags->Report(diag::err_pch_langopt_value_mismatch) \
242 << Description; \
243 return true; \
244 }
245
246#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
247 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_langopt_value_mismatch) \
250 << Description; \
251 return true; \
252 }
253
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000254#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
255 if (!AllowCompatibleDifferences) \
256 LANGOPT(Name, Bits, Default, Description)
257
258#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
259 if (!AllowCompatibleDifferences) \
260 ENUM_LANGOPT(Name, Bits, Default, Description)
261
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000262#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
263 if (!AllowCompatibleDifferences) \
264 VALUE_LANGOPT(Name, Bits, Default, Description)
265
Guy Benyei11169dd2012-12-18 14:30:41 +0000266#define BENIGN_LANGOPT(Name, Bits, Default, Description)
267#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000268#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#include "clang/Basic/LangOptions.def"
270
Ben Langmuircd98cb72015-06-23 18:20:18 +0000271 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
272 if (Diags)
273 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
274 return true;
275 }
276
Guy Benyei11169dd2012-12-18 14:30:41 +0000277 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
278 if (Diags)
279 Diags->Report(diag::err_pch_langopt_value_mismatch)
280 << "target Objective-C runtime";
281 return true;
282 }
283
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000284 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
285 LangOpts.CommentOpts.BlockCommandNames) {
286 if (Diags)
287 Diags->Report(diag::err_pch_langopt_value_mismatch)
288 << "block command names";
289 return true;
290 }
291
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 return false;
293}
294
295/// \brief Compare the given set of target options against an existing set of
296/// target options.
297///
298/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
299///
300/// \returns true if the target options mis-match, false otherwise.
301static bool checkTargetOptions(const TargetOptions &TargetOpts,
302 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 DiagnosticsEngine *Diags,
304 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000305#define CHECK_TARGET_OPT(Field, Name) \
306 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
307 if (Diags) \
308 Diags->Report(diag::err_pch_targetopt_mismatch) \
309 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
310 return true; \
311 }
312
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316
317 // We can tolerate different CPUs in many cases, notably when one CPU
318 // supports a strict superset of another. When allowing compatible
319 // differences skip this check.
320 if (!AllowCompatibleDifferences)
321 CHECK_TARGET_OPT(CPU, "target CPU");
322
Guy Benyei11169dd2012-12-18 14:30:41 +0000323#undef CHECK_TARGET_OPT
324
325 // Compare feature sets.
326 SmallVector<StringRef, 4> ExistingFeatures(
327 ExistingTargetOpts.FeaturesAsWritten.begin(),
328 ExistingTargetOpts.FeaturesAsWritten.end());
329 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
330 TargetOpts.FeaturesAsWritten.end());
331 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
332 std::sort(ReadFeatures.begin(), ReadFeatures.end());
333
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000334 // We compute the set difference in both directions explicitly so that we can
335 // diagnose the differences differently.
336 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
337 std::set_difference(
338 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
339 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
340 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
341 ExistingFeatures.begin(), ExistingFeatures.end(),
342 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000343
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000344 // If we are allowing compatible differences and the read feature set is
345 // a strict subset of the existing feature set, there is nothing to diagnose.
346 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
347 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000348
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000349 if (Diags) {
350 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000351 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000352 << /* is-existing-feature */ false << Feature;
353 for (StringRef Feature : UnmatchedExistingFeatures)
354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
355 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000356 }
357
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000358 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000359}
360
361bool
362PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000363 bool Complain,
364 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 const LangOptions &ExistingLangOpts = PP.getLangOpts();
366 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000367 Complain ? &Reader.Diags : nullptr,
368 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000369}
370
371bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000372 bool Complain,
373 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000374 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
375 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000376 Complain ? &Reader.Diags : nullptr,
377 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000378}
379
380namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000381
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
383 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000384 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
385 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000386
387} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000388
Ben Langmuirb92de022014-04-29 16:25:26 +0000389static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
390 DiagnosticsEngine &Diags,
391 bool Complain) {
392 typedef DiagnosticsEngine::Level Level;
393
394 // Check current mappings for new -Werror mappings, and the stored mappings
395 // for cases that were explicitly mapped to *not* be errors that are now
396 // errors because of options like -Werror.
397 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
398
399 for (DiagnosticsEngine *MappingSource : MappingSources) {
400 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
401 diag::kind DiagID = DiagIDMappingPair.first;
402 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
403 if (CurLevel < DiagnosticsEngine::Error)
404 continue; // not significant
405 Level StoredLevel =
406 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
407 if (StoredLevel < DiagnosticsEngine::Error) {
408 if (Complain)
409 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
410 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
411 return true;
412 }
413 }
414 }
415
416 return false;
417}
418
Alp Tokerac4e8e52014-06-22 21:58:33 +0000419static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
420 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
421 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
422 return true;
423 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000424}
425
426static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
427 DiagnosticsEngine &Diags,
428 bool IsSystem, bool Complain) {
429 // Top-level options
430 if (IsSystem) {
431 if (Diags.getSuppressSystemWarnings())
432 return false;
433 // If -Wsystem-headers was not enabled before, be conservative
434 if (StoredDiags.getSuppressSystemWarnings()) {
435 if (Complain)
436 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
437 return true;
438 }
439 }
440
441 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
442 if (Complain)
443 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
444 return true;
445 }
446
447 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
448 !StoredDiags.getEnableAllWarnings()) {
449 if (Complain)
450 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
451 return true;
452 }
453
454 if (isExtHandlingFromDiagsError(Diags) &&
455 !isExtHandlingFromDiagsError(StoredDiags)) {
456 if (Complain)
457 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
458 return true;
459 }
460
461 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
462}
463
464bool PCHValidator::ReadDiagnosticOptions(
465 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
466 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
467 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
468 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000469 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000470 // This should never fail, because we would have processed these options
471 // before writing them to an ASTFile.
472 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
473
474 ModuleManager &ModuleMgr = Reader.getModuleManager();
475 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
476
477 // If the original import came from a file explicitly generated by the user,
478 // don't check the diagnostic mappings.
479 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000480 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000481 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
482 // the transitive closure of its imports, since unrelated modules cannot be
483 // imported until after this module finishes validation.
484 ModuleFile *TopImport = *ModuleMgr.rbegin();
485 while (!TopImport->ImportedBy.empty())
486 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000487 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000488 return false;
489
490 StringRef ModuleName = TopImport->ModuleName;
491 assert(!ModuleName.empty() && "diagnostic options read before module name");
492
493 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
494 assert(M && "missing module");
495
496 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
497 // contains the union of their flags.
498 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
499}
500
Guy Benyei11169dd2012-12-18 14:30:41 +0000501/// \brief Collect the macro definitions provided by the given preprocessor
502/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000503static void
504collectMacroDefinitions(const PreprocessorOptions &PPOpts,
505 MacroDefinitionsMap &Macros,
506 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
508 StringRef Macro = PPOpts.Macros[I].first;
509 bool IsUndef = PPOpts.Macros[I].second;
510
511 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
512 StringRef MacroName = MacroPair.first;
513 StringRef MacroBody = MacroPair.second;
514
515 // For an #undef'd macro, we only care about the name.
516 if (IsUndef) {
517 if (MacroNames && !Macros.count(MacroName))
518 MacroNames->push_back(MacroName);
519
520 Macros[MacroName] = std::make_pair("", true);
521 continue;
522 }
523
524 // For a #define'd macro, figure out the actual definition.
525 if (MacroName.size() == Macro.size())
526 MacroBody = "1";
527 else {
528 // Note: GCC drops anything following an end-of-line character.
529 StringRef::size_type End = MacroBody.find_first_of("\n\r");
530 MacroBody = MacroBody.substr(0, End);
531 }
532
533 if (MacroNames && !Macros.count(MacroName))
534 MacroNames->push_back(MacroName);
535 Macros[MacroName] = std::make_pair(MacroBody, false);
536 }
537}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000538
Guy Benyei11169dd2012-12-18 14:30:41 +0000539/// \brief Check the preprocessor options deserialized from the control block
540/// against the preprocessor options in an existing preprocessor.
541///
542/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000543/// \param Validate If true, validate preprocessor options. If false, allow
544/// macros defined by \p ExistingPPOpts to override those defined by
545/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000546static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
547 const PreprocessorOptions &ExistingPPOpts,
548 DiagnosticsEngine *Diags,
549 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000550 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000551 const LangOptions &LangOpts,
552 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 // Check macro definitions.
554 MacroDefinitionsMap ASTFileMacros;
555 collectMacroDefinitions(PPOpts, ASTFileMacros);
556 MacroDefinitionsMap ExistingMacros;
557 SmallVector<StringRef, 4> ExistingMacroNames;
558 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
559
560 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
561 // Dig out the macro definition in the existing preprocessor options.
562 StringRef MacroName = ExistingMacroNames[I];
563 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
564
565 // Check whether we know anything about this macro name or not.
566 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
567 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000568 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 // FIXME: Check whether this identifier was referenced anywhere in the
570 // AST file. If so, we should reject the AST file. Unfortunately, this
571 // information isn't in the control block. What shall we do about it?
572
573 if (Existing.second) {
574 SuggestedPredefines += "#undef ";
575 SuggestedPredefines += MacroName.str();
576 SuggestedPredefines += '\n';
577 } else {
578 SuggestedPredefines += "#define ";
579 SuggestedPredefines += MacroName.str();
580 SuggestedPredefines += ' ';
581 SuggestedPredefines += Existing.first.str();
582 SuggestedPredefines += '\n';
583 }
584 continue;
585 }
586
587 // If the macro was defined in one but undef'd in the other, we have a
588 // conflict.
589 if (Existing.second != Known->second.second) {
590 if (Diags) {
591 Diags->Report(diag::err_pch_macro_def_undef)
592 << MacroName << Known->second.second;
593 }
594 return true;
595 }
596
597 // If the macro was #undef'd in both, or if the macro bodies are identical,
598 // it's fine.
599 if (Existing.second || Existing.first == Known->second.first)
600 continue;
601
602 // The macro bodies differ; complain.
603 if (Diags) {
604 Diags->Report(diag::err_pch_macro_def_conflict)
605 << MacroName << Known->second.first << Existing.first;
606 }
607 return true;
608 }
609
610 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000611 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000612 if (Diags) {
613 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
614 }
615 return true;
616 }
617
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000618 // Detailed record is important since it is used for the module cache hash.
619 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000620 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000621 if (Diags) {
622 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
623 }
624 return true;
625 }
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 // Compute the #include and #include_macros lines we need.
628 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
629 StringRef File = ExistingPPOpts.Includes[I];
630 if (File == ExistingPPOpts.ImplicitPCHInclude)
631 continue;
632
633 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
634 != PPOpts.Includes.end())
635 continue;
636
637 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000638 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 SuggestedPredefines += "\"\n";
640 }
641
642 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
643 StringRef File = ExistingPPOpts.MacroIncludes[I];
644 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
645 File)
646 != PPOpts.MacroIncludes.end())
647 continue;
648
649 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000650 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 SuggestedPredefines += "\"\n##\n";
652 }
653
654 return false;
655}
656
657bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
658 bool Complain,
659 std::string &SuggestedPredefines) {
660 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
661
662 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000663 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000665 SuggestedPredefines,
666 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000667}
668
Yaxun Liu43712e02016-09-07 18:40:20 +0000669bool SimpleASTReaderListener::ReadPreprocessorOptions(
670 const PreprocessorOptions &PPOpts,
671 bool Complain,
672 std::string &SuggestedPredefines) {
673 return checkPreprocessorOptions(PPOpts,
674 PP.getPreprocessorOpts(),
675 nullptr,
676 PP.getFileManager(),
677 SuggestedPredefines,
678 PP.getLangOpts(),
679 false);
680}
681
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000682/// Check the header search options deserialized from the control block
683/// against the header search options in an existing preprocessor.
684///
685/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
686static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
687 StringRef SpecificModuleCachePath,
688 StringRef ExistingModuleCachePath,
689 DiagnosticsEngine *Diags,
690 const LangOptions &LangOpts) {
691 if (LangOpts.Modules) {
692 if (SpecificModuleCachePath != ExistingModuleCachePath) {
693 if (Diags)
694 Diags->Report(diag::err_pch_modulecache_mismatch)
695 << SpecificModuleCachePath << ExistingModuleCachePath;
696 return true;
697 }
698 }
699
700 return false;
701}
702
703bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
704 StringRef SpecificModuleCachePath,
705 bool Complain) {
706 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
707 PP.getHeaderSearchInfo().getModuleCachePath(),
708 Complain ? &Reader.Diags : nullptr,
709 PP.getLangOpts());
710}
711
Guy Benyei11169dd2012-12-18 14:30:41 +0000712void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
713 PP.setCounterValue(Value);
714}
715
716//===----------------------------------------------------------------------===//
717// AST reader implementation
718//===----------------------------------------------------------------------===//
719
Nico Weber824285e2014-05-08 04:26:47 +0000720void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
721 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000723 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000724}
725
Guy Benyei11169dd2012-12-18 14:30:41 +0000726unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
727 return serialization::ComputeHash(Sel);
728}
729
Guy Benyei11169dd2012-12-18 14:30:41 +0000730std::pair<unsigned, unsigned>
731ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000732 using namespace llvm::support;
733 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
734 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 return std::make_pair(KeyLen, DataLen);
736}
737
738ASTSelectorLookupTrait::internal_key_type
739ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000740 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000742 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
743 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
744 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 if (N == 0)
746 return SelTable.getNullarySelector(FirstII);
747 else if (N == 1)
748 return SelTable.getUnarySelector(FirstII);
749
750 SmallVector<IdentifierInfo *, 16> Args;
751 Args.push_back(FirstII);
752 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000753 Args.push_back(Reader.getLocalIdentifier(
754 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000755
756 return SelTable.getSelector(N, Args.data());
757}
758
759ASTSelectorLookupTrait::data_type
760ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
761 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000762 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000763
764 data_type Result;
765
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 Result.ID = Reader.getGlobalSelectorID(
767 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000768 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
769 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
770 Result.InstanceBits = FullInstanceBits & 0x3;
771 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
772 Result.FactoryBits = FullFactoryBits & 0x3;
773 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
774 unsigned NumInstanceMethods = FullInstanceBits >> 3;
775 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000776
777 // Load instance methods
778 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000779 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
780 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Result.Instance.push_back(Method);
782 }
783
784 // Load factory methods
785 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000786 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
787 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 Result.Factory.push_back(Method);
789 }
790
791 return Result;
792}
793
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000794unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
795 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000796}
797
798std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000799ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000800 using namespace llvm::support;
801 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
802 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000803 return std::make_pair(KeyLen, DataLen);
804}
805
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000806ASTIdentifierLookupTraitBase::internal_key_type
807ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000809 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000810}
811
Douglas Gregordcf25082013-02-11 18:16:18 +0000812/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000813static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
814 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000815 return II.hadMacroDefinition() ||
816 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000817 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000818 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000819 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
820 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000821}
822
Richard Smith76c2f2c2015-07-17 20:09:43 +0000823static bool readBit(unsigned &Bits) {
824 bool Value = Bits & 0x1;
825 Bits >>= 1;
826 return Value;
827}
828
Richard Smith79bf9202015-08-24 03:33:22 +0000829IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
830 using namespace llvm::support;
831 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
832 return Reader.getGlobalIdentifierID(F, RawID >> 1);
833}
834
Richard Smitheb4b58f62016-02-05 01:40:54 +0000835static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
836 if (!II.isFromAST()) {
837 II.setIsFromAST();
838 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
839 if (isInterestingIdentifier(Reader, II, IsModule))
840 II.setChangedSinceDeserialization();
841 }
842}
843
Guy Benyei11169dd2012-12-18 14:30:41 +0000844IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
845 const unsigned char* d,
846 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000847 using namespace llvm::support;
848 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 bool IsInteresting = RawID & 0x01;
850
851 // Wipe out the "is interesting" bit.
852 RawID = RawID >> 1;
853
Richard Smith76c2f2c2015-07-17 20:09:43 +0000854 // Build the IdentifierInfo and link the identifier ID with it.
855 IdentifierInfo *II = KnownII;
856 if (!II) {
857 II = &Reader.getIdentifierTable().getOwn(k);
858 KnownII = II;
859 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000860 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000861 Reader.markIdentifierUpToDate(II);
862
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
864 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000865 // For uninteresting identifiers, there's nothing else to do. Just notify
866 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 return II;
869 }
870
Justin Bogner57ba0b22014-03-28 22:03:24 +0000871 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
872 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000873 bool CPlusPlusOperatorKeyword = readBit(Bits);
874 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000875 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000876 bool Poisoned = readBit(Bits);
877 bool ExtensionToken = readBit(Bits);
878 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000879
880 assert(Bits == 0 && "Extra bits in the identifier?");
881 DataLen -= 8;
882
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 // Set or check the various bits in the IdentifierInfo structure.
884 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000885 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000886 II->revertTokenIDToIdentifier();
887 if (!F.isModule())
888 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
889 else if (HasRevertedBuiltin && II->getBuiltinID()) {
890 II->revertBuiltin();
891 assert((II->hasRevertedBuiltin() ||
892 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
893 "Incorrect ObjC keyword or builtin ID");
894 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000895 assert(II->isExtensionToken() == ExtensionToken &&
896 "Incorrect extension token flag");
897 (void)ExtensionToken;
898 if (Poisoned)
899 II->setIsPoisoned(true);
900 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
901 "Incorrect C++ operator keyword flag");
902 (void)CPlusPlusOperatorKeyword;
903
904 // If this identifier is a macro, deserialize the macro
905 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000906 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000907 uint32_t MacroDirectivesOffset =
908 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000909 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000910
Richard Smithd7329392015-04-21 21:46:32 +0000911 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 }
913
914 Reader.SetIdentifierInfo(ID, II);
915
916 // Read all of the declarations visible at global scope with this
917 // name.
918 if (DataLen > 0) {
919 SmallVector<uint32_t, 4> DeclIDs;
920 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000921 DeclIDs.push_back(Reader.getGlobalDeclID(
922 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000923 Reader.SetGloballyVisibleDecls(II, DeclIDs);
924 }
925
926 return II;
927}
928
Richard Smitha06c7e62015-08-26 23:55:49 +0000929DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
930 : Kind(Name.getNameKind()) {
931 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000933 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 break;
935 case DeclarationName::ObjCZeroArgSelector:
936 case DeclarationName::ObjCOneArgSelector:
937 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000938 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000941 Data = Name.getCXXOverloadedOperator();
942 break;
943 case DeclarationName::CXXLiteralOperatorName:
944 Data = (uint64_t)Name.getCXXLiteralIdentifier();
945 break;
946 case DeclarationName::CXXConstructorName:
947 case DeclarationName::CXXDestructorName:
948 case DeclarationName::CXXConversionFunctionName:
949 case DeclarationName::CXXUsingDirective:
950 Data = 0;
951 break;
952 }
953}
954
955unsigned DeclarationNameKey::getHash() const {
956 llvm::FoldingSetNodeID ID;
957 ID.AddInteger(Kind);
958
959 switch (Kind) {
960 case DeclarationName::Identifier:
961 case DeclarationName::CXXLiteralOperatorName:
962 ID.AddString(((IdentifierInfo*)Data)->getName());
963 break;
964 case DeclarationName::ObjCZeroArgSelector:
965 case DeclarationName::ObjCOneArgSelector:
966 case DeclarationName::ObjCMultiArgSelector:
967 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
968 break;
969 case DeclarationName::CXXOperatorName:
970 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 break;
972 case DeclarationName::CXXConstructorName:
973 case DeclarationName::CXXDestructorName:
974 case DeclarationName::CXXConversionFunctionName:
975 case DeclarationName::CXXUsingDirective:
976 break;
977 }
978
979 return ID.ComputeHash();
980}
981
Richard Smithd88a7f12015-09-01 20:35:42 +0000982ModuleFile *
983ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
984 using namespace llvm::support;
985 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
986 return Reader.getLocalModuleFile(F, ModuleFileID);
987}
988
Guy Benyei11169dd2012-12-18 14:30:41 +0000989std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000990ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000991 using namespace llvm::support;
992 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
993 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 return std::make_pair(KeyLen, DataLen);
995}
996
Richard Smitha06c7e62015-08-26 23:55:49 +0000997ASTDeclContextNameLookupTrait::internal_key_type
998ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000999 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001000
Richard Smitha06c7e62015-08-26 23:55:49 +00001001 auto Kind = (DeclarationName::NameKind)*d++;
1002 uint64_t Data;
1003 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001005 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001006 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001007 break;
1008 case DeclarationName::ObjCZeroArgSelector:
1009 case DeclarationName::ObjCOneArgSelector:
1010 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001011 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001012 (uint64_t)Reader.getLocalSelector(
1013 F, endian::readNext<uint32_t, little, unaligned>(
1014 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001017 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 break;
1019 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001021 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 break;
1023 case DeclarationName::CXXConstructorName:
1024 case DeclarationName::CXXDestructorName:
1025 case DeclarationName::CXXConversionFunctionName:
1026 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001027 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 break;
1029 }
1030
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032}
1033
Richard Smithd88a7f12015-09-01 20:35:42 +00001034void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1035 const unsigned char *d,
1036 unsigned DataLen,
1037 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001038 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001039 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1040 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1041 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001043}
1044
Richard Smith0f4e2c42015-08-06 04:23:48 +00001045bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1046 BitstreamCursor &Cursor,
1047 uint64_t Offset,
1048 DeclContext *DC) {
1049 assert(Offset != 0);
1050
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001052 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001053
Richard Smith0f4e2c42015-08-06 04:23:48 +00001054 RecordData Record;
1055 StringRef Blob;
1056 unsigned Code = Cursor.ReadCode();
1057 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1058 if (RecCode != DECL_CONTEXT_LEXICAL) {
1059 Error("Expected lexical block");
1060 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 }
1062
Richard Smith82f8fcd2015-08-06 22:07:25 +00001063 assert(!isa<TranslationUnitDecl>(DC) &&
1064 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001065 // If we are handling a C++ class template instantiation, we can see multiple
1066 // lexical updates for the same record. It's important that we select only one
1067 // of them, so that field numbering works properly. Just pick the first one we
1068 // see.
1069 auto &Lex = LexicalDecls[DC];
1070 if (!Lex.first) {
1071 Lex = std::make_pair(
1072 &M, llvm::makeArrayRef(
1073 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1074 Blob.data()),
1075 Blob.size() / 4));
1076 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001077 DC->setHasExternalLexicalStorage(true);
1078 return false;
1079}
Guy Benyei11169dd2012-12-18 14:30:41 +00001080
Richard Smith0f4e2c42015-08-06 04:23:48 +00001081bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1082 BitstreamCursor &Cursor,
1083 uint64_t Offset,
1084 DeclID ID) {
1085 assert(Offset != 0);
1086
1087 SavedStreamPosition SavedPosition(Cursor);
1088 Cursor.JumpToBit(Offset);
1089
1090 RecordData Record;
1091 StringRef Blob;
1092 unsigned Code = Cursor.ReadCode();
1093 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1094 if (RecCode != DECL_CONTEXT_VISIBLE) {
1095 Error("Expected visible lookup table block");
1096 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 }
1098
Richard Smith0f4e2c42015-08-06 04:23:48 +00001099 // We can't safely determine the primary context yet, so delay attaching the
1100 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001101 auto *Data = (const unsigned char*)Blob.data();
1102 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 return false;
1104}
1105
1106void ASTReader::Error(StringRef Msg) {
1107 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001108 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1109 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001110 Diag(diag::note_module_cache_path)
1111 << PP.getHeaderSearchInfo().getModuleCachePath();
1112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001113}
1114
1115void ASTReader::Error(unsigned DiagID,
1116 StringRef Arg1, StringRef Arg2) {
1117 if (Diags.isDiagnosticInFlight())
1118 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1119 else
1120 Diag(DiagID) << Arg1 << Arg2;
1121}
1122
1123//===----------------------------------------------------------------------===//
1124// Source Manager Deserialization
1125//===----------------------------------------------------------------------===//
1126
1127/// \brief Read the line table in the source manager block.
1128/// \returns true if there was an error.
1129bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001130 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 unsigned Idx = 0;
1132 LineTableInfo &LineTable = SourceMgr.getLineTable();
1133
1134 // Parse the file names
1135 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001136 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001137 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001138 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1140 }
Richard Smith63078492015-09-01 07:41:55 +00001141 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001142
1143 // Parse the line entries
1144 std::vector<LineEntry> Entries;
1145 while (Idx < Record.size()) {
1146 int FID = Record[Idx++];
1147 assert(FID >= 0 && "Serialized line entries for non-local file.");
1148 // Remap FileID from 1-based old view.
1149 FID += F.SLocEntryBaseID - 1;
1150
1151 // Extract the line entries
1152 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001153 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 Entries.clear();
1155 Entries.reserve(NumEntries);
1156 for (unsigned I = 0; I != NumEntries; ++I) {
1157 unsigned FileOffset = Record[Idx++];
1158 unsigned LineNo = Record[Idx++];
1159 int FilenameID = FileIDs[Record[Idx++]];
1160 SrcMgr::CharacteristicKind FileKind
1161 = (SrcMgr::CharacteristicKind)Record[Idx++];
1162 unsigned IncludeOffset = Record[Idx++];
1163 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1164 FileKind, IncludeOffset));
1165 }
1166 LineTable.AddEntry(FileID::get(FID), Entries);
1167 }
1168
1169 return false;
1170}
1171
1172/// \brief Read a source manager block
1173bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1174 using namespace SrcMgr;
1175
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001176 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001177
1178 // Set the source-location entry cursor to the current position in
1179 // the stream. This cursor will be used to read the contents of the
1180 // source manager block initially, and then lazily read
1181 // source-location entries as needed.
1182 SLocEntryCursor = F.Stream;
1183
1184 // The stream itself is going to skip over the source manager block.
1185 if (F.Stream.SkipBlock()) {
1186 Error("malformed block record in AST file");
1187 return true;
1188 }
1189
1190 // Enter the source manager block.
1191 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1192 Error("malformed source manager block record in AST file");
1193 return true;
1194 }
1195
1196 RecordData Record;
1197 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001198 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1199
1200 switch (E.Kind) {
1201 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1202 case llvm::BitstreamEntry::Error:
1203 Error("malformed block record in AST file");
1204 return true;
1205 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001207 case llvm::BitstreamEntry::Record:
1208 // The interesting case.
1209 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001211
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001214 StringRef Blob;
1215 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 default: // Default behavior: ignore.
1217 break;
1218
1219 case SM_SLOC_FILE_ENTRY:
1220 case SM_SLOC_BUFFER_ENTRY:
1221 case SM_SLOC_EXPANSION_ENTRY:
1222 // Once we hit one of the source location entries, we're done.
1223 return false;
1224 }
1225 }
1226}
1227
1228/// \brief If a header file is not found at the path that we expect it to be
1229/// and the PCH file was moved from its original location, try to resolve the
1230/// file by assuming that header+PCH were moved together and the header is in
1231/// the same place relative to the PCH.
1232static std::string
1233resolveFileRelativeToOriginalDir(const std::string &Filename,
1234 const std::string &OriginalDir,
1235 const std::string &CurrDir) {
1236 assert(OriginalDir != CurrDir &&
1237 "No point trying to resolve the file if the PCH dir didn't change");
1238 using namespace llvm::sys;
1239 SmallString<128> filePath(Filename);
1240 fs::make_absolute(filePath);
1241 assert(path::is_absolute(OriginalDir));
1242 SmallString<128> currPCHPath(CurrDir);
1243
1244 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1245 fileDirE = path::end(path::parent_path(filePath));
1246 path::const_iterator origDirI = path::begin(OriginalDir),
1247 origDirE = path::end(OriginalDir);
1248 // Skip the common path components from filePath and OriginalDir.
1249 while (fileDirI != fileDirE && origDirI != origDirE &&
1250 *fileDirI == *origDirI) {
1251 ++fileDirI;
1252 ++origDirI;
1253 }
1254 for (; origDirI != origDirE; ++origDirI)
1255 path::append(currPCHPath, "..");
1256 path::append(currPCHPath, fileDirI, fileDirE);
1257 path::append(currPCHPath, path::filename(Filename));
1258 return currPCHPath.str();
1259}
1260
1261bool ASTReader::ReadSLocEntry(int ID) {
1262 if (ID == 0)
1263 return false;
1264
1265 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1266 Error("source location entry ID out-of-range for AST file");
1267 return true;
1268 }
1269
Richard Smithaada85c2016-02-06 02:06:43 +00001270 // Local helper to read the (possibly-compressed) buffer data following the
1271 // entry record.
1272 auto ReadBuffer = [this](
1273 BitstreamCursor &SLocEntryCursor,
1274 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1275 RecordData Record;
1276 StringRef Blob;
1277 unsigned Code = SLocEntryCursor.ReadCode();
1278 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1279
1280 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1281 SmallString<0> Uncompressed;
1282 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1283 llvm::zlib::StatusOK) {
1284 Error("could not decompress embedded file contents");
1285 return nullptr;
1286 }
1287 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1288 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1289 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1290 } else {
1291 Error("AST record has invalid code");
1292 return nullptr;
1293 }
1294 };
1295
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1297 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001298 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 unsigned BaseOffset = F->SLocEntryBaseOffset;
1300
1301 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001302 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1303 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 Error("incorrectly-formatted source location entry in AST file");
1305 return true;
1306 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001307
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001309 StringRef Blob;
1310 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 default:
1312 Error("incorrectly-formatted source location entry in AST file");
1313 return true;
1314
1315 case SM_SLOC_FILE_ENTRY: {
1316 // We will detect whether a file changed and return 'Failure' for it, but
1317 // we will also try to fail gracefully by setting up the SLocEntry.
1318 unsigned InputID = Record[4];
1319 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001320 const FileEntry *File = IF.getFile();
1321 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001322
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001323 // Note that we only check if a File was returned. If it was out-of-date
1324 // we have complained but we will continue creating a FileID to recover
1325 // gracefully.
1326 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 return true;
1328
1329 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1330 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1331 // This is the module's main file.
1332 IncludeLoc = getImportLocation(F);
1333 }
1334 SrcMgr::CharacteristicKind
1335 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1336 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1337 ID, BaseOffset + Record[0]);
1338 SrcMgr::FileInfo &FileInfo =
1339 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1340 FileInfo.NumCreatedFIDs = Record[5];
1341 if (Record[3])
1342 FileInfo.setHasLineDirectives();
1343
1344 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1345 unsigned NumFileDecls = Record[7];
1346 if (NumFileDecls) {
1347 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1348 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1349 NumFileDecls));
1350 }
Richard Smithaada85c2016-02-06 02:06:43 +00001351
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 const SrcMgr::ContentCache *ContentCache
1353 = SourceMgr.getOrCreateContentCache(File,
1354 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1355 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001356 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1357 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001358 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1359 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001361 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 }
1363
1364 break;
1365 }
1366
1367 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001368 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 unsigned Offset = Record[0];
1370 SrcMgr::CharacteristicKind
1371 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1372 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001373 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 IncludeLoc = getImportLocation(F);
1375 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001376
Richard Smithaada85c2016-02-06 02:06:43 +00001377 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1378 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001380 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001381 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 break;
1383 }
1384
1385 case SM_SLOC_EXPANSION_ENTRY: {
1386 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1387 SourceMgr.createExpansionLoc(SpellingLoc,
1388 ReadSourceLocation(*F, Record[2]),
1389 ReadSourceLocation(*F, Record[3]),
1390 Record[4],
1391 ID,
1392 BaseOffset + Record[0]);
1393 break;
1394 }
1395 }
1396
1397 return false;
1398}
1399
1400std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1401 if (ID == 0)
1402 return std::make_pair(SourceLocation(), "");
1403
1404 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1405 Error("source location entry ID out-of-range for AST file");
1406 return std::make_pair(SourceLocation(), "");
1407 }
1408
1409 // Find which module file this entry lands in.
1410 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001411 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 return std::make_pair(SourceLocation(), "");
1413
1414 // FIXME: Can we map this down to a particular submodule? That would be
1415 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001416 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001417}
1418
1419/// \brief Find the location where the module F is imported.
1420SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1421 if (F->ImportLoc.isValid())
1422 return F->ImportLoc;
1423
1424 // Otherwise we have a PCH. It's considered to be "imported" at the first
1425 // location of its includer.
1426 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001427 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001428 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001429 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 return F->ImportedBy[0]->FirstLoc;
1432}
1433
1434/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1435/// specified cursor. Read the abbreviations that are at the top of the block
1436/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001437bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001438 if (Cursor.EnterSubBlock(BlockID))
1439 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001440
1441 while (true) {
1442 uint64_t Offset = Cursor.GetCurrentBitNo();
1443 unsigned Code = Cursor.ReadCode();
1444
1445 // We expect all abbrevs to be at the start of the block.
1446 if (Code != llvm::bitc::DEFINE_ABBREV) {
1447 Cursor.JumpToBit(Offset);
1448 return false;
1449 }
1450 Cursor.ReadAbbrevRecord();
1451 }
1452}
1453
Richard Smithe40f2ba2013-08-07 21:41:30 +00001454Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001455 unsigned &Idx) {
1456 Token Tok;
1457 Tok.startToken();
1458 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1459 Tok.setLength(Record[Idx++]);
1460 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1461 Tok.setIdentifierInfo(II);
1462 Tok.setKind((tok::TokenKind)Record[Idx++]);
1463 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1464 return Tok;
1465}
1466
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001467MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001468 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001469
1470 // Keep track of where we are in the stream, then jump back there
1471 // after reading this macro.
1472 SavedStreamPosition SavedPosition(Stream);
1473
1474 Stream.JumpToBit(Offset);
1475 RecordData Record;
1476 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001477 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001480 // Advance to the next record, but if we get to the end of the block, don't
1481 // pop it (removing all the abbreviations from the cursor) since we want to
1482 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001483 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001484 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1485
1486 switch (Entry.Kind) {
1487 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1488 case llvm::BitstreamEntry::Error:
1489 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001490 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001491 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001492 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 case llvm::BitstreamEntry::Record:
1494 // The interesting case.
1495 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 }
1497
1498 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 Record.clear();
1500 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001501 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001503 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001504 case PP_MACRO_DIRECTIVE_HISTORY:
1505 return Macro;
1506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 case PP_MACRO_OBJECT_LIKE:
1508 case PP_MACRO_FUNCTION_LIKE: {
1509 // If we already have a macro, that means that we've hit the end
1510 // of the definition of the macro we were looking for. We're
1511 // done.
1512 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001515 unsigned NextIndex = 1; // Skip identifier ID.
1516 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001518 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001519 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001521 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1524 // Decode function-like macro info.
1525 bool isC99VarArgs = Record[NextIndex++];
1526 bool isGNUVarArgs = Record[NextIndex++];
1527 bool hasCommaPasting = Record[NextIndex++];
1528 MacroArgs.clear();
1529 unsigned NumArgs = Record[NextIndex++];
1530 for (unsigned i = 0; i != NumArgs; ++i)
1531 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1532
1533 // Install function-like macro info.
1534 MI->setIsFunctionLike();
1535 if (isC99VarArgs) MI->setIsC99Varargs();
1536 if (isGNUVarArgs) MI->setIsGNUVarargs();
1537 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001538 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 }
1540
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 // Remember that we saw this macro last so that we add the tokens that
1542 // form its body to it.
1543 Macro = MI;
1544
1545 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1546 Record[NextIndex]) {
1547 // We have a macro definition. Register the association
1548 PreprocessedEntityID
1549 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1550 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001551 PreprocessingRecord::PPEntityID PPID =
1552 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1553 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1554 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001555 if (PPDef)
1556 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 }
1558
1559 ++NumMacrosRead;
1560 break;
1561 }
1562
1563 case PP_TOKEN: {
1564 // If we see a TOKEN before a PP_MACRO_*, then the file is
1565 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001566 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001567
John McCallf413f5e2013-05-03 00:10:13 +00001568 unsigned Idx = 0;
1569 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 Macro->AddTokenToBody(Tok);
1571 break;
1572 }
1573 }
1574 }
1575}
1576
1577PreprocessedEntityID
1578ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1579 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1580 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1581 assert(I != M.PreprocessedEntityRemap.end()
1582 && "Invalid index into preprocessed entity index remap");
1583
1584 return LocalID + I->second;
1585}
1586
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001587unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1588 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001589}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001592HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001593 internal_key_type ikey = {FE->getSize(),
1594 M.HasTimestamps ? FE->getModificationTime() : 0,
1595 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596 return ikey;
1597}
Guy Benyei11169dd2012-12-18 14:30:41 +00001598
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001599bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001600 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 return false;
1602
Mehdi Amini004b9c72016-10-10 22:52:47 +00001603 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001604 return true;
1605
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001607 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001608 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1609 if (!Key.Imported)
1610 return FileMgr.getFile(Key.Filename);
1611
1612 std::string Resolved = Key.Filename;
1613 Reader.ResolveImportedPath(M, Resolved);
1614 return FileMgr.getFile(Resolved);
1615 };
1616
1617 const FileEntry *FEA = GetFile(a);
1618 const FileEntry *FEB = GetFile(b);
1619 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620}
1621
1622std::pair<unsigned, unsigned>
1623HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001624 using namespace llvm::support;
1625 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001627 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001629
1630HeaderFileInfoTrait::internal_key_type
1631HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001632 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001633 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001634 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1635 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001637 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001638 return ikey;
1639}
1640
Guy Benyei11169dd2012-12-18 14:30:41 +00001641HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001642HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 unsigned DataLen) {
1644 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001645 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 HeaderFileInfo HFI;
1647 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001648 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1649 HFI.isImport |= (Flags >> 4) & 0x01;
1650 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1651 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001653 // FIXME: Find a better way to handle this. Maybe just store a
1654 // "has been included" flag?
1655 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1656 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001657 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1658 M, endian::readNext<uint32_t, little, unaligned>(d));
1659 if (unsigned FrameworkOffset =
1660 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 // The framework offset is 1 greater than the actual offset,
1662 // since 0 is used as an indicator for "no framework name".
1663 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1664 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1665 }
Richard Smith386bb072015-08-18 23:42:23 +00001666
1667 assert((End - d) % 4 == 0 &&
1668 "Wrong data length in HeaderFileInfo deserialization");
1669 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001670 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001671 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1672 LocalSMID >>= 2;
1673
1674 // This header is part of a module. Associate it with the module to enable
1675 // implicit module import.
1676 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1677 Module *Mod = Reader.getSubmodule(GlobalSMID);
1678 FileManager &FileMgr = Reader.getFileManager();
1679 ModuleMap &ModMap =
1680 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1681
1682 std::string Filename = key.Filename;
1683 if (key.Imported)
1684 Reader.ResolveImportedPath(M, Filename);
1685 // FIXME: This is not always the right filename-as-written, but we're not
1686 // going to use this information to rebuild the module, so it doesn't make
1687 // a lot of difference.
1688 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001689 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1690 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001691 }
1692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 // This HeaderFileInfo was externally loaded.
1694 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001695 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 return HFI;
1697}
1698
Richard Smithd7329392015-04-21 21:46:32 +00001699void ASTReader::addPendingMacro(IdentifierInfo *II,
1700 ModuleFile *M,
1701 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001702 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1703 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001704}
1705
1706void ASTReader::ReadDefinedMacros() {
1707 // Note that we are loading defined macros.
1708 Deserializing Macros(this);
1709
Pete Cooper57d3f142015-07-30 17:22:52 +00001710 for (auto &I : llvm::reverse(ModuleMgr)) {
1711 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001712
1713 // If there was no preprocessor block, skip this file.
1714 if (!MacroCursor.getBitStreamReader())
1715 continue;
1716
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001717 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001718 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719
1720 RecordData Record;
1721 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001722 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1723
1724 switch (E.Kind) {
1725 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1726 case llvm::BitstreamEntry::Error:
1727 Error("malformed block record in AST file");
1728 return;
1729 case llvm::BitstreamEntry::EndBlock:
1730 goto NextCursor;
1731
1732 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001733 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001734 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001735 default: // Default behavior: ignore.
1736 break;
1737
1738 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001739 case PP_MACRO_FUNCTION_LIKE: {
1740 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1741 if (II->isOutOfDate())
1742 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001743 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001744 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001745
1746 case PP_TOKEN:
1747 // Ignore tokens.
1748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001749 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001750 break;
1751 }
1752 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001753 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 }
1755}
1756
1757namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001758
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 /// \brief Visitor class used to look up identifirs in an AST file.
1760 class IdentifierLookupVisitor {
1761 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001762 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001764 unsigned &NumIdentifierLookups;
1765 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001767
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001769 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1770 unsigned &NumIdentifierLookups,
1771 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001772 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1773 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001774 NumIdentifierLookups(NumIdentifierLookups),
1775 NumIdentifierLookupHits(NumIdentifierLookupHits),
1776 Found()
1777 {
1778 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001779
1780 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001782 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001784
Guy Benyei11169dd2012-12-18 14:30:41 +00001785 ASTIdentifierLookupTable *IdTable
1786 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1787 if (!IdTable)
1788 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001789
1790 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001791 Found);
1792 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001793 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001794 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 if (Pos == IdTable->end())
1796 return false;
1797
1798 // Dereferencing the iterator has the effect of building the
1799 // IdentifierInfo node and populating it with the various
1800 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001801 ++NumIdentifierLookupHits;
1802 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 return true;
1804 }
1805
1806 // \brief Retrieve the identifier info found within the module
1807 // files.
1808 IdentifierInfo *getIdentifierInfo() const { return Found; }
1809 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001810
1811} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001812
1813void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1814 // Note that we are loading an identifier.
1815 Deserializing AnIdentifier(this);
1816
1817 unsigned PriorGeneration = 0;
1818 if (getContext().getLangOpts().Modules)
1819 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001820
1821 // If there is a global index, look there first to determine which modules
1822 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001823 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001824 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001825 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001826 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1827 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001828 }
1829 }
1830
Douglas Gregor7211ac12013-01-25 23:32:03 +00001831 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001832 NumIdentifierLookups,
1833 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001834 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 markIdentifierUpToDate(&II);
1836}
1837
1838void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1839 if (!II)
1840 return;
1841
1842 II->setOutOfDate(false);
1843
1844 // Update the generation for this identifier.
1845 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001846 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001847}
1848
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1850 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001851 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001852
1853 BitstreamCursor &Cursor = M.MacroCursor;
1854 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001855 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001856
Richard Smith713369b2015-04-23 20:40:50 +00001857 struct ModuleMacroRecord {
1858 SubmoduleID SubModID;
1859 MacroInfo *MI;
1860 SmallVector<SubmoduleID, 8> Overrides;
1861 };
1862 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863
Richard Smithd7329392015-04-21 21:46:32 +00001864 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1865 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1866 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001868 while (true) {
1869 llvm::BitstreamEntry Entry =
1870 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1871 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1872 Error("malformed block record in AST file");
1873 return;
1874 }
1875
1876 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001877 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001878 case PP_MACRO_DIRECTIVE_HISTORY:
1879 break;
1880
1881 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001882 ModuleMacros.push_back(ModuleMacroRecord());
1883 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001884 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1885 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001886 for (int I = 2, N = Record.size(); I != N; ++I)
1887 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001888 continue;
1889 }
1890
1891 default:
1892 Error("malformed block record in AST file");
1893 return;
1894 }
1895
1896 // We found the macro directive history; that's the last record
1897 // for this macro.
1898 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001899 }
1900
Richard Smithd7329392015-04-21 21:46:32 +00001901 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001902 {
1903 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001904 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001905 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001906 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001907 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001908 Module *Mod = getSubmodule(ModID);
1909 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001910 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001911 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001912 }
1913
1914 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001915 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001916 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001917 }
1918 }
1919
1920 // Don't read the directive history for a module; we don't have anywhere
1921 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001922 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001923 return;
1924
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001925 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001926 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001927 unsigned Idx = 0, N = Record.size();
1928 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001929 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001930 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001931 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1932 switch (K) {
1933 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001934 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001935 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001936 break;
1937 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001938 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001939 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001940 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001941 }
1942 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001943 bool isPublic = Record[Idx++];
1944 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1945 break;
1946 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001947
1948 if (!Latest)
1949 Latest = MD;
1950 if (Earliest)
1951 Earliest->setPrevious(MD);
1952 Earliest = MD;
1953 }
1954
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001955 if (Latest)
1956 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001957}
1958
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001959ASTReader::InputFileInfo
1960ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001961 // Go find this input file.
1962 BitstreamCursor &Cursor = F.InputFilesCursor;
1963 SavedStreamPosition SavedPosition(Cursor);
1964 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1965
1966 unsigned Code = Cursor.ReadCode();
1967 RecordData Record;
1968 StringRef Blob;
1969
1970 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1971 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1972 "invalid record type for input file");
1973 (void)Result;
1974
1975 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001976 InputFileInfo R;
1977 R.StoredSize = static_cast<off_t>(Record[1]);
1978 R.StoredTime = static_cast<time_t>(Record[2]);
1979 R.Overridden = static_cast<bool>(Record[3]);
1980 R.Transient = static_cast<bool>(Record[4]);
1981 R.Filename = Blob;
1982 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001983 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001984}
1985
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001986InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001987 // If this ID is bogus, just return an empty input file.
1988 if (ID == 0 || ID > F.InputFilesLoaded.size())
1989 return InputFile();
1990
1991 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001992 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 return F.InputFilesLoaded[ID-1];
1994
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001995 if (F.InputFilesLoaded[ID-1].isNotFound())
1996 return InputFile();
1997
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001999 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002000 SavedStreamPosition SavedPosition(Cursor);
2001 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2002
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002003 InputFileInfo FI = readInputFileInfo(F, ID);
2004 off_t StoredSize = FI.StoredSize;
2005 time_t StoredTime = FI.StoredTime;
2006 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002007 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002008 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002009
Richard Smitha8cfffa2015-11-26 02:04:16 +00002010 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002011
2012 // If we didn't find the file, resolve it relative to the
2013 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002014 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 F.OriginalDir != CurrentDir) {
2016 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2017 F.OriginalDir,
2018 CurrentDir);
2019 if (!Resolved.empty())
2020 File = FileMgr.getFile(Resolved);
2021 }
2022
2023 // For an overridden file, create a virtual file with the stored
2024 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002025 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002026 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002027
Craig Toppera13603a2014-05-22 05:54:18 +00002028 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002029 if (Complain) {
2030 std::string ErrorStr = "could not find file '";
2031 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002032 ErrorStr += "' referenced by AST file '";
2033 ErrorStr += F.FileName;
2034 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002035 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002037 // Record that we didn't find the file.
2038 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2039 return InputFile();
2040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002041
Ben Langmuir198c1682014-03-07 07:27:49 +00002042 // Check if there was a request to override the contents of the file
2043 // that was part of the precompiled header. Overridding such a file
2044 // can lead to problems when lexing using the source locations from the
2045 // PCH.
2046 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002047 // FIXME: Reject if the overrides are different.
2048 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002049 if (Complain)
2050 Error(diag::err_fe_pch_file_overridden, Filename);
2051 // After emitting the diagnostic, recover by disabling the override so
2052 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002053 //
2054 // FIXME: This recovery is just as broken as the original state; there may
2055 // be another precompiled module that's using the overridden contents, or
2056 // we might be half way through parsing it. Instead, we should treat the
2057 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002058 SM.disableFileContentsOverride(File);
2059 // The FileEntry is a virtual file entry with the size of the contents
2060 // that would override the original contents. Set it to the original's
2061 // size/time.
2062 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2063 StoredSize, StoredTime);
2064 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002065
Ben Langmuir198c1682014-03-07 07:27:49 +00002066 bool IsOutOfDate = false;
2067
2068 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002069 if (!Overridden && //
2070 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002071 (StoredTime && StoredTime != File->getModificationTime() &&
2072 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 )) {
2074 if (Complain) {
2075 // Build a list of the PCH imports that got us here (in reverse).
2076 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2077 while (ImportStack.back()->ImportedBy.size() > 0)
2078 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002079
Ben Langmuir198c1682014-03-07 07:27:49 +00002080 // The top-level PCH is stale.
2081 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2082 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002083
Ben Langmuir198c1682014-03-07 07:27:49 +00002084 // Print the import stack.
2085 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2086 Diag(diag::note_pch_required_by)
2087 << Filename << ImportStack[0]->FileName;
2088 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002089 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002090 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002091 }
2092
Ben Langmuir198c1682014-03-07 07:27:49 +00002093 if (!Diags.isDiagnosticInFlight())
2094 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 }
2096
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002099 // FIXME: If the file is overridden and we've already opened it,
2100 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002101
Richard Smitha8cfffa2015-11-26 02:04:16 +00002102 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002103
2104 // Note that we've loaded this input file.
2105 F.InputFilesLoaded[ID-1] = IF;
2106 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002107}
2108
Richard Smith7ed1bc92014-12-05 22:42:13 +00002109/// \brief If we are loading a relocatable PCH or module file, and the filename
2110/// is not an absolute path, add the system or module root to the beginning of
2111/// the file name.
2112void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2113 // Resolve relative to the base directory, if we have one.
2114 if (!M.BaseDirectory.empty())
2115 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002116}
2117
Richard Smith7ed1bc92014-12-05 22:42:13 +00002118void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2120 return;
2121
Richard Smith7ed1bc92014-12-05 22:42:13 +00002122 SmallString<128> Buffer;
2123 llvm::sys::path::append(Buffer, Prefix, Filename);
2124 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002125}
2126
Richard Smith0f99d6a2015-08-09 08:48:41 +00002127static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2128 switch (ARR) {
2129 case ASTReader::Failure: return true;
2130 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2131 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2132 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2133 case ASTReader::ConfigurationMismatch:
2134 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2135 case ASTReader::HadErrors: return true;
2136 case ASTReader::Success: return false;
2137 }
2138
2139 llvm_unreachable("unknown ASTReadResult");
2140}
2141
Richard Smith0516b182015-09-08 19:40:14 +00002142ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2143 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2144 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002145 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002146 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2147 return Failure;
2148
2149 // Read all of the records in the options block.
2150 RecordData Record;
2151 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002152 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002153 llvm::BitstreamEntry Entry = Stream.advance();
2154
2155 switch (Entry.Kind) {
2156 case llvm::BitstreamEntry::Error:
2157 case llvm::BitstreamEntry::SubBlock:
2158 return Failure;
2159
2160 case llvm::BitstreamEntry::EndBlock:
2161 return Result;
2162
2163 case llvm::BitstreamEntry::Record:
2164 // The interesting case.
2165 break;
2166 }
2167
2168 // Read and process a record.
2169 Record.clear();
2170 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2171 case LANGUAGE_OPTIONS: {
2172 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2173 if (ParseLanguageOptions(Record, Complain, Listener,
2174 AllowCompatibleConfigurationMismatch))
2175 Result = ConfigurationMismatch;
2176 break;
2177 }
2178
2179 case TARGET_OPTIONS: {
2180 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2181 if (ParseTargetOptions(Record, Complain, Listener,
2182 AllowCompatibleConfigurationMismatch))
2183 Result = ConfigurationMismatch;
2184 break;
2185 }
2186
2187 case DIAGNOSTIC_OPTIONS: {
2188 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002189 if (ValidateDiagnosticOptions &&
2190 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002191 ParseDiagnosticOptions(Record, Complain, Listener))
2192 return OutOfDate;
2193 break;
2194 }
2195
2196 case FILE_SYSTEM_OPTIONS: {
2197 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2198 if (!AllowCompatibleConfigurationMismatch &&
2199 ParseFileSystemOptions(Record, Complain, Listener))
2200 Result = ConfigurationMismatch;
2201 break;
2202 }
2203
2204 case HEADER_SEARCH_OPTIONS: {
2205 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2206 if (!AllowCompatibleConfigurationMismatch &&
2207 ParseHeaderSearchOptions(Record, Complain, Listener))
2208 Result = ConfigurationMismatch;
2209 break;
2210 }
2211
2212 case PREPROCESSOR_OPTIONS:
2213 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2214 if (!AllowCompatibleConfigurationMismatch &&
2215 ParsePreprocessorOptions(Record, Complain, Listener,
2216 SuggestedPredefines))
2217 Result = ConfigurationMismatch;
2218 break;
2219 }
2220 }
2221}
2222
Guy Benyei11169dd2012-12-18 14:30:41 +00002223ASTReader::ASTReadResult
2224ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002225 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002226 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002228 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002229 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002230
2231 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2232 Error("malformed block record in AST file");
2233 return Failure;
2234 }
2235
2236 // Read all of the records and blocks in the control block.
2237 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002238 unsigned NumInputs = 0;
2239 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002240 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002241 llvm::BitstreamEntry Entry = Stream.advance();
2242
2243 switch (Entry.Kind) {
2244 case llvm::BitstreamEntry::Error:
2245 Error("malformed block record in AST file");
2246 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002247 case llvm::BitstreamEntry::EndBlock: {
2248 // Validate input files.
2249 const HeaderSearchOptions &HSOpts =
2250 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002251
Richard Smitha1825302014-10-23 22:18:29 +00002252 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002253 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2254 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002255 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2256 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002258
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002259 // If we are reading a module, we will create a verification timestamp,
2260 // so we verify all input files. Otherwise, verify only user input
2261 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002262
2263 unsigned N = NumUserInputs;
2264 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002265 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002266 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002267 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002268 N = NumInputs;
2269
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002270 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002271 InputFile IF = getInputFile(F, I+1, Complain);
2272 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002274 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002276
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002277 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002278 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002279
Ben Langmuircb69b572014-03-07 06:40:32 +00002280 if (Listener && Listener->needsInputFileVisitation()) {
2281 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2282 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002283 for (unsigned I = 0; I < N; ++I) {
2284 bool IsSystem = I >= NumUserInputs;
2285 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002286 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002287 F.Kind == MK_ExplicitModule ||
2288 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002289 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002290 }
2291
Richard Smith8a308ec2015-11-05 00:54:55 +00002292 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002293 }
2294
Chris Lattnere7b154b2013-01-19 21:39:22 +00002295 case llvm::BitstreamEntry::SubBlock:
2296 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 case INPUT_FILES_BLOCK_ID:
2298 F.InputFilesCursor = Stream;
2299 if (Stream.SkipBlock() || // Skip with the main cursor
2300 // Read the abbreviations
2301 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2302 Error("malformed block record in AST file");
2303 return Failure;
2304 }
2305 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002306
2307 case OPTIONS_BLOCK_ID:
2308 // If we're reading the first module for this group, check its options
2309 // are compatible with ours. For modules it imports, no further checking
2310 // is required, because we checked them when we built it.
2311 if (Listener && !ImportedBy) {
2312 // Should we allow the configuration of the module file to differ from
2313 // the configuration of the current translation unit in a compatible
2314 // way?
2315 //
2316 // FIXME: Allow this for files explicitly specified with -include-pch.
2317 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002318 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002319 const HeaderSearchOptions &HSOpts =
2320 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002321
Richard Smith8a308ec2015-11-05 00:54:55 +00002322 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2323 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002324 *Listener, SuggestedPredefines,
2325 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002326 if (Result == Failure) {
2327 Error("malformed block record in AST file");
2328 return Result;
2329 }
2330
Richard Smith8a308ec2015-11-05 00:54:55 +00002331 if (DisableValidation ||
2332 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2333 Result = Success;
2334
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002335 // If we can't load the module, exit early since we likely
2336 // will rebuild the module anyway. The stream may be in the
2337 // middle of a block.
2338 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002339 return Result;
2340 } else if (Stream.SkipBlock()) {
2341 Error("malformed block record in AST file");
2342 return Failure;
2343 }
2344 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002345
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002347 if (Stream.SkipBlock()) {
2348 Error("malformed block record in AST file");
2349 return Failure;
2350 }
2351 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353
2354 case llvm::BitstreamEntry::Record:
2355 // The interesting case.
2356 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 }
2358
2359 // Read and process a record.
2360 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002361 StringRef Blob;
2362 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case METADATA: {
2364 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2365 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002366 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2367 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 return VersionMismatch;
2369 }
2370
Richard Smithe75ee0f2015-08-17 07:13:32 +00002371 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2373 Diag(diag::err_pch_with_compiler_errors);
2374 return HadErrors;
2375 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002376 if (hasErrors) {
2377 Diags.ErrorOccurred = true;
2378 Diags.UncompilableErrorOccurred = true;
2379 Diags.UnrecoverableErrorOccurred = true;
2380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002381
2382 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002383 // Relative paths in a relocatable PCH are relative to our sysroot.
2384 if (F.RelocatablePCH)
2385 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002386
Richard Smithe75ee0f2015-08-17 07:13:32 +00002387 F.HasTimestamps = Record[5];
2388
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002390 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2392 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002393 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 return VersionMismatch;
2395 }
2396 break;
2397 }
2398
Ben Langmuir487ea142014-10-23 18:05:36 +00002399 case SIGNATURE:
2400 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2401 F.Signature = Record[0];
2402 break;
2403
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 case IMPORTS: {
2405 // Load each of the imported PCH files.
2406 unsigned Idx = 0, N = Record.size();
2407 while (Idx < N) {
2408 // Read information about the AST file.
2409 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2410 // The import location will be the local one for now; we will adjust
2411 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002412 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002414 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002415 off_t StoredSize = (off_t)Record[Idx++];
2416 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002417 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002418 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002419
Richard Smith0f99d6a2015-08-09 08:48:41 +00002420 // If our client can't cope with us being out of date, we can't cope with
2421 // our dependency being missing.
2422 unsigned Capabilities = ClientLoadCapabilities;
2423 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2424 Capabilities &= ~ARR_Missing;
2425
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002427 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2428 Loaded, StoredSize, StoredModTime,
2429 StoredSignature, Capabilities);
2430
2431 // If we diagnosed a problem, produce a backtrace.
2432 if (isDiagnosedResult(Result, Capabilities))
2433 Diag(diag::note_module_file_imported_by)
2434 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2435
2436 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 case Failure: return Failure;
2438 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002439 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 case OutOfDate: return OutOfDate;
2441 case VersionMismatch: return VersionMismatch;
2442 case ConfigurationMismatch: return ConfigurationMismatch;
2443 case HadErrors: return HadErrors;
2444 case Success: break;
2445 }
2446 }
2447 break;
2448 }
2449
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 case ORIGINAL_FILE:
2451 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002452 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002454 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 break;
2456
2457 case ORIGINAL_FILE_ID:
2458 F.OriginalSourceFileID = FileID::get(Record[0]);
2459 break;
2460
2461 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002462 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 break;
2464
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002465 case MODULE_NAME:
2466 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002467 if (Listener)
2468 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002469 break;
2470
Richard Smith223d3f22014-12-06 03:21:08 +00002471 case MODULE_DIRECTORY: {
2472 assert(!F.ModuleName.empty() &&
2473 "MODULE_DIRECTORY found before MODULE_NAME");
2474 // If we've already loaded a module map file covering this module, we may
2475 // have a better path for it (relative to the current build).
2476 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2477 if (M && M->Directory) {
2478 // If we're implicitly loading a module, the base directory can't
2479 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002480 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002481 const DirectoryEntry *BuildDir =
2482 PP.getFileManager().getDirectory(Blob);
2483 if (!BuildDir || BuildDir != M->Directory) {
2484 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2485 Diag(diag::err_imported_module_relocated)
2486 << F.ModuleName << Blob << M->Directory->getName();
2487 return OutOfDate;
2488 }
2489 }
2490 F.BaseDirectory = M->Directory->getName();
2491 } else {
2492 F.BaseDirectory = Blob;
2493 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002494 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002495 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002496
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002497 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002498 if (ASTReadResult Result =
2499 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2500 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002501 break;
2502
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002503 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002504 NumInputs = Record[0];
2505 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002506 F.InputFileOffsets =
2507 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002508 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 break;
2510 }
2511 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002512}
2513
Ben Langmuir2c9af442014-04-10 17:57:43 +00002514ASTReader::ASTReadResult
2515ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002516 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517
2518 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2519 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002520 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 }
2522
2523 // Read all of the records and blocks for the AST file.
2524 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002525 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002526 llvm::BitstreamEntry Entry = Stream.advance();
2527
2528 switch (Entry.Kind) {
2529 case llvm::BitstreamEntry::Error:
2530 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002532 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002533 // Outside of C++, we do not store a lookup map for the translation unit.
2534 // Instead, mark it as needing a lookup map to be built if this module
2535 // contains any declarations lexically within it (which it always does!).
2536 // This usually has no cost, since we very rarely need the lookup map for
2537 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002539 if (DC->hasExternalLexicalStorage() &&
2540 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002542
Ben Langmuir2c9af442014-04-10 17:57:43 +00002543 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545 case llvm::BitstreamEntry::SubBlock:
2546 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 case DECLTYPES_BLOCK_ID:
2548 // We lazily load the decls block, but we want to set up the
2549 // DeclsCursor cursor to point into it. Clone our current bitcode
2550 // cursor to it, enter the block and read the abbrevs in that block.
2551 // With the main cursor, we just skip over it.
2552 F.DeclsCursor = Stream;
2553 if (Stream.SkipBlock() || // Skip with the main cursor.
2554 // Read the abbrevs.
2555 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2556 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002557 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 }
2559 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002560
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 case PREPROCESSOR_BLOCK_ID:
2562 F.MacroCursor = Stream;
2563 if (!PP.getExternalSource())
2564 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002565
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 if (Stream.SkipBlock() ||
2567 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2568 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002569 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 }
2571 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2572 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002573
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case PREPROCESSOR_DETAIL_BLOCK_ID:
2575 F.PreprocessorDetailCursor = Stream;
2576 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002577 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002579 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002580 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002583 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2584
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 if (!PP.getPreprocessingRecord())
2586 PP.createPreprocessingRecord();
2587 if (!PP.getPreprocessingRecord()->getExternalSource())
2588 PP.getPreprocessingRecord()->SetExternalSource(*this);
2589 break;
2590
2591 case SOURCE_MANAGER_BLOCK_ID:
2592 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002593 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2598 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002602 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 if (Stream.SkipBlock() ||
2604 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2605 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002606 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 }
2608 CommentsCursors.push_back(std::make_pair(C, &F));
2609 break;
2610 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002613 if (Stream.SkipBlock()) {
2614 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002616 }
2617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 }
2619 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620
2621 case llvm::BitstreamEntry::Record:
2622 // The interesting case.
2623 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 }
2625
2626 // Read and process a record.
2627 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002628 StringRef Blob;
2629 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 default: // Default behavior: ignore.
2631 break;
2632
2633 case TYPE_OFFSET: {
2634 if (F.LocalNumTypes != 0) {
2635 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002638 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 F.LocalNumTypes = Record[0];
2640 unsigned LocalBaseTypeIndex = Record[1];
2641 F.BaseTypeIndex = getTotalNumTypes();
2642
2643 if (F.LocalNumTypes > 0) {
2644 // Introduce the global -> local mapping for types within this module.
2645 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2646
2647 // Introduce the local -> global mapping for types within this module.
2648 F.TypeRemap.insertOrReplace(
2649 std::make_pair(LocalBaseTypeIndex,
2650 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002651
2652 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
2655 }
2656
2657 case DECL_OFFSET: {
2658 if (F.LocalNumDecls != 0) {
2659 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002660 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002662 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 F.LocalNumDecls = Record[0];
2664 unsigned LocalBaseDeclID = Record[1];
2665 F.BaseDeclID = getTotalNumDecls();
2666
2667 if (F.LocalNumDecls > 0) {
2668 // Introduce the global -> local mapping for declarations within this
2669 // module.
2670 GlobalDeclMap.insert(
2671 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2672
2673 // Introduce the local -> global mapping for declarations within this
2674 // module.
2675 F.DeclRemap.insertOrReplace(
2676 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2677
2678 // Introduce the global -> local mapping for declarations within this
2679 // module.
2680 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002681
Ben Langmuir52ca6782014-10-20 16:27:32 +00002682 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2683 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 break;
2685 }
2686
2687 case TU_UPDATE_LEXICAL: {
2688 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002689 LexicalContents Contents(
2690 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2691 Blob.data()),
2692 static_cast<unsigned int>(Blob.size() / 4));
2693 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 TU->setHasExternalLexicalStorage(true);
2695 break;
2696 }
2697
2698 case UPDATE_VISIBLE: {
2699 unsigned Idx = 0;
2700 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002701 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002702 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002703 // If we've already loaded the decl, perform the updates when we finish
2704 // loading this block.
2705 if (Decl *D = GetExistingDecl(ID))
2706 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 break;
2708 }
2709
2710 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002711 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002713 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2714 (const unsigned char *)F.IdentifierTableData + Record[0],
2715 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2716 (const unsigned char *)F.IdentifierTableData,
2717 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002718
2719 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2720 }
2721 break;
2722
2723 case IDENTIFIER_OFFSET: {
2724 if (F.LocalNumIdentifiers != 0) {
2725 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002726 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002728 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 F.LocalNumIdentifiers = Record[0];
2730 unsigned LocalBaseIdentifierID = Record[1];
2731 F.BaseIdentifierID = getTotalNumIdentifiers();
2732
2733 if (F.LocalNumIdentifiers > 0) {
2734 // Introduce the global -> local mapping for identifiers within this
2735 // module.
2736 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2737 &F));
2738
2739 // Introduce the local -> global mapping for identifiers within this
2740 // module.
2741 F.IdentifierRemap.insertOrReplace(
2742 std::make_pair(LocalBaseIdentifierID,
2743 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002744
Ben Langmuir52ca6782014-10-20 16:27:32 +00002745 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2746 + F.LocalNumIdentifiers);
2747 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 break;
2749 }
2750
Richard Smith33e0f7e2015-07-22 02:08:40 +00002751 case INTERESTING_IDENTIFIERS:
2752 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2753 break;
2754
Ben Langmuir332aafe2014-01-31 01:06:56 +00002755 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002756 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2757 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002759 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 break;
2761
2762 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002763 if (SpecialTypes.empty()) {
2764 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2765 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2766 break;
2767 }
2768
2769 if (SpecialTypes.size() != Record.size()) {
2770 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002771 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002772 }
2773
2774 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2775 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2776 if (!SpecialTypes[I])
2777 SpecialTypes[I] = ID;
2778 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2779 // merge step?
2780 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 break;
2782
2783 case STATISTICS:
2784 TotalNumStatements += Record[0];
2785 TotalNumMacros += Record[1];
2786 TotalLexicalDeclContexts += Record[2];
2787 TotalVisibleDeclContexts += Record[3];
2788 break;
2789
2790 case UNUSED_FILESCOPED_DECLS:
2791 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2792 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2793 break;
2794
2795 case DELEGATING_CTORS:
2796 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2797 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2798 break;
2799
2800 case WEAK_UNDECLARED_IDENTIFIERS:
2801 if (Record.size() % 4 != 0) {
2802 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002803 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 }
2805
2806 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2807 // files. This isn't the way to do it :)
2808 WeakUndeclaredIdentifiers.clear();
2809
2810 // Translate the weak, undeclared identifiers into global IDs.
2811 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2812 WeakUndeclaredIdentifiers.push_back(
2813 getGlobalIdentifierID(F, Record[I++]));
2814 WeakUndeclaredIdentifiers.push_back(
2815 getGlobalIdentifierID(F, Record[I++]));
2816 WeakUndeclaredIdentifiers.push_back(
2817 ReadSourceLocation(F, Record, I).getRawEncoding());
2818 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2819 }
2820 break;
2821
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002823 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 F.LocalNumSelectors = Record[0];
2825 unsigned LocalBaseSelectorID = Record[1];
2826 F.BaseSelectorID = getTotalNumSelectors();
2827
2828 if (F.LocalNumSelectors > 0) {
2829 // Introduce the global -> local mapping for selectors within this
2830 // module.
2831 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2832
2833 // Introduce the local -> global mapping for selectors within this
2834 // module.
2835 F.SelectorRemap.insertOrReplace(
2836 std::make_pair(LocalBaseSelectorID,
2837 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002838
2839 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 }
2841 break;
2842 }
2843
2844 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002845 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 if (Record[0])
2847 F.SelectorLookupTable
2848 = ASTSelectorLookupTable::Create(
2849 F.SelectorLookupTableData + Record[0],
2850 F.SelectorLookupTableData,
2851 ASTSelectorLookupTrait(*this, F));
2852 TotalNumMethodPoolEntries += Record[1];
2853 break;
2854
2855 case REFERENCED_SELECTOR_POOL:
2856 if (!Record.empty()) {
2857 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2858 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2859 Record[Idx++]));
2860 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2861 getRawEncoding());
2862 }
2863 }
2864 break;
2865
2866 case PP_COUNTER_VALUE:
2867 if (!Record.empty() && Listener)
2868 Listener->ReadCounter(F, Record[0]);
2869 break;
2870
2871 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002872 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 F.NumFileSortedDecls = Record[0];
2874 break;
2875
2876 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002877 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 F.LocalNumSLocEntries = Record[0];
2879 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002880 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002881 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002883 if (!F.SLocEntryBaseID) {
2884 Error("ran out of source locations");
2885 break;
2886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 // Make our entry in the range map. BaseID is negative and growing, so
2888 // we invert it. Because we invert it, though, we need the other end of
2889 // the range.
2890 unsigned RangeStart =
2891 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2892 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2893 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2894
2895 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2896 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2897 GlobalSLocOffsetMap.insert(
2898 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2899 - SLocSpaceSize,&F));
2900
2901 // Initialize the remapping table.
2902 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002903 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002905 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2907
2908 TotalNumSLocEntries += F.LocalNumSLocEntries;
2909 break;
2910 }
2911
2912 case MODULE_OFFSET_MAP: {
2913 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002914 const unsigned char *Data = (const unsigned char*)Blob.data();
2915 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002916
2917 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2918 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2919 F.SLocRemap.insert(std::make_pair(0U, 0));
2920 F.SLocRemap.insert(std::make_pair(2U, 1));
2921 }
2922
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002924 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2925 RemapBuilder;
2926 RemapBuilder SLocRemap(F.SLocRemap);
2927 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2928 RemapBuilder MacroRemap(F.MacroRemap);
2929 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2930 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2931 RemapBuilder SelectorRemap(F.SelectorRemap);
2932 RemapBuilder DeclRemap(F.DeclRemap);
2933 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002934
Richard Smithd8879c82015-08-24 21:59:32 +00002935 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002936 using namespace llvm::support;
2937 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 StringRef Name = StringRef((const char*)Data, Len);
2939 Data += Len;
2940 ModuleFile *OM = ModuleMgr.lookup(Name);
2941 if (!OM) {
2942 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
2945
Justin Bogner57ba0b22014-03-28 22:03:24 +00002946 uint32_t SLocOffset =
2947 endian::readNext<uint32_t, little, unaligned>(Data);
2948 uint32_t IdentifierIDOffset =
2949 endian::readNext<uint32_t, little, unaligned>(Data);
2950 uint32_t MacroIDOffset =
2951 endian::readNext<uint32_t, little, unaligned>(Data);
2952 uint32_t PreprocessedEntityIDOffset =
2953 endian::readNext<uint32_t, little, unaligned>(Data);
2954 uint32_t SubmoduleIDOffset =
2955 endian::readNext<uint32_t, little, unaligned>(Data);
2956 uint32_t SelectorIDOffset =
2957 endian::readNext<uint32_t, little, unaligned>(Data);
2958 uint32_t DeclIDOffset =
2959 endian::readNext<uint32_t, little, unaligned>(Data);
2960 uint32_t TypeIndexOffset =
2961 endian::readNext<uint32_t, little, unaligned>(Data);
2962
Ben Langmuir785180e2014-10-20 16:27:30 +00002963 uint32_t None = std::numeric_limits<uint32_t>::max();
2964
2965 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2966 RemapBuilder &Remap) {
2967 if (Offset != None)
2968 Remap.insert(std::make_pair(Offset,
2969 static_cast<int>(BaseOffset - Offset)));
2970 };
2971 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2972 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2973 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2974 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2975 PreprocessedEntityRemap);
2976 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2977 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2978 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2979 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002980
2981 // Global -> local mappings.
2982 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2983 }
2984 break;
2985 }
2986
2987 case SOURCE_MANAGER_LINE_TABLE:
2988 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002989 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 break;
2991
2992 case SOURCE_LOCATION_PRELOADS: {
2993 // Need to transform from the local view (1-based IDs) to the global view,
2994 // which is based off F.SLocEntryBaseID.
2995 if (!F.PreloadSLocEntries.empty()) {
2996 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002997 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 }
2999
3000 F.PreloadSLocEntries.swap(Record);
3001 break;
3002 }
3003
3004 case EXT_VECTOR_DECLS:
3005 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3006 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3007 break;
3008
3009 case VTABLE_USES:
3010 if (Record.size() % 3 != 0) {
3011 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003012 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 }
3014
3015 // Later tables overwrite earlier ones.
3016 // FIXME: Modules will have some trouble with this. This is clearly not
3017 // the right way to do this.
3018 VTableUses.clear();
3019
3020 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3021 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3022 VTableUses.push_back(
3023 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3024 VTableUses.push_back(Record[Idx++]);
3025 }
3026 break;
3027
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 case PENDING_IMPLICIT_INSTANTIATIONS:
3029 if (PendingInstantiations.size() % 2 != 0) {
3030 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003031 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 }
3033
3034 if (Record.size() % 2 != 0) {
3035 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003036 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 }
3038
3039 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3040 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3041 PendingInstantiations.push_back(
3042 ReadSourceLocation(F, Record, I).getRawEncoding());
3043 }
3044 break;
3045
3046 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003047 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003048 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3052 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3053 break;
3054
3055 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003056 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3057 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3058 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003059
3060 unsigned LocalBasePreprocessedEntityID = Record[0];
3061
3062 unsigned StartingID;
3063 if (!PP.getPreprocessingRecord())
3064 PP.createPreprocessingRecord();
3065 if (!PP.getPreprocessingRecord()->getExternalSource())
3066 PP.getPreprocessingRecord()->SetExternalSource(*this);
3067 StartingID
3068 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003069 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 F.BasePreprocessedEntityID = StartingID;
3071
3072 if (F.NumPreprocessedEntities > 0) {
3073 // Introduce the global -> local mapping for preprocessed entities in
3074 // this module.
3075 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3076
3077 // Introduce the local -> global mapping for preprocessed entities in
3078 // this module.
3079 F.PreprocessedEntityRemap.insertOrReplace(
3080 std::make_pair(LocalBasePreprocessedEntityID,
3081 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3082 }
3083
3084 break;
3085 }
3086
3087 case DECL_UPDATE_OFFSETS: {
3088 if (Record.size() % 2 != 0) {
3089 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003090 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003092 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3093 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3094 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3095
3096 // If we've already loaded the decl, perform the updates when we finish
3097 // loading this block.
3098 if (Decl *D = GetExistingDecl(ID))
3099 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3100 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 break;
3102 }
3103
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 case OBJC_CATEGORIES_MAP: {
3105 if (F.LocalNumObjCCategoriesInMap != 0) {
3106 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003107 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 }
3109
3110 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003111 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 break;
3113 }
3114
3115 case OBJC_CATEGORIES:
3116 F.ObjCCategories.swap(Record);
3117 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 case DIAG_PRAGMA_MAPPINGS:
3120 if (F.PragmaDiagMappings.empty())
3121 F.PragmaDiagMappings.swap(Record);
3122 else
3123 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3124 Record.begin(), Record.end());
3125 break;
3126
3127 case CUDA_SPECIAL_DECL_REFS:
3128 // Later tables overwrite earlier ones.
3129 // FIXME: Modules will have trouble with this.
3130 CUDASpecialDeclRefs.clear();
3131 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3132 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3133 break;
3134
3135 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003136 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 if (Record[0]) {
3139 F.HeaderFileInfoTable
3140 = HeaderFileInfoLookupTable::Create(
3141 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3142 (const unsigned char *)F.HeaderFileInfoTableData,
3143 HeaderFileInfoTrait(*this, F,
3144 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003145 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003146
3147 PP.getHeaderSearchInfo().SetExternalSource(this);
3148 if (!PP.getHeaderSearchInfo().getExternalLookup())
3149 PP.getHeaderSearchInfo().SetExternalLookup(this);
3150 }
3151 break;
3152 }
3153
3154 case FP_PRAGMA_OPTIONS:
3155 // Later tables overwrite earlier ones.
3156 FPPragmaOptions.swap(Record);
3157 break;
3158
3159 case OPENCL_EXTENSIONS:
3160 // Later tables overwrite earlier ones.
3161 OpenCLExtensions.swap(Record);
3162 break;
3163
3164 case TENTATIVE_DEFINITIONS:
3165 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3166 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3167 break;
3168
3169 case KNOWN_NAMESPACES:
3170 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3171 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3172 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003173
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003174 case UNDEFINED_BUT_USED:
3175 if (UndefinedButUsed.size() % 2 != 0) {
3176 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003177 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003178 }
3179
3180 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003181 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003182 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003183 }
3184 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003185 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3186 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003187 ReadSourceLocation(F, Record, I).getRawEncoding());
3188 }
3189 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003190 case DELETE_EXPRS_TO_ANALYZE:
3191 for (unsigned I = 0, N = Record.size(); I != N;) {
3192 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3193 const uint64_t Count = Record[I++];
3194 DelayedDeleteExprs.push_back(Count);
3195 for (uint64_t C = 0; C < Count; ++C) {
3196 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3197 bool IsArrayForm = Record[I++] == 1;
3198 DelayedDeleteExprs.push_back(IsArrayForm);
3199 }
3200 }
3201 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003202
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003204 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 // If we aren't loading a module (which has its own exports), make
3206 // all of the imported modules visible.
3207 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003208 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3209 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3210 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3211 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003212 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 }
3214 }
3215 break;
3216 }
3217
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 case MACRO_OFFSET: {
3219 if (F.LocalNumMacros != 0) {
3220 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003221 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003223 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 F.LocalNumMacros = Record[0];
3225 unsigned LocalBaseMacroID = Record[1];
3226 F.BaseMacroID = getTotalNumMacros();
3227
3228 if (F.LocalNumMacros > 0) {
3229 // Introduce the global -> local mapping for macros within this module.
3230 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3231
3232 // Introduce the local -> global mapping for macros within this module.
3233 F.MacroRemap.insertOrReplace(
3234 std::make_pair(LocalBaseMacroID,
3235 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003236
3237 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
3239 break;
3240 }
3241
Richard Smithe40f2ba2013-08-07 21:41:30 +00003242 case LATE_PARSED_TEMPLATE: {
3243 LateParsedTemplates.append(Record.begin(), Record.end());
3244 break;
3245 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003246
3247 case OPTIMIZE_PRAGMA_OPTIONS:
3248 if (Record.size() != 1) {
3249 Error("invalid pragma optimize record");
3250 return Failure;
3251 }
3252 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3253 break;
Nico Weber72889432014-09-06 01:25:55 +00003254
Nico Weber779355f2016-03-02 23:22:00 +00003255 case MSSTRUCT_PRAGMA_OPTIONS:
3256 if (Record.size() != 1) {
3257 Error("invalid pragma ms_struct record");
3258 return Failure;
3259 }
3260 PragmaMSStructState = Record[0];
3261 break;
3262
Nico Weber42932312016-03-03 00:17:35 +00003263 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3264 if (Record.size() != 2) {
3265 Error("invalid pragma ms_struct record");
3266 return Failure;
3267 }
3268 PragmaMSPointersToMembersState = Record[0];
3269 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3270 break;
3271
Nico Weber72889432014-09-06 01:25:55 +00003272 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3273 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3274 UnusedLocalTypedefNameCandidates.push_back(
3275 getGlobalDeclID(F, Record[I]));
3276 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003277
3278 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3279 if (Record.size() != 1) {
3280 Error("invalid cuda pragma options record");
3281 return Failure;
3282 }
3283 ForceCUDAHostDeviceDepth = Record[0];
3284 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 }
3286 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003287}
3288
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003289ASTReader::ASTReadResult
3290ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3291 const ModuleFile *ImportedBy,
3292 unsigned ClientLoadCapabilities) {
3293 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003294 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003295
Manman Ren11f2a472016-08-18 17:42:15 +00003296 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003297 // For an explicitly-loaded module, we don't care whether the original
3298 // module map file exists or matches.
3299 return Success;
3300 }
3301
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003302 // Try to resolve ModuleName in the current header search context and
3303 // verify that it is found in the same module map file as we saved. If the
3304 // top-level AST file is a main file, skip this check because there is no
3305 // usable header search context.
3306 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003307 "MODULE_NAME should come before MODULE_MAP_FILE");
3308 if (F.Kind == MK_ImplicitModule &&
3309 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3310 // An implicitly-loaded module file should have its module listed in some
3311 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003312 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003313 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3314 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3315 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003316 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003317 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3318 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3319 // This module was defined by an imported (explicit) module.
3320 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3321 << ASTFE->getName();
3322 else
3323 // This module was built with a different module map.
3324 Diag(diag::err_imported_module_not_found)
3325 << F.ModuleName << F.FileName << ImportedBy->FileName
3326 << F.ModuleMapPath;
3327 }
3328 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003329 }
3330
Richard Smithe842a472014-10-22 02:05:46 +00003331 assert(M->Name == F.ModuleName && "found module with different name");
3332
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003333 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003334 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003335 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3336 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003337 assert(ImportedBy && "top-level import should be verified");
3338 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3339 Diag(diag::err_imported_module_modmap_changed)
3340 << F.ModuleName << ImportedBy->FileName
3341 << ModMap->getName() << F.ModuleMapPath;
3342 return OutOfDate;
3343 }
3344
3345 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3346 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3347 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003348 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003349 const FileEntry *F =
3350 FileMgr.getFile(Filename, false, false);
3351 if (F == nullptr) {
3352 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3353 Error("could not find file '" + Filename +"' referenced by AST file");
3354 return OutOfDate;
3355 }
3356 AdditionalStoredMaps.insert(F);
3357 }
3358
3359 // Check any additional module map files (e.g. module.private.modulemap)
3360 // that are not in the pcm.
3361 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3362 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3363 // Remove files that match
3364 // Note: SmallPtrSet::erase is really remove
3365 if (!AdditionalStoredMaps.erase(ModMap)) {
3366 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3367 Diag(diag::err_module_different_modmap)
3368 << F.ModuleName << /*new*/0 << ModMap->getName();
3369 return OutOfDate;
3370 }
3371 }
3372 }
3373
3374 // Check any additional module map files that are in the pcm, but not
3375 // found in header search. Cases that match are already removed.
3376 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3377 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3378 Diag(diag::err_module_different_modmap)
3379 << F.ModuleName << /*not new*/1 << ModMap->getName();
3380 return OutOfDate;
3381 }
3382 }
3383
3384 if (Listener)
3385 Listener->ReadModuleMapFile(F.ModuleMapPath);
3386 return Success;
3387}
3388
3389
Douglas Gregorc1489562013-02-12 23:36:21 +00003390/// \brief Move the given method to the back of the global list of methods.
3391static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3392 // Find the entry for this selector in the method pool.
3393 Sema::GlobalMethodPool::iterator Known
3394 = S.MethodPool.find(Method->getSelector());
3395 if (Known == S.MethodPool.end())
3396 return;
3397
3398 // Retrieve the appropriate method list.
3399 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3400 : Known->second.second;
3401 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003402 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003403 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003404 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003405 Found = true;
3406 } else {
3407 // Keep searching.
3408 continue;
3409 }
3410 }
3411
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003412 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003413 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003414 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003415 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003416 }
3417}
3418
Richard Smithde711422015-04-23 21:20:19 +00003419void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003420 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003421 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003422 bool wasHidden = D->Hidden;
3423 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Richard Smith49f906a2014-03-01 00:08:04 +00003425 if (wasHidden && SemaObj) {
3426 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3427 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 }
3430 }
3431}
3432
Richard Smith49f906a2014-03-01 00:08:04 +00003433void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003434 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003435 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003437 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003438 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003440 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003441
3442 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003443 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 // there is nothing more to do.
3445 continue;
3446 }
Richard Smith49f906a2014-03-01 00:08:04 +00003447
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 if (!Mod->isAvailable()) {
3449 // Modules that aren't available cannot be made visible.
3450 continue;
3451 }
3452
3453 // Update the module's name visibility.
3454 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003455
Guy Benyei11169dd2012-12-18 14:30:41 +00003456 // If we've already deserialized any names from this module,
3457 // mark them as visible.
3458 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3459 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003460 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003462 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003463 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3464 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003466
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003468 SmallVector<Module *, 16> Exports;
3469 Mod->getExportedModules(Exports);
3470 for (SmallVectorImpl<Module *>::iterator
3471 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3472 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003473 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003474 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 }
3476 }
3477}
3478
Richard Smith6561f922016-09-12 21:06:40 +00003479/// We've merged the definition \p MergedDef into the existing definition
3480/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3481/// visible.
3482void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3483 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003484 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3485 // in modules other than its owning module. We should instead give the
3486 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003487 if (Def->isHidden()) {
3488 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003489 if (!MergedDef->isHidden())
3490 Def->Hidden = false;
3491 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3492 getContext().mergeDefinitionIntoModule(
3493 Def, MergedDef->getImportedOwningModule(),
3494 /*NotifyListeners*/ false);
3495 PendingMergedDefinitionsToDeduplicate.insert(Def);
3496 } else {
3497 auto SubmoduleID = MergedDef->getOwningModuleID();
3498 assert(SubmoduleID && "hidden definition in no module");
3499 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3500 }
Richard Smith6561f922016-09-12 21:06:40 +00003501 }
3502}
3503
Douglas Gregore060e572013-01-25 01:03:03 +00003504bool ASTReader::loadGlobalIndex() {
3505 if (GlobalIndex)
3506 return false;
3507
3508 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3509 !Context.getLangOpts().Modules)
3510 return true;
3511
3512 // Try to load the global index.
3513 TriedLoadingGlobalIndex = true;
3514 StringRef ModuleCachePath
3515 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3516 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003517 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003518 if (!Result.first)
3519 return true;
3520
3521 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003522 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003523 return false;
3524}
3525
3526bool ASTReader::isGlobalIndexUnavailable() const {
3527 return Context.getLangOpts().Modules && UseGlobalIndex &&
3528 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3529}
3530
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003531static void updateModuleTimestamp(ModuleFile &MF) {
3532 // Overwrite the timestamp file contents so that file's mtime changes.
3533 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003534 std::error_code EC;
3535 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3536 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003537 return;
3538 OS << "Timestamp file\n";
3539}
3540
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003541/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3542/// cursor into the start of the given block ID, returning false on success and
3543/// true on failure.
3544static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003545 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003546 llvm::BitstreamEntry Entry = Cursor.advance();
3547 switch (Entry.Kind) {
3548 case llvm::BitstreamEntry::Error:
3549 case llvm::BitstreamEntry::EndBlock:
3550 return true;
3551
3552 case llvm::BitstreamEntry::Record:
3553 // Ignore top-level records.
3554 Cursor.skipRecord(Entry.ID);
3555 break;
3556
3557 case llvm::BitstreamEntry::SubBlock:
3558 if (Entry.ID == BlockID) {
3559 if (Cursor.EnterSubBlock(BlockID))
3560 return true;
3561 // Found it!
3562 return false;
3563 }
3564
3565 if (Cursor.SkipBlock())
3566 return true;
3567 }
3568 }
3569}
3570
Benjamin Kramer0772c422016-02-13 13:42:54 +00003571ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 ModuleKind Type,
3573 SourceLocation ImportLoc,
3574 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003575 llvm::SaveAndRestore<SourceLocation>
3576 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3577
Richard Smithd1c46742014-04-30 02:24:17 +00003578 // Defer any pending actions until we get to the end of reading the AST file.
3579 Deserializing AnASTFile(this);
3580
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003582 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003583
3584 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003585 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003587 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003588 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 ClientLoadCapabilities)) {
3590 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003591 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 case OutOfDate:
3593 case VersionMismatch:
3594 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003595 case HadErrors: {
3596 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3597 for (const ImportedModule &IM : Loaded)
3598 LoadedSet.insert(IM.Mod);
3599
Douglas Gregor7029ce12013-03-19 00:28:20 +00003600 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003601 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003602 Context.getLangOpts().Modules
3603 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003604 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003605
3606 // If we find that any modules are unusable, the global index is going
3607 // to be out-of-date. Just remove it.
3608 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003609 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003611 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 case Success:
3613 break;
3614 }
3615
3616 // Here comes stuff that we only do once the entire chain is loaded.
3617
3618 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003619 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3620 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 M != MEnd; ++M) {
3622 ModuleFile &F = *M->Mod;
3623
3624 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003625 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3626 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003627
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003628 // Read the extension blocks.
3629 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3630 if (ASTReadResult Result = ReadExtensionBlock(F))
3631 return Result;
3632 }
3633
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 // Once read, set the ModuleFile bit base offset and update the size in
3635 // bits of all files we've seen.
3636 F.GlobalBitOffset = TotalModulesSizeInBits;
3637 TotalModulesSizeInBits += F.SizeInBits;
3638 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3639
3640 // Preload SLocEntries.
3641 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3642 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3643 // Load it through the SourceManager and don't call ReadSLocEntry()
3644 // directly because the entry may have already been loaded in which case
3645 // calling ReadSLocEntry() directly would trigger an assertion in
3646 // SourceManager.
3647 SourceMgr.getLoadedSLocEntryByID(Index);
3648 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003649
3650 // Preload all the pending interesting identifiers by marking them out of
3651 // date.
3652 for (auto Offset : F.PreloadIdentifierOffsets) {
3653 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3654 F.IdentifierTableData + Offset);
3655
3656 ASTIdentifierLookupTrait Trait(*this, F);
3657 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3658 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003659 auto &II = PP.getIdentifierTable().getOwn(Key);
3660 II.setOutOfDate(true);
3661
3662 // Mark this identifier as being from an AST file so that we can track
3663 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003664 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003665
3666 // Associate the ID with the identifier so that the writer can reuse it.
3667 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3668 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 }
3671
Douglas Gregor603cd862013-03-22 18:50:14 +00003672 // Setup the import locations and notify the module manager that we've
3673 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003674 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3675 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 M != MEnd; ++M) {
3677 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003678
3679 ModuleMgr.moduleFileAccepted(&F);
3680
3681 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003682 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003683 // FIXME: We assume that locations from PCH / preamble do not need
3684 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003685 if (!M->ImportedBy)
3686 F.ImportLoc = M->ImportLoc;
3687 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003688 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 }
3690
Richard Smith33e0f7e2015-07-22 02:08:40 +00003691 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003692 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3693 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003694 // Mark all of the identifiers in the identifier table as being out of date,
3695 // so that various accessors know to check the loaded modules when the
3696 // identifier is used.
3697 //
3698 // For C++ modules, we don't need information on many identifiers (just
3699 // those that provide macros or are poisoned), so we mark all of
3700 // the interesting ones via PreloadIdentifierOffsets.
3701 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3702 IdEnd = PP.getIdentifierTable().end();
3703 Id != IdEnd; ++Id)
3704 Id->second->setOutOfDate(true);
3705 }
Manman Rena0f31a02016-04-29 19:04:05 +00003706 // Mark selectors as out of date.
3707 for (auto Sel : SelectorGeneration)
3708 SelectorOutOfDate[Sel.first] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003709
3710 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003711 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3712 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3714 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003715
3716 switch (Unresolved.Kind) {
3717 case UnresolvedModuleRef::Conflict:
3718 if (ResolvedMod) {
3719 Module::Conflict Conflict;
3720 Conflict.Other = ResolvedMod;
3721 Conflict.Message = Unresolved.String.str();
3722 Unresolved.Mod->Conflicts.push_back(Conflict);
3723 }
3724 continue;
3725
3726 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003728 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003730
Douglas Gregorfb912652013-03-20 21:10:35 +00003731 case UnresolvedModuleRef::Export:
3732 if (ResolvedMod || Unresolved.IsWildcard)
3733 Unresolved.Mod->Exports.push_back(
3734 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3735 continue;
3736 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003738 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003739
3740 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3741 // Might be unnecessary as use declarations are only used to build the
3742 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003743
3744 InitializeContext();
3745
Richard Smith3d8e97e2013-10-18 06:54:39 +00003746 if (SemaObj)
3747 UpdateSema();
3748
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 if (DeserializationListener)
3750 DeserializationListener->ReaderInitialized(this);
3751
3752 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003753 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 PrimaryModule.OriginalSourceFileID
3755 = FileID::get(PrimaryModule.SLocEntryBaseID
3756 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3757
3758 // If this AST file is a precompiled preamble, then set the
3759 // preamble file ID of the source manager to the file source file
3760 // from which the preamble was built.
3761 if (Type == MK_Preamble) {
3762 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3763 } else if (Type == MK_MainFile) {
3764 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3765 }
3766 }
3767
3768 // For any Objective-C class definitions we have already loaded, make sure
3769 // that we load any additional categories.
3770 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3771 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3772 ObjCClassesLoaded[I],
3773 PreviousGeneration);
3774 }
Douglas Gregore060e572013-01-25 01:03:03 +00003775
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003776 if (PP.getHeaderSearchInfo()
3777 .getHeaderSearchOpts()
3778 .ModulesValidateOncePerBuildSession) {
3779 // Now we are certain that the module and all modules it depends on are
3780 // up to date. Create or update timestamp files for modules that are
3781 // located in the module cache (not for PCH files that could be anywhere
3782 // in the filesystem).
3783 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3784 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003785 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003786 updateModuleTimestamp(*M.Mod);
3787 }
3788 }
3789 }
3790
Guy Benyei11169dd2012-12-18 14:30:41 +00003791 return Success;
3792}
3793
Ben Langmuir487ea142014-10-23 18:05:36 +00003794static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3795
Ben Langmuir70a1b812015-03-24 04:43:52 +00003796/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3797static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3798 return Stream.Read(8) == 'C' &&
3799 Stream.Read(8) == 'P' &&
3800 Stream.Read(8) == 'C' &&
3801 Stream.Read(8) == 'H';
3802}
3803
Richard Smith0f99d6a2015-08-09 08:48:41 +00003804static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3805 switch (Kind) {
3806 case MK_PCH:
3807 return 0; // PCH
3808 case MK_ImplicitModule:
3809 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003810 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003811 return 1; // module
3812 case MK_MainFile:
3813 case MK_Preamble:
3814 return 2; // main source file
3815 }
3816 llvm_unreachable("unknown module kind");
3817}
3818
Guy Benyei11169dd2012-12-18 14:30:41 +00003819ASTReader::ASTReadResult
3820ASTReader::ReadASTCore(StringRef FileName,
3821 ModuleKind Type,
3822 SourceLocation ImportLoc,
3823 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003824 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003825 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003826 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 unsigned ClientLoadCapabilities) {
3828 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003830 ModuleManager::AddModuleResult AddResult
3831 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003832 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003833 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003834 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003835
Douglas Gregor7029ce12013-03-19 00:28:20 +00003836 switch (AddResult) {
3837 case ModuleManager::AlreadyLoaded:
3838 return Success;
3839
3840 case ModuleManager::NewlyLoaded:
3841 // Load module file below.
3842 break;
3843
3844 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003845 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003846 // it.
3847 if (ClientLoadCapabilities & ARR_Missing)
3848 return Missing;
3849
3850 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003851 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003852 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003853 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003854 return Failure;
3855
3856 case ModuleManager::OutOfDate:
3857 // We couldn't load the module file because it is out-of-date. If the
3858 // client can handle out-of-date, return it.
3859 if (ClientLoadCapabilities & ARR_OutOfDate)
3860 return OutOfDate;
3861
3862 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003863 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003864 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003865 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 return Failure;
3867 }
3868
Douglas Gregor7029ce12013-03-19 00:28:20 +00003869 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003870
3871 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3872 // module?
3873 if (FileName != "-") {
3874 CurrentDir = llvm::sys::path::parent_path(FileName);
3875 if (CurrentDir.empty()) CurrentDir = ".";
3876 }
3877
3878 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003879 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003880 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003881 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003882 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3883
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003885 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003886 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3887 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 return Failure;
3889 }
3890
3891 // This is used for compatibility with older PCH formats.
3892 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003893 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003894 llvm::BitstreamEntry Entry = Stream.advance();
3895
3896 switch (Entry.Kind) {
3897 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003898 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003899 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003900 Error("invalid record at top-level of AST file");
3901 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003902
3903 case llvm::BitstreamEntry::SubBlock:
3904 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 }
3906
Chris Lattnerefa77172013-01-20 00:00:22 +00003907 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 case CONTROL_BLOCK_ID:
3909 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003910 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003912 // Check that we didn't try to load a non-module AST file as a module.
3913 //
3914 // FIXME: Should we also perform the converse check? Loading a module as
3915 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003916 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3917 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003918 F.ModuleName.empty()) {
3919 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3920 if (Result != OutOfDate ||
3921 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3922 Diag(diag::err_module_file_not_module) << FileName;
3923 return Result;
3924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 break;
3926
3927 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003928 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 case OutOfDate: return OutOfDate;
3930 case VersionMismatch: return VersionMismatch;
3931 case ConfigurationMismatch: return ConfigurationMismatch;
3932 case HadErrors: return HadErrors;
3933 }
3934 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003935
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 case AST_BLOCK_ID:
3937 if (!HaveReadControlBlock) {
3938 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003939 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 return VersionMismatch;
3941 }
3942
3943 // Record that we've loaded this module.
3944 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3945 return Success;
3946
3947 default:
3948 if (Stream.SkipBlock()) {
3949 Error("malformed block record in AST file");
3950 return Failure;
3951 }
3952 break;
3953 }
3954 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003955
3956 return Success;
3957}
3958
3959/// Parse a record and blob containing module file extension metadata.
3960static bool parseModuleFileExtensionMetadata(
3961 const SmallVectorImpl<uint64_t> &Record,
3962 StringRef Blob,
3963 ModuleFileExtensionMetadata &Metadata) {
3964 if (Record.size() < 4) return true;
3965
3966 Metadata.MajorVersion = Record[0];
3967 Metadata.MinorVersion = Record[1];
3968
3969 unsigned BlockNameLen = Record[2];
3970 unsigned UserInfoLen = Record[3];
3971
3972 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3973
3974 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3975 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3976 Blob.data() + BlockNameLen + UserInfoLen);
3977 return false;
3978}
3979
3980ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3981 BitstreamCursor &Stream = F.Stream;
3982
3983 RecordData Record;
3984 while (true) {
3985 llvm::BitstreamEntry Entry = Stream.advance();
3986 switch (Entry.Kind) {
3987 case llvm::BitstreamEntry::SubBlock:
3988 if (Stream.SkipBlock())
3989 return Failure;
3990
3991 continue;
3992
3993 case llvm::BitstreamEntry::EndBlock:
3994 return Success;
3995
3996 case llvm::BitstreamEntry::Error:
3997 return HadErrors;
3998
3999 case llvm::BitstreamEntry::Record:
4000 break;
4001 }
4002
4003 Record.clear();
4004 StringRef Blob;
4005 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4006 switch (RecCode) {
4007 case EXTENSION_METADATA: {
4008 ModuleFileExtensionMetadata Metadata;
4009 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4010 return Failure;
4011
4012 // Find a module file extension with this block name.
4013 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4014 if (Known == ModuleFileExtensions.end()) break;
4015
4016 // Form a reader.
4017 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4018 F, Stream)) {
4019 F.ExtensionReaders.push_back(std::move(Reader));
4020 }
4021
4022 break;
4023 }
4024 }
4025 }
4026
4027 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004028}
4029
Richard Smitha7e2cc62015-05-01 01:53:09 +00004030void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 // If there's a listener, notify them that we "read" the translation unit.
4032 if (DeserializationListener)
4033 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4034 Context.getTranslationUnitDecl());
4035
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 // FIXME: Find a better way to deal with collisions between these
4037 // built-in types. Right now, we just ignore the problem.
4038
4039 // Load the special types.
4040 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4041 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4042 if (!Context.CFConstantStringTypeDecl)
4043 Context.setCFConstantStringType(GetType(String));
4044 }
4045
4046 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4047 QualType FileType = GetType(File);
4048 if (FileType.isNull()) {
4049 Error("FILE type is NULL");
4050 return;
4051 }
4052
4053 if (!Context.FILEDecl) {
4054 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4055 Context.setFILEDecl(Typedef->getDecl());
4056 else {
4057 const TagType *Tag = FileType->getAs<TagType>();
4058 if (!Tag) {
4059 Error("Invalid FILE type in AST file");
4060 return;
4061 }
4062 Context.setFILEDecl(Tag->getDecl());
4063 }
4064 }
4065 }
4066
4067 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4068 QualType Jmp_bufType = GetType(Jmp_buf);
4069 if (Jmp_bufType.isNull()) {
4070 Error("jmp_buf type is NULL");
4071 return;
4072 }
4073
4074 if (!Context.jmp_bufDecl) {
4075 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4076 Context.setjmp_bufDecl(Typedef->getDecl());
4077 else {
4078 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4079 if (!Tag) {
4080 Error("Invalid jmp_buf type in AST file");
4081 return;
4082 }
4083 Context.setjmp_bufDecl(Tag->getDecl());
4084 }
4085 }
4086 }
4087
4088 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4089 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4090 if (Sigjmp_bufType.isNull()) {
4091 Error("sigjmp_buf type is NULL");
4092 return;
4093 }
4094
4095 if (!Context.sigjmp_bufDecl) {
4096 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4097 Context.setsigjmp_bufDecl(Typedef->getDecl());
4098 else {
4099 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4100 assert(Tag && "Invalid sigjmp_buf type in AST file");
4101 Context.setsigjmp_bufDecl(Tag->getDecl());
4102 }
4103 }
4104 }
4105
4106 if (unsigned ObjCIdRedef
4107 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4108 if (Context.ObjCIdRedefinitionType.isNull())
4109 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4110 }
4111
4112 if (unsigned ObjCClassRedef
4113 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4114 if (Context.ObjCClassRedefinitionType.isNull())
4115 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4116 }
4117
4118 if (unsigned ObjCSelRedef
4119 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4120 if (Context.ObjCSelRedefinitionType.isNull())
4121 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4122 }
4123
4124 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4125 QualType Ucontext_tType = GetType(Ucontext_t);
4126 if (Ucontext_tType.isNull()) {
4127 Error("ucontext_t type is NULL");
4128 return;
4129 }
4130
4131 if (!Context.ucontext_tDecl) {
4132 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4133 Context.setucontext_tDecl(Typedef->getDecl());
4134 else {
4135 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4136 assert(Tag && "Invalid ucontext_t type in AST file");
4137 Context.setucontext_tDecl(Tag->getDecl());
4138 }
4139 }
4140 }
4141 }
4142
4143 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4144
4145 // If there were any CUDA special declarations, deserialize them.
4146 if (!CUDASpecialDeclRefs.empty()) {
4147 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4148 Context.setcudaConfigureCallDecl(
4149 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4150 }
Richard Smith56be7542014-03-21 00:33:59 +00004151
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004153 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004154 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004155 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004156 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004157 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004158 if (Import.ImportLoc.isValid())
4159 PP.makeModuleVisible(Imported, Import.ImportLoc);
4160 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004161 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 }
4163 ImportedModules.clear();
4164}
4165
4166void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004167 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004168}
4169
Ben Langmuir70a1b812015-03-24 04:43:52 +00004170/// \brief Reads and return the signature record from \p StreamFile's control
4171/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004172static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4173 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004174 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004175 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004176
4177 // Scan for the CONTROL_BLOCK_ID block.
4178 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4179 return 0;
4180
4181 // Scan for SIGNATURE inside the control block.
4182 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004183 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004184 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4185 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4186 Entry.Kind != llvm::BitstreamEntry::Record)
4187 return 0;
4188
4189 Record.clear();
4190 StringRef Blob;
4191 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4192 return Record[0];
4193 }
4194}
4195
Guy Benyei11169dd2012-12-18 14:30:41 +00004196/// \brief Retrieve the name of the original source file name
4197/// directly from the AST file, without actually loading the AST
4198/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004199std::string ASTReader::getOriginalSourceFile(
4200 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004201 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004203 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004205 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4206 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 return std::string();
4208 }
4209
4210 // Initialize the stream
4211 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004212 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004213 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004214
4215 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004216 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4218 return std::string();
4219 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004220
Chris Lattnere7b154b2013-01-19 21:39:22 +00004221 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004222 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004223 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4224 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004225 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004226
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 // Scan for ORIGINAL_FILE inside the control block.
4228 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004229 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004230 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004231 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4232 return std::string();
4233
4234 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4235 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4236 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004238
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004240 StringRef Blob;
4241 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4242 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004244}
4245
4246namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004247
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 class SimplePCHValidator : public ASTReaderListener {
4249 const LangOptions &ExistingLangOpts;
4250 const TargetOptions &ExistingTargetOpts;
4251 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004252 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 public:
4256 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4257 const TargetOptions &ExistingTargetOpts,
4258 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004259 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 FileManager &FileMgr)
4261 : ExistingLangOpts(ExistingLangOpts),
4262 ExistingTargetOpts(ExistingTargetOpts),
4263 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004264 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 FileMgr(FileMgr)
4266 {
4267 }
4268
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004269 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4270 bool AllowCompatibleDifferences) override {
4271 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4272 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004274
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004275 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4276 bool AllowCompatibleDifferences) override {
4277 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4278 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004280
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004281 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4282 StringRef SpecificModuleCachePath,
4283 bool Complain) override {
4284 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4285 ExistingModuleCachePath,
4286 nullptr, ExistingLangOpts);
4287 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004288
Craig Topper3e89dfe2014-03-13 02:13:41 +00004289 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4290 bool Complain,
4291 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004292 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004293 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 }
4295 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004296
4297} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004298
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004299bool ASTReader::readASTFileControlBlock(
4300 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004301 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004302 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004303 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004305 // FIXME: This allows use of the VFS; we do not allow use of the
4306 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004307 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 if (!Buffer) {
4309 return true;
4310 }
4311
4312 // Initialize the stream
4313 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004314 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004315 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004316
4317 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004318 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004321 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004322 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004323 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004324
4325 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004326 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004327 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004328 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004329
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004331 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004332 bool DoneWithControlBlock = false;
4333 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004334 llvm::BitstreamEntry Entry = Stream.advance();
4335
4336 switch (Entry.Kind) {
4337 case llvm::BitstreamEntry::SubBlock: {
4338 switch (Entry.ID) {
4339 case OPTIONS_BLOCK_ID: {
4340 std::string IgnoredSuggestedPredefines;
4341 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4342 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004343 Listener, IgnoredSuggestedPredefines,
4344 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004345 return true;
4346 break;
4347 }
4348
4349 case INPUT_FILES_BLOCK_ID:
4350 InputFilesCursor = Stream;
4351 if (Stream.SkipBlock() ||
4352 (NeedsInputFiles &&
4353 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4354 return true;
4355 break;
4356
4357 default:
4358 if (Stream.SkipBlock())
4359 return true;
4360 break;
4361 }
4362
4363 continue;
4364 }
4365
4366 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004367 DoneWithControlBlock = true;
4368 break;
Richard Smith0516b182015-09-08 19:40:14 +00004369
4370 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004371 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004372
4373 case llvm::BitstreamEntry::Record:
4374 break;
4375 }
4376
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004377 if (DoneWithControlBlock) break;
4378
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004380 StringRef Blob;
4381 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004382 switch ((ControlRecordTypes)RecCode) {
4383 case METADATA: {
4384 if (Record[0] != VERSION_MAJOR)
4385 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004386
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004387 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004388 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004389
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004390 break;
4391 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004392 case MODULE_NAME:
4393 Listener.ReadModuleName(Blob);
4394 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004395 case MODULE_DIRECTORY:
4396 ModuleDir = Blob;
4397 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004398 case MODULE_MAP_FILE: {
4399 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004400 auto Path = ReadString(Record, Idx);
4401 ResolveImportedPath(Path, ModuleDir);
4402 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004403 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004404 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004405 case INPUT_FILE_OFFSETS: {
4406 if (!NeedsInputFiles)
4407 break;
4408
4409 unsigned NumInputFiles = Record[0];
4410 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004411 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004412 for (unsigned I = 0; I != NumInputFiles; ++I) {
4413 // Go find this input file.
4414 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004415
4416 if (isSystemFile && !NeedsSystemInputFiles)
4417 break; // the rest are system input files
4418
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004419 BitstreamCursor &Cursor = InputFilesCursor;
4420 SavedStreamPosition SavedPosition(Cursor);
4421 Cursor.JumpToBit(InputFileOffs[I]);
4422
4423 unsigned Code = Cursor.ReadCode();
4424 RecordData Record;
4425 StringRef Blob;
4426 bool shouldContinue = false;
4427 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4428 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004429 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004430 std::string Filename = Blob;
4431 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004432 shouldContinue = Listener.visitInputFile(
4433 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004434 break;
4435 }
4436 if (!shouldContinue)
4437 break;
4438 }
4439 break;
4440 }
4441
Richard Smithd4b230b2014-10-27 23:01:16 +00004442 case IMPORTS: {
4443 if (!NeedsImports)
4444 break;
4445
4446 unsigned Idx = 0, N = Record.size();
4447 while (Idx < N) {
4448 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004449 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004450 std::string Filename = ReadString(Record, Idx);
4451 ResolveImportedPath(Filename, ModuleDir);
4452 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004453 }
4454 break;
4455 }
4456
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004457 default:
4458 // No other validation to perform.
4459 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004462
4463 // Look for module file extension blocks, if requested.
4464 if (FindModuleFileExtensions) {
4465 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4466 bool DoneWithExtensionBlock = false;
4467 while (!DoneWithExtensionBlock) {
4468 llvm::BitstreamEntry Entry = Stream.advance();
4469
4470 switch (Entry.Kind) {
4471 case llvm::BitstreamEntry::SubBlock:
4472 if (Stream.SkipBlock())
4473 return true;
4474
4475 continue;
4476
4477 case llvm::BitstreamEntry::EndBlock:
4478 DoneWithExtensionBlock = true;
4479 continue;
4480
4481 case llvm::BitstreamEntry::Error:
4482 return true;
4483
4484 case llvm::BitstreamEntry::Record:
4485 break;
4486 }
4487
4488 Record.clear();
4489 StringRef Blob;
4490 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4491 switch (RecCode) {
4492 case EXTENSION_METADATA: {
4493 ModuleFileExtensionMetadata Metadata;
4494 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4495 return true;
4496
4497 Listener.readModuleFileExtension(Metadata);
4498 break;
4499 }
4500 }
4501 }
4502 }
4503 }
4504
4505 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506}
4507
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004508bool ASTReader::isAcceptableASTFile(
4509 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004510 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004511 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4512 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004513 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4514 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004515 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004516 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004517 validator,
4518 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004519}
4520
Ben Langmuir2c9af442014-04-10 17:57:43 +00004521ASTReader::ASTReadResult
4522ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 // Enter the submodule block.
4524 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4525 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004526 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528
4529 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4530 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004531 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 RecordData Record;
4533 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004534 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4535
4536 switch (Entry.Kind) {
4537 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4538 case llvm::BitstreamEntry::Error:
4539 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004540 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004541 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004542 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004543 case llvm::BitstreamEntry::Record:
4544 // The interesting case.
4545 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004547
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004549 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004551 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4552
4553 if ((Kind == SUBMODULE_METADATA) != First) {
4554 Error("submodule metadata record should be at beginning of block");
4555 return Failure;
4556 }
4557 First = false;
4558
4559 // Submodule information is only valid if we have a current module.
4560 // FIXME: Should we error on these cases?
4561 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4562 Kind != SUBMODULE_DEFINITION)
4563 continue;
4564
4565 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 default: // Default behavior: ignore.
4567 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004568
Richard Smith03478d92014-10-23 22:12:14 +00004569 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004570 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004572 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
Richard Smith03478d92014-10-23 22:12:14 +00004574
Chris Lattner0e6c9402013-01-20 02:38:54 +00004575 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004576 unsigned Idx = 0;
4577 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4578 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4579 bool IsFramework = Record[Idx++];
4580 bool IsExplicit = Record[Idx++];
4581 bool IsSystem = Record[Idx++];
4582 bool IsExternC = Record[Idx++];
4583 bool InferSubmodules = Record[Idx++];
4584 bool InferExplicitSubmodules = Record[Idx++];
4585 bool InferExportWildcard = Record[Idx++];
4586 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004587
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004588 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004589 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004591
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 // Retrieve this (sub)module from the module map, creating it if
4593 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004594 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004596
4597 // FIXME: set the definition loc for CurrentModule, or call
4598 // ModMap.setInferredModuleAllowedBy()
4599
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4601 if (GlobalIndex >= SubmodulesLoaded.size() ||
4602 SubmodulesLoaded[GlobalIndex]) {
4603 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004604 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004606
Douglas Gregor7029ce12013-03-19 00:28:20 +00004607 if (!ParentModule) {
4608 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4609 if (CurFile != F.File) {
4610 if (!Diags.isDiagnosticInFlight()) {
4611 Diag(diag::err_module_file_conflict)
4612 << CurrentModule->getTopLevelModuleName()
4613 << CurFile->getName()
4614 << F.File->getName();
4615 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004616 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004617 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004618 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004619
4620 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004621 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004622
Adrian Prantl15bcf702015-06-30 17:39:43 +00004623 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 CurrentModule->IsFromModuleFile = true;
4625 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004626 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 CurrentModule->InferSubmodules = InferSubmodules;
4628 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4629 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004630 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 if (DeserializationListener)
4632 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4633
4634 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004635
Richard Smith8a3e39a2016-03-28 21:31:09 +00004636 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004637 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004638 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004639 CurrentModule->UnresolvedConflicts.clear();
4640 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004641
4642 // The module is available unless it's missing a requirement; relevant
4643 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4644 // Missing headers that were present when the module was built do not
4645 // make it unavailable -- if we got this far, this must be an explicitly
4646 // imported module file.
4647 CurrentModule->Requirements.clear();
4648 CurrentModule->MissingHeaders.clear();
4649 CurrentModule->IsMissingRequirement =
4650 ParentModule && ParentModule->IsMissingRequirement;
4651 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 break;
4653 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004654
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004656 std::string Filename = Blob;
4657 ResolveImportedPath(F, Filename);
4658 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004660 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4661 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004662 // This can be a spurious difference caused by changing the VFS to
4663 // point to a different copy of the file, and it is too late to
4664 // to rebuild safely.
4665 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4666 // after input file validation only real problems would remain and we
4667 // could just error. For now, assume it's okay.
4668 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 }
4670 }
4671 break;
4672 }
4673
Richard Smith202210b2014-10-24 20:23:01 +00004674 case SUBMODULE_HEADER:
4675 case SUBMODULE_EXCLUDED_HEADER:
4676 case SUBMODULE_PRIVATE_HEADER:
4677 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004678 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4679 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004680 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004681
Richard Smith202210b2014-10-24 20:23:01 +00004682 case SUBMODULE_TEXTUAL_HEADER:
4683 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4684 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4685 // them here.
4686 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004687
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004689 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 break;
4691 }
4692
4693 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004694 std::string Dirname = Blob;
4695 ResolveImportedPath(F, Dirname);
4696 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004698 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4699 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004700 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4701 Error("mismatched umbrella directories in submodule");
4702 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 }
4704 }
4705 break;
4706 }
4707
4708 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 F.BaseSubmoduleID = getTotalNumSubmodules();
4710 F.LocalNumSubmodules = Record[0];
4711 unsigned LocalBaseSubmoduleID = Record[1];
4712 if (F.LocalNumSubmodules > 0) {
4713 // Introduce the global -> local mapping for submodules within this
4714 // module.
4715 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4716
4717 // Introduce the local -> global mapping for submodules within this
4718 // module.
4719 F.SubmoduleRemap.insertOrReplace(
4720 std::make_pair(LocalBaseSubmoduleID,
4721 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004722
Ben Langmuir52ca6782014-10-20 16:27:32 +00004723 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4724 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 break;
4726 }
4727
4728 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004730 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 Unresolved.File = &F;
4732 Unresolved.Mod = CurrentModule;
4733 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004734 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004736 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 }
4738 break;
4739 }
4740
4741 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004743 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 Unresolved.File = &F;
4745 Unresolved.Mod = CurrentModule;
4746 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004747 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004749 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 }
4751
4752 // Once we've loaded the set of exports, there's no reason to keep
4753 // the parsed, unresolved exports around.
4754 CurrentModule->UnresolvedExports.clear();
4755 break;
4756 }
4757 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004758 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 Context.getTargetInfo());
4760 break;
4761 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004762
4763 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004764 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004765 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004766 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004767
4768 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004769 CurrentModule->ConfigMacros.push_back(Blob.str());
4770 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004771
4772 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004773 UnresolvedModuleRef Unresolved;
4774 Unresolved.File = &F;
4775 Unresolved.Mod = CurrentModule;
4776 Unresolved.ID = Record[0];
4777 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4778 Unresolved.IsWildcard = false;
4779 Unresolved.String = Blob;
4780 UnresolvedModuleRefs.push_back(Unresolved);
4781 break;
4782 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004783
4784 case SUBMODULE_INITIALIZERS:
4785 SmallVector<uint32_t, 16> Inits;
4786 for (auto &ID : Record)
4787 Inits.push_back(getGlobalDeclID(F, ID));
4788 Context.addLazyModuleInitializers(CurrentModule, Inits);
4789 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 }
4791 }
4792}
4793
4794/// \brief Parse the record that corresponds to a LangOptions data
4795/// structure.
4796///
4797/// This routine parses the language options from the AST file and then gives
4798/// them to the AST listener if one is set.
4799///
4800/// \returns true if the listener deems the file unacceptable, false otherwise.
4801bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4802 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004803 ASTReaderListener &Listener,
4804 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 LangOptions LangOpts;
4806 unsigned Idx = 0;
4807#define LANGOPT(Name, Bits, Default, Description) \
4808 LangOpts.Name = Record[Idx++];
4809#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4810 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4811#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004812#define SANITIZER(NAME, ID) \
4813 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004814#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004815
Ben Langmuircd98cb72015-06-23 18:20:18 +00004816 for (unsigned N = Record[Idx++]; N; --N)
4817 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4818
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4820 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4821 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004822
Ben Langmuird4a667a2015-06-23 18:20:23 +00004823 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004824
4825 // Comment options.
4826 for (unsigned N = Record[Idx++]; N; --N) {
4827 LangOpts.CommentOpts.BlockCommandNames.push_back(
4828 ReadString(Record, Idx));
4829 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004830 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004831
Samuel Antaoee8fb302016-01-06 13:42:12 +00004832 // OpenMP offloading options.
4833 for (unsigned N = Record[Idx++]; N; --N) {
4834 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4835 }
4836
4837 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4838
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004839 return Listener.ReadLanguageOptions(LangOpts, Complain,
4840 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004841}
4842
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004843bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4844 ASTReaderListener &Listener,
4845 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 unsigned Idx = 0;
4847 TargetOptions TargetOpts;
4848 TargetOpts.Triple = ReadString(Record, Idx);
4849 TargetOpts.CPU = ReadString(Record, Idx);
4850 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 for (unsigned N = Record[Idx++]; N; --N) {
4852 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4853 }
4854 for (unsigned N = Record[Idx++]; N; --N) {
4855 TargetOpts.Features.push_back(ReadString(Record, Idx));
4856 }
4857
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004858 return Listener.ReadTargetOptions(TargetOpts, Complain,
4859 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004860}
4861
4862bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4863 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004864 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004866#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004867#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004868 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004869#include "clang/Basic/DiagnosticOptions.def"
4870
Richard Smith3be1cb22014-08-07 00:24:21 +00004871 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004872 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004873 for (unsigned N = Record[Idx++]; N; --N)
4874 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004875
4876 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4877}
4878
4879bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4880 ASTReaderListener &Listener) {
4881 FileSystemOptions FSOpts;
4882 unsigned Idx = 0;
4883 FSOpts.WorkingDir = ReadString(Record, Idx);
4884 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4885}
4886
4887bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4888 bool Complain,
4889 ASTReaderListener &Listener) {
4890 HeaderSearchOptions HSOpts;
4891 unsigned Idx = 0;
4892 HSOpts.Sysroot = ReadString(Record, Idx);
4893
4894 // Include entries.
4895 for (unsigned N = Record[Idx++]; N; --N) {
4896 std::string Path = ReadString(Record, Idx);
4897 frontend::IncludeDirGroup Group
4898 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 bool IsFramework = Record[Idx++];
4900 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004901 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4902 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 }
4904
4905 // System header prefixes.
4906 for (unsigned N = Record[Idx++]; N; --N) {
4907 std::string Prefix = ReadString(Record, Idx);
4908 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004909 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 }
4911
4912 HSOpts.ResourceDir = ReadString(Record, Idx);
4913 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004914 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 HSOpts.DisableModuleHash = Record[Idx++];
4916 HSOpts.UseBuiltinIncludes = Record[Idx++];
4917 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4918 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4919 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004920 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004921
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004922 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4923 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004924}
4925
4926bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4927 bool Complain,
4928 ASTReaderListener &Listener,
4929 std::string &SuggestedPredefines) {
4930 PreprocessorOptions PPOpts;
4931 unsigned Idx = 0;
4932
4933 // Macro definitions/undefs
4934 for (unsigned N = Record[Idx++]; N; --N) {
4935 std::string Macro = ReadString(Record, Idx);
4936 bool IsUndef = Record[Idx++];
4937 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4938 }
4939
4940 // Includes
4941 for (unsigned N = Record[Idx++]; N; --N) {
4942 PPOpts.Includes.push_back(ReadString(Record, Idx));
4943 }
4944
4945 // Macro Includes
4946 for (unsigned N = Record[Idx++]; N; --N) {
4947 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4948 }
4949
4950 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004951 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4953 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4954 PPOpts.ObjCXXARCStandardLibrary =
4955 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4956 SuggestedPredefines.clear();
4957 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4958 SuggestedPredefines);
4959}
4960
4961std::pair<ModuleFile *, unsigned>
4962ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4963 GlobalPreprocessedEntityMapType::iterator
4964 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4965 assert(I != GlobalPreprocessedEntityMap.end() &&
4966 "Corrupted global preprocessed entity map");
4967 ModuleFile *M = I->second;
4968 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4969 return std::make_pair(M, LocalIndex);
4970}
4971
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004972llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004973ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4974 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4975 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4976 Mod.NumPreprocessedEntities);
4977
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004978 return llvm::make_range(PreprocessingRecord::iterator(),
4979 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004980}
4981
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004982llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004983ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004984 return llvm::make_range(
4985 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4986 ModuleDeclIterator(this, &Mod,
4987 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004988}
4989
4990PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4991 PreprocessedEntityID PPID = Index+1;
4992 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4993 ModuleFile &M = *PPInfo.first;
4994 unsigned LocalIndex = PPInfo.second;
4995 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4996
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 if (!PP.getPreprocessingRecord()) {
4998 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004999 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 }
5001
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005002 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5003 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5004
5005 llvm::BitstreamEntry Entry =
5006 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5007 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005008 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005009
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005011 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5012 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005014 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 RecordData Record;
5016 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005017 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5018 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 switch (RecType) {
5020 case PPD_MACRO_EXPANSION: {
5021 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005022 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005023 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 if (isBuiltin)
5025 Name = getLocalIdentifier(M, Record[1]);
5026 else {
Richard Smith66a81862015-05-04 02:25:31 +00005027 PreprocessedEntityID GlobalID =
5028 getGlobalPreprocessedEntityID(M, Record[1]);
5029 Def = cast<MacroDefinitionRecord>(
5030 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 }
5032
5033 MacroExpansion *ME;
5034 if (isBuiltin)
5035 ME = new (PPRec) MacroExpansion(Name, Range);
5036 else
5037 ME = new (PPRec) MacroExpansion(Def, Range);
5038
5039 return ME;
5040 }
5041
5042 case PPD_MACRO_DEFINITION: {
5043 // Decode the identifier info and then check again; if the macro is
5044 // still defined and associated with the identifier,
5045 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005046 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005047
5048 if (DeserializationListener)
5049 DeserializationListener->MacroDefinitionRead(PPID, MD);
5050
5051 return MD;
5052 }
5053
5054 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005055 const char *FullFileNameStart = Blob.data() + Record[0];
5056 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005057 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 if (!FullFileName.empty())
5059 File = PP.getFileManager().getFile(FullFileName);
5060
5061 // FIXME: Stable encoding
5062 InclusionDirective::InclusionKind Kind
5063 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5064 InclusionDirective *ID
5065 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005066 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 Record[1], Record[3],
5068 File,
5069 Range);
5070 return ID;
5071 }
5072 }
5073
5074 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5075}
5076
5077/// \brief \arg SLocMapI points at a chunk of a module that contains no
5078/// preprocessed entities or the entities it contains are not the ones we are
5079/// looking for. Find the next module that contains entities and return the ID
5080/// of the first entry.
5081PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5082 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5083 ++SLocMapI;
5084 for (GlobalSLocOffsetMapType::const_iterator
5085 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5086 ModuleFile &M = *SLocMapI->second;
5087 if (M.NumPreprocessedEntities)
5088 return M.BasePreprocessedEntityID;
5089 }
5090
5091 return getTotalNumPreprocessedEntities();
5092}
5093
5094namespace {
5095
Guy Benyei11169dd2012-12-18 14:30:41 +00005096struct PPEntityComp {
5097 const ASTReader &Reader;
5098 ModuleFile &M;
5099
5100 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5101
5102 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5103 SourceLocation LHS = getLoc(L);
5104 SourceLocation RHS = getLoc(R);
5105 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5106 }
5107
5108 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5109 SourceLocation LHS = getLoc(L);
5110 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5111 }
5112
5113 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5114 SourceLocation RHS = getLoc(R);
5115 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5116 }
5117
5118 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005119 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 }
5121};
5122
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005123} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005124
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005125PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5126 bool EndsAfter) const {
5127 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 return getTotalNumPreprocessedEntities();
5129
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005130 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5131 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5133 "Corrupted global sloc offset map");
5134
5135 if (SLocMapI->second->NumPreprocessedEntities == 0)
5136 return findNextPreprocessedEntity(SLocMapI);
5137
5138 ModuleFile &M = *SLocMapI->second;
5139 typedef const PPEntityOffset *pp_iterator;
5140 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5141 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5142
5143 size_t Count = M.NumPreprocessedEntities;
5144 size_t Half;
5145 pp_iterator First = pp_begin;
5146 pp_iterator PPI;
5147
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005148 if (EndsAfter) {
5149 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005150 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005151 } else {
5152 // Do a binary search manually instead of using std::lower_bound because
5153 // The end locations of entities may be unordered (when a macro expansion
5154 // is inside another macro argument), but for this case it is not important
5155 // whether we get the first macro expansion or its containing macro.
5156 while (Count > 0) {
5157 Half = Count / 2;
5158 PPI = First;
5159 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005160 if (SourceMgr.isBeforeInTranslationUnit(
5161 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005162 First = PPI;
5163 ++First;
5164 Count = Count - Half - 1;
5165 } else
5166 Count = Half;
5167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 }
5169
5170 if (PPI == pp_end)
5171 return findNextPreprocessedEntity(SLocMapI);
5172
5173 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5174}
5175
Guy Benyei11169dd2012-12-18 14:30:41 +00005176/// \brief Returns a pair of [Begin, End) indices of preallocated
5177/// preprocessed entities that \arg Range encompasses.
5178std::pair<unsigned, unsigned>
5179 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5180 if (Range.isInvalid())
5181 return std::make_pair(0,0);
5182 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5183
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005184 PreprocessedEntityID BeginID =
5185 findPreprocessedEntity(Range.getBegin(), false);
5186 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 return std::make_pair(BeginID, EndID);
5188}
5189
5190/// \brief Optionally returns true or false if the preallocated preprocessed
5191/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005192Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 FileID FID) {
5194 if (FID.isInvalid())
5195 return false;
5196
5197 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5198 ModuleFile &M = *PPInfo.first;
5199 unsigned LocalIndex = PPInfo.second;
5200 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5201
Richard Smithcb34bd32016-03-27 07:28:06 +00005202 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 if (Loc.isInvalid())
5204 return false;
5205
5206 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5207 return true;
5208 else
5209 return false;
5210}
5211
5212namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005213
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 /// \brief Visitor used to search for information about a header file.
5215 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 const FileEntry *FE;
5217
David Blaikie05785d12013-02-20 22:23:23 +00005218 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005219
5220 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005221 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5222 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005223
5224 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 HeaderFileInfoLookupTable *Table
5226 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5227 if (!Table)
5228 return false;
5229
5230 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005231 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 if (Pos == Table->end())
5233 return false;
5234
Richard Smithbdf2d932015-07-30 03:37:16 +00005235 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 return true;
5237 }
5238
David Blaikie05785d12013-02-20 22:23:23 +00005239 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005241
5242} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005243
5244HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005245 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005246 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005247 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005249
5250 return HeaderFileInfo();
5251}
5252
5253void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5254 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005255 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5257 ModuleFile &F = *(*I);
5258 unsigned Idx = 0;
5259 DiagStates.clear();
5260 assert(!Diag.DiagStates.empty());
5261 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5262 while (Idx < F.PragmaDiagMappings.size()) {
5263 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5264 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5265 if (DiagStateID != 0) {
5266 Diag.DiagStatePoints.push_back(
5267 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5268 FullSourceLoc(Loc, SourceMgr)));
5269 continue;
5270 }
5271
5272 assert(DiagStateID == 0);
5273 // A new DiagState was created here.
5274 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5275 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5276 DiagStates.push_back(NewState);
5277 Diag.DiagStatePoints.push_back(
5278 DiagnosticsEngine::DiagStatePoint(NewState,
5279 FullSourceLoc(Loc, SourceMgr)));
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005280 while (true) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 assert(Idx < F.PragmaDiagMappings.size() &&
5282 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5283 if (Idx >= F.PragmaDiagMappings.size()) {
5284 break; // Something is messed up but at least avoid infinite loop in
5285 // release build.
5286 }
5287 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5288 if (DiagID == (unsigned)-1) {
5289 break; // no more diag/map pairs for this location.
5290 }
Alp Tokerc726c362014-06-10 09:31:37 +00005291 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5292 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5293 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 }
5295 }
5296 }
5297}
5298
5299/// \brief Get the correct cursor and offset for loading a type.
5300ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5301 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5302 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5303 ModuleFile *M = I->second;
5304 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5305}
5306
5307/// \brief Read and return the type with the given index..
5308///
5309/// The index is the type ID, shifted and minus the number of predefs. This
5310/// routine actually reads the record corresponding to the type at the given
5311/// location. It is a helper routine for GetType, which deals with reading type
5312/// IDs.
5313QualType ASTReader::readTypeRecord(unsigned Index) {
5314 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005315 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005316
5317 // Keep track of where we are in the stream, then jump back there
5318 // after reading this type.
5319 SavedStreamPosition SavedPosition(DeclsCursor);
5320
5321 ReadingKindTracker ReadingKind(Read_Type, *this);
5322
5323 // Note that we are loading a type record.
5324 Deserializing AType(this);
5325
5326 unsigned Idx = 0;
5327 DeclsCursor.JumpToBit(Loc.Offset);
5328 RecordData Record;
5329 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005330 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case TYPE_EXT_QUAL: {
5332 if (Record.size() != 2) {
5333 Error("Incorrect encoding of extended qualifier type");
5334 return QualType();
5335 }
5336 QualType Base = readType(*Loc.F, Record, Idx);
5337 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5338 return Context.getQualifiedType(Base, Quals);
5339 }
5340
5341 case TYPE_COMPLEX: {
5342 if (Record.size() != 1) {
5343 Error("Incorrect encoding of complex type");
5344 return QualType();
5345 }
5346 QualType ElemType = readType(*Loc.F, Record, Idx);
5347 return Context.getComplexType(ElemType);
5348 }
5349
5350 case TYPE_POINTER: {
5351 if (Record.size() != 1) {
5352 Error("Incorrect encoding of pointer type");
5353 return QualType();
5354 }
5355 QualType PointeeType = readType(*Loc.F, Record, Idx);
5356 return Context.getPointerType(PointeeType);
5357 }
5358
Reid Kleckner8a365022013-06-24 17:51:48 +00005359 case TYPE_DECAYED: {
5360 if (Record.size() != 1) {
5361 Error("Incorrect encoding of decayed type");
5362 return QualType();
5363 }
5364 QualType OriginalType = readType(*Loc.F, Record, Idx);
5365 QualType DT = Context.getAdjustedParameterType(OriginalType);
5366 if (!isa<DecayedType>(DT))
5367 Error("Decayed type does not decay");
5368 return DT;
5369 }
5370
Reid Kleckner0503a872013-12-05 01:23:43 +00005371 case TYPE_ADJUSTED: {
5372 if (Record.size() != 2) {
5373 Error("Incorrect encoding of adjusted type");
5374 return QualType();
5375 }
5376 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5377 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5378 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5379 }
5380
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case TYPE_BLOCK_POINTER: {
5382 if (Record.size() != 1) {
5383 Error("Incorrect encoding of block pointer type");
5384 return QualType();
5385 }
5386 QualType PointeeType = readType(*Loc.F, Record, Idx);
5387 return Context.getBlockPointerType(PointeeType);
5388 }
5389
5390 case TYPE_LVALUE_REFERENCE: {
5391 if (Record.size() != 2) {
5392 Error("Incorrect encoding of lvalue reference type");
5393 return QualType();
5394 }
5395 QualType PointeeType = readType(*Loc.F, Record, Idx);
5396 return Context.getLValueReferenceType(PointeeType, Record[1]);
5397 }
5398
5399 case TYPE_RVALUE_REFERENCE: {
5400 if (Record.size() != 1) {
5401 Error("Incorrect encoding of rvalue reference type");
5402 return QualType();
5403 }
5404 QualType PointeeType = readType(*Loc.F, Record, Idx);
5405 return Context.getRValueReferenceType(PointeeType);
5406 }
5407
5408 case TYPE_MEMBER_POINTER: {
5409 if (Record.size() != 2) {
5410 Error("Incorrect encoding of member pointer type");
5411 return QualType();
5412 }
5413 QualType PointeeType = readType(*Loc.F, Record, Idx);
5414 QualType ClassType = readType(*Loc.F, Record, Idx);
5415 if (PointeeType.isNull() || ClassType.isNull())
5416 return QualType();
5417
5418 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5419 }
5420
5421 case TYPE_CONSTANT_ARRAY: {
5422 QualType ElementType = readType(*Loc.F, Record, Idx);
5423 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5424 unsigned IndexTypeQuals = Record[2];
5425 unsigned Idx = 3;
5426 llvm::APInt Size = ReadAPInt(Record, Idx);
5427 return Context.getConstantArrayType(ElementType, Size,
5428 ASM, IndexTypeQuals);
5429 }
5430
5431 case TYPE_INCOMPLETE_ARRAY: {
5432 QualType ElementType = readType(*Loc.F, Record, Idx);
5433 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5434 unsigned IndexTypeQuals = Record[2];
5435 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5436 }
5437
5438 case TYPE_VARIABLE_ARRAY: {
5439 QualType ElementType = readType(*Loc.F, Record, Idx);
5440 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5441 unsigned IndexTypeQuals = Record[2];
5442 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5443 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5444 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5445 ASM, IndexTypeQuals,
5446 SourceRange(LBLoc, RBLoc));
5447 }
5448
5449 case TYPE_VECTOR: {
5450 if (Record.size() != 3) {
5451 Error("incorrect encoding of vector type in AST file");
5452 return QualType();
5453 }
5454
5455 QualType ElementType = readType(*Loc.F, Record, Idx);
5456 unsigned NumElements = Record[1];
5457 unsigned VecKind = Record[2];
5458 return Context.getVectorType(ElementType, NumElements,
5459 (VectorType::VectorKind)VecKind);
5460 }
5461
5462 case TYPE_EXT_VECTOR: {
5463 if (Record.size() != 3) {
5464 Error("incorrect encoding of extended vector type in AST file");
5465 return QualType();
5466 }
5467
5468 QualType ElementType = readType(*Loc.F, Record, Idx);
5469 unsigned NumElements = Record[1];
5470 return Context.getExtVectorType(ElementType, NumElements);
5471 }
5472
5473 case TYPE_FUNCTION_NO_PROTO: {
5474 if (Record.size() != 6) {
5475 Error("incorrect encoding of no-proto function type");
5476 return QualType();
5477 }
5478 QualType ResultType = readType(*Loc.F, Record, Idx);
5479 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5480 (CallingConv)Record[4], Record[5]);
5481 return Context.getFunctionNoProtoType(ResultType, Info);
5482 }
5483
5484 case TYPE_FUNCTION_PROTO: {
5485 QualType ResultType = readType(*Loc.F, Record, Idx);
5486
5487 FunctionProtoType::ExtProtoInfo EPI;
5488 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5489 /*hasregparm*/ Record[2],
5490 /*regparm*/ Record[3],
5491 static_cast<CallingConv>(Record[4]),
5492 /*produces*/ Record[5]);
5493
5494 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005495
5496 EPI.Variadic = Record[Idx++];
5497 EPI.HasTrailingReturn = Record[Idx++];
5498 EPI.TypeQuals = Record[Idx++];
5499 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005500 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005501 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005502
5503 unsigned NumParams = Record[Idx++];
5504 SmallVector<QualType, 16> ParamTypes;
5505 for (unsigned I = 0; I != NumParams; ++I)
5506 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5507
John McCall18afab72016-03-01 00:49:02 +00005508 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5509 if (Idx != Record.size()) {
5510 for (unsigned I = 0; I != NumParams; ++I)
5511 ExtParameterInfos.push_back(
5512 FunctionProtoType::ExtParameterInfo
5513 ::getFromOpaqueValue(Record[Idx++]));
5514 EPI.ExtParameterInfos = ExtParameterInfos.data();
5515 }
5516
5517 assert(Idx == Record.size());
5518
Jordan Rose5c382722013-03-08 21:51:21 +00005519 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005520 }
5521
5522 case TYPE_UNRESOLVED_USING: {
5523 unsigned Idx = 0;
5524 return Context.getTypeDeclType(
5525 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5526 }
5527
5528 case TYPE_TYPEDEF: {
5529 if (Record.size() != 2) {
5530 Error("incorrect encoding of typedef type");
5531 return QualType();
5532 }
5533 unsigned Idx = 0;
5534 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5535 QualType Canonical = readType(*Loc.F, Record, Idx);
5536 if (!Canonical.isNull())
5537 Canonical = Context.getCanonicalType(Canonical);
5538 return Context.getTypedefType(Decl, Canonical);
5539 }
5540
5541 case TYPE_TYPEOF_EXPR:
5542 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5543
5544 case TYPE_TYPEOF: {
5545 if (Record.size() != 1) {
5546 Error("incorrect encoding of typeof(type) in AST file");
5547 return QualType();
5548 }
5549 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5550 return Context.getTypeOfType(UnderlyingType);
5551 }
5552
5553 case TYPE_DECLTYPE: {
5554 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5555 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5556 }
5557
5558 case TYPE_UNARY_TRANSFORM: {
5559 QualType BaseType = readType(*Loc.F, Record, Idx);
5560 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5561 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5562 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5563 }
5564
Richard Smith74aeef52013-04-26 16:15:35 +00005565 case TYPE_AUTO: {
5566 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005567 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005568 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005569 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005571
5572 case TYPE_RECORD: {
5573 if (Record.size() != 2) {
5574 Error("incorrect encoding of record type");
5575 return QualType();
5576 }
5577 unsigned Idx = 0;
5578 bool IsDependent = Record[Idx++];
5579 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5580 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5581 QualType T = Context.getRecordType(RD);
5582 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5583 return T;
5584 }
5585
5586 case TYPE_ENUM: {
5587 if (Record.size() != 2) {
5588 Error("incorrect encoding of enum type");
5589 return QualType();
5590 }
5591 unsigned Idx = 0;
5592 bool IsDependent = Record[Idx++];
5593 QualType T
5594 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5595 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5596 return T;
5597 }
5598
5599 case TYPE_ATTRIBUTED: {
5600 if (Record.size() != 3) {
5601 Error("incorrect encoding of attributed type");
5602 return QualType();
5603 }
5604 QualType modifiedType = readType(*Loc.F, Record, Idx);
5605 QualType equivalentType = readType(*Loc.F, Record, Idx);
5606 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5607 return Context.getAttributedType(kind, modifiedType, equivalentType);
5608 }
5609
5610 case TYPE_PAREN: {
5611 if (Record.size() != 1) {
5612 Error("incorrect encoding of paren type");
5613 return QualType();
5614 }
5615 QualType InnerType = readType(*Loc.F, Record, Idx);
5616 return Context.getParenType(InnerType);
5617 }
5618
5619 case TYPE_PACK_EXPANSION: {
5620 if (Record.size() != 2) {
5621 Error("incorrect encoding of pack expansion type");
5622 return QualType();
5623 }
5624 QualType Pattern = readType(*Loc.F, Record, Idx);
5625 if (Pattern.isNull())
5626 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005627 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 if (Record[1])
5629 NumExpansions = Record[1] - 1;
5630 return Context.getPackExpansionType(Pattern, NumExpansions);
5631 }
5632
5633 case TYPE_ELABORATED: {
5634 unsigned Idx = 0;
5635 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5636 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5637 QualType NamedType = readType(*Loc.F, Record, Idx);
5638 return Context.getElaboratedType(Keyword, NNS, NamedType);
5639 }
5640
5641 case TYPE_OBJC_INTERFACE: {
5642 unsigned Idx = 0;
5643 ObjCInterfaceDecl *ItfD
5644 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5645 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5646 }
5647
Manman Rene6be26c2016-09-13 17:25:08 +00005648 case TYPE_OBJC_TYPE_PARAM: {
5649 unsigned Idx = 0;
5650 ObjCTypeParamDecl *Decl
5651 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5652 unsigned NumProtos = Record[Idx++];
5653 SmallVector<ObjCProtocolDecl*, 4> Protos;
5654 for (unsigned I = 0; I != NumProtos; ++I)
5655 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5656 return Context.getObjCTypeParamType(Decl, Protos);
5657 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 case TYPE_OBJC_OBJECT: {
5659 unsigned Idx = 0;
5660 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005661 unsigned NumTypeArgs = Record[Idx++];
5662 SmallVector<QualType, 4> TypeArgs;
5663 for (unsigned I = 0; I != NumTypeArgs; ++I)
5664 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 unsigned NumProtos = Record[Idx++];
5666 SmallVector<ObjCProtocolDecl*, 4> Protos;
5667 for (unsigned I = 0; I != NumProtos; ++I)
5668 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005669 bool IsKindOf = Record[Idx++];
5670 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 }
5672
5673 case TYPE_OBJC_OBJECT_POINTER: {
5674 unsigned Idx = 0;
5675 QualType Pointee = readType(*Loc.F, Record, Idx);
5676 return Context.getObjCObjectPointerType(Pointee);
5677 }
5678
5679 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5680 unsigned Idx = 0;
5681 QualType Parm = readType(*Loc.F, Record, Idx);
5682 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005683 return Context.getSubstTemplateTypeParmType(
5684 cast<TemplateTypeParmType>(Parm),
5685 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005686 }
5687
5688 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5689 unsigned Idx = 0;
5690 QualType Parm = readType(*Loc.F, Record, Idx);
5691 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5692 return Context.getSubstTemplateTypeParmPackType(
5693 cast<TemplateTypeParmType>(Parm),
5694 ArgPack);
5695 }
5696
5697 case TYPE_INJECTED_CLASS_NAME: {
5698 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5699 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5700 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5701 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005702 const Type *T = nullptr;
5703 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5704 if (const Type *Existing = DI->getTypeForDecl()) {
5705 T = Existing;
5706 break;
5707 }
5708 }
5709 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005710 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005711 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5712 DI->setTypeForDecl(T);
5713 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005714 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005715 }
5716
5717 case TYPE_TEMPLATE_TYPE_PARM: {
5718 unsigned Idx = 0;
5719 unsigned Depth = Record[Idx++];
5720 unsigned Index = Record[Idx++];
5721 bool Pack = Record[Idx++];
5722 TemplateTypeParmDecl *D
5723 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5724 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5725 }
5726
5727 case TYPE_DEPENDENT_NAME: {
5728 unsigned Idx = 0;
5729 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5730 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005731 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 QualType Canon = readType(*Loc.F, Record, Idx);
5733 if (!Canon.isNull())
5734 Canon = Context.getCanonicalType(Canon);
5735 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5736 }
5737
5738 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5739 unsigned Idx = 0;
5740 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5741 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005742 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 unsigned NumArgs = Record[Idx++];
5744 SmallVector<TemplateArgument, 8> Args;
5745 Args.reserve(NumArgs);
5746 while (NumArgs--)
5747 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5748 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005749 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005750 }
5751
5752 case TYPE_DEPENDENT_SIZED_ARRAY: {
5753 unsigned Idx = 0;
5754
5755 // ArrayType
5756 QualType ElementType = readType(*Loc.F, Record, Idx);
5757 ArrayType::ArraySizeModifier ASM
5758 = (ArrayType::ArraySizeModifier)Record[Idx++];
5759 unsigned IndexTypeQuals = Record[Idx++];
5760
5761 // DependentSizedArrayType
5762 Expr *NumElts = ReadExpr(*Loc.F);
5763 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5764
5765 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5766 IndexTypeQuals, Brackets);
5767 }
5768
5769 case TYPE_TEMPLATE_SPECIALIZATION: {
5770 unsigned Idx = 0;
5771 bool IsDependent = Record[Idx++];
5772 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5773 SmallVector<TemplateArgument, 8> Args;
5774 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5775 QualType Underlying = readType(*Loc.F, Record, Idx);
5776 QualType T;
5777 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005778 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005779 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005780 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5782 return T;
5783 }
5784
5785 case TYPE_ATOMIC: {
5786 if (Record.size() != 1) {
5787 Error("Incorrect encoding of atomic type");
5788 return QualType();
5789 }
5790 QualType ValueType = readType(*Loc.F, Record, Idx);
5791 return Context.getAtomicType(ValueType);
5792 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005793
5794 case TYPE_PIPE: {
5795 if (Record.size() != 1) {
5796 Error("Incorrect encoding of pipe type");
5797 return QualType();
5798 }
5799
5800 // Reading the pipe element type.
5801 QualType ElementType = readType(*Loc.F, Record, Idx);
5802 return Context.getPipeType(ElementType);
5803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 }
5805 llvm_unreachable("Invalid TypeCode!");
5806}
5807
Richard Smith564417a2014-03-20 21:47:22 +00005808void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5809 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005810 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005811 const RecordData &Record, unsigned &Idx) {
5812 ExceptionSpecificationType EST =
5813 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005814 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005815 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005816 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005817 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005818 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005819 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005820 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005821 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005822 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5823 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005824 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005825 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005826 }
5827}
5828
Guy Benyei11169dd2012-12-18 14:30:41 +00005829class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5830 ASTReader &Reader;
5831 ModuleFile &F;
5832 const ASTReader::RecordData &Record;
5833 unsigned &Idx;
5834
5835 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5836 unsigned &I) {
5837 return Reader.ReadSourceLocation(F, R, I);
5838 }
5839
5840 template<typename T>
5841 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5842 return Reader.ReadDeclAs<T>(F, Record, Idx);
5843 }
5844
5845public:
5846 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5847 const ASTReader::RecordData &Record, unsigned &Idx)
5848 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5849 { }
5850
5851 // We want compile-time assurance that we've enumerated all of
5852 // these, so unfortunately we have to declare them first, then
5853 // define them out-of-line.
5854#define ABSTRACT_TYPELOC(CLASS, PARENT)
5855#define TYPELOC(CLASS, PARENT) \
5856 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5857#include "clang/AST/TypeLocNodes.def"
5858
5859 void VisitFunctionTypeLoc(FunctionTypeLoc);
5860 void VisitArrayTypeLoc(ArrayTypeLoc);
5861};
5862
5863void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5864 // nothing to do
5865}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005866
Guy Benyei11169dd2012-12-18 14:30:41 +00005867void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5868 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5869 if (TL.needsExtraLocalData()) {
5870 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5871 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5872 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5873 TL.setModeAttr(Record[Idx++]);
5874 }
5875}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005876
Guy Benyei11169dd2012-12-18 14:30:41 +00005877void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5878 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5879}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005880
Guy Benyei11169dd2012-12-18 14:30:41 +00005881void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5882 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5883}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005884
Reid Kleckner8a365022013-06-24 17:51:48 +00005885void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5886 // nothing to do
5887}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005888
Reid Kleckner0503a872013-12-05 01:23:43 +00005889void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5890 // nothing to do
5891}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005892
Guy Benyei11169dd2012-12-18 14:30:41 +00005893void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5894 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5895}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005896
Guy Benyei11169dd2012-12-18 14:30:41 +00005897void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5898 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5899}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005900
Guy Benyei11169dd2012-12-18 14:30:41 +00005901void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5902 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5903}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005904
Guy Benyei11169dd2012-12-18 14:30:41 +00005905void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5906 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5907 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5908}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005909
Guy Benyei11169dd2012-12-18 14:30:41 +00005910void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5911 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5912 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5913 if (Record[Idx++])
5914 TL.setSizeExpr(Reader.ReadExpr(F));
5915 else
Craig Toppera13603a2014-05-22 05:54:18 +00005916 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005917}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005918
Guy Benyei11169dd2012-12-18 14:30:41 +00005919void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5920 VisitArrayTypeLoc(TL);
5921}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5924 VisitArrayTypeLoc(TL);
5925}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005926
Guy Benyei11169dd2012-12-18 14:30:41 +00005927void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5928 VisitArrayTypeLoc(TL);
5929}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005930
Guy Benyei11169dd2012-12-18 14:30:41 +00005931void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5932 DependentSizedArrayTypeLoc TL) {
5933 VisitArrayTypeLoc(TL);
5934}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005935
Guy Benyei11169dd2012-12-18 14:30:41 +00005936void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5937 DependentSizedExtVectorTypeLoc TL) {
5938 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5939}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005940
Guy Benyei11169dd2012-12-18 14:30:41 +00005941void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5942 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5943}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005944
Guy Benyei11169dd2012-12-18 14:30:41 +00005945void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5946 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5947}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005948
Guy Benyei11169dd2012-12-18 14:30:41 +00005949void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5950 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5951 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5952 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5953 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005954 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5955 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 }
5957}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005958
Guy Benyei11169dd2012-12-18 14:30:41 +00005959void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5960 VisitFunctionTypeLoc(TL);
5961}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005962
Guy Benyei11169dd2012-12-18 14:30:41 +00005963void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5964 VisitFunctionTypeLoc(TL);
5965}
5966void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5967 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5968}
5969void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5970 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5971}
5972void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5973 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5974 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5975 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5976}
5977void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5978 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5979 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5980 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5981 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5982}
5983void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5984 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5985}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005986
Guy Benyei11169dd2012-12-18 14:30:41 +00005987void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5988 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5989 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5990 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5991 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5992}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005993
Guy Benyei11169dd2012-12-18 14:30:41 +00005994void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5995 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5999 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6000}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006001
Guy Benyei11169dd2012-12-18 14:30:41 +00006002void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6003 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6004}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006005
Guy Benyei11169dd2012-12-18 14:30:41 +00006006void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6007 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
6008 if (TL.hasAttrOperand()) {
6009 SourceRange range;
6010 range.setBegin(ReadSourceLocation(Record, Idx));
6011 range.setEnd(ReadSourceLocation(Record, Idx));
6012 TL.setAttrOperandParensRange(range);
6013 }
6014 if (TL.hasAttrExprOperand()) {
6015 if (Record[Idx++])
6016 TL.setAttrExprOperand(Reader.ReadExpr(F));
6017 else
Craig Toppera13603a2014-05-22 05:54:18 +00006018 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 } else if (TL.hasAttrEnumOperand())
6020 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
6021}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006022
Guy Benyei11169dd2012-12-18 14:30:41 +00006023void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6024 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6025}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006026
Guy Benyei11169dd2012-12-18 14:30:41 +00006027void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6028 SubstTemplateTypeParmTypeLoc TL) {
6029 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6030}
6031void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6032 SubstTemplateTypeParmPackTypeLoc TL) {
6033 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6034}
6035void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6036 TemplateSpecializationTypeLoc TL) {
6037 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6038 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6039 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6040 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6041 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6042 TL.setArgLocInfo(i,
6043 Reader.GetTemplateArgumentLocInfo(F,
6044 TL.getTypePtr()->getArg(i).getKind(),
6045 Record, Idx));
6046}
6047void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6048 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6049 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6050}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006051
Guy Benyei11169dd2012-12-18 14:30:41 +00006052void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6053 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6054 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6055}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6058 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6059}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006060
Guy Benyei11169dd2012-12-18 14:30:41 +00006061void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6062 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6063 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6064 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6065}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006066
Guy Benyei11169dd2012-12-18 14:30:41 +00006067void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6068 DependentTemplateSpecializationTypeLoc TL) {
6069 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6070 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6071 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6072 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6073 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6074 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6075 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6076 TL.setArgLocInfo(I,
6077 Reader.GetTemplateArgumentLocInfo(F,
6078 TL.getTypePtr()->getArg(I).getKind(),
6079 Record, Idx));
6080}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6083 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
6084}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6087 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6088}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006089
Manman Rene6be26c2016-09-13 17:25:08 +00006090void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6091 if (TL.getNumProtocols()) {
6092 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6093 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
6094 }
6095 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6096 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6097}
6098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6100 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006101 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
6102 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
6103 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6104 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
6105 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6106 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6108 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6109}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006110
Guy Benyei11169dd2012-12-18 14:30:41 +00006111void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6112 TL.setStarLoc(ReadSourceLocation(Record, Idx));
6113}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006114
Guy Benyei11169dd2012-12-18 14:30:41 +00006115void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6116 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6117 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6118 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6119}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006120
Xiuli Pan9c14e282016-01-09 12:53:17 +00006121void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6122 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6123}
Guy Benyei11169dd2012-12-18 14:30:41 +00006124
6125TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
6126 const RecordData &Record,
6127 unsigned &Idx) {
6128 QualType InfoTy = readType(F, Record, Idx);
6129 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006130 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006131
6132 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6133 TypeLocReader TLR(*this, F, Record, Idx);
6134 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6135 TLR.Visit(TL);
6136 return TInfo;
6137}
6138
6139QualType ASTReader::GetType(TypeID ID) {
6140 unsigned FastQuals = ID & Qualifiers::FastMask;
6141 unsigned Index = ID >> Qualifiers::FastWidth;
6142
6143 if (Index < NUM_PREDEF_TYPE_IDS) {
6144 QualType T;
6145 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006146 case PREDEF_TYPE_NULL_ID:
6147 return QualType();
6148 case PREDEF_TYPE_VOID_ID:
6149 T = Context.VoidTy;
6150 break;
6151 case PREDEF_TYPE_BOOL_ID:
6152 T = Context.BoolTy;
6153 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006154
6155 case PREDEF_TYPE_CHAR_U_ID:
6156 case PREDEF_TYPE_CHAR_S_ID:
6157 // FIXME: Check that the signedness of CharTy is correct!
6158 T = Context.CharTy;
6159 break;
6160
Alexey Baderbdf7c842015-09-15 12:18:29 +00006161 case PREDEF_TYPE_UCHAR_ID:
6162 T = Context.UnsignedCharTy;
6163 break;
6164 case PREDEF_TYPE_USHORT_ID:
6165 T = Context.UnsignedShortTy;
6166 break;
6167 case PREDEF_TYPE_UINT_ID:
6168 T = Context.UnsignedIntTy;
6169 break;
6170 case PREDEF_TYPE_ULONG_ID:
6171 T = Context.UnsignedLongTy;
6172 break;
6173 case PREDEF_TYPE_ULONGLONG_ID:
6174 T = Context.UnsignedLongLongTy;
6175 break;
6176 case PREDEF_TYPE_UINT128_ID:
6177 T = Context.UnsignedInt128Ty;
6178 break;
6179 case PREDEF_TYPE_SCHAR_ID:
6180 T = Context.SignedCharTy;
6181 break;
6182 case PREDEF_TYPE_WCHAR_ID:
6183 T = Context.WCharTy;
6184 break;
6185 case PREDEF_TYPE_SHORT_ID:
6186 T = Context.ShortTy;
6187 break;
6188 case PREDEF_TYPE_INT_ID:
6189 T = Context.IntTy;
6190 break;
6191 case PREDEF_TYPE_LONG_ID:
6192 T = Context.LongTy;
6193 break;
6194 case PREDEF_TYPE_LONGLONG_ID:
6195 T = Context.LongLongTy;
6196 break;
6197 case PREDEF_TYPE_INT128_ID:
6198 T = Context.Int128Ty;
6199 break;
6200 case PREDEF_TYPE_HALF_ID:
6201 T = Context.HalfTy;
6202 break;
6203 case PREDEF_TYPE_FLOAT_ID:
6204 T = Context.FloatTy;
6205 break;
6206 case PREDEF_TYPE_DOUBLE_ID:
6207 T = Context.DoubleTy;
6208 break;
6209 case PREDEF_TYPE_LONGDOUBLE_ID:
6210 T = Context.LongDoubleTy;
6211 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006212 case PREDEF_TYPE_FLOAT128_ID:
6213 T = Context.Float128Ty;
6214 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006215 case PREDEF_TYPE_OVERLOAD_ID:
6216 T = Context.OverloadTy;
6217 break;
6218 case PREDEF_TYPE_BOUND_MEMBER:
6219 T = Context.BoundMemberTy;
6220 break;
6221 case PREDEF_TYPE_PSEUDO_OBJECT:
6222 T = Context.PseudoObjectTy;
6223 break;
6224 case PREDEF_TYPE_DEPENDENT_ID:
6225 T = Context.DependentTy;
6226 break;
6227 case PREDEF_TYPE_UNKNOWN_ANY:
6228 T = Context.UnknownAnyTy;
6229 break;
6230 case PREDEF_TYPE_NULLPTR_ID:
6231 T = Context.NullPtrTy;
6232 break;
6233 case PREDEF_TYPE_CHAR16_ID:
6234 T = Context.Char16Ty;
6235 break;
6236 case PREDEF_TYPE_CHAR32_ID:
6237 T = Context.Char32Ty;
6238 break;
6239 case PREDEF_TYPE_OBJC_ID:
6240 T = Context.ObjCBuiltinIdTy;
6241 break;
6242 case PREDEF_TYPE_OBJC_CLASS:
6243 T = Context.ObjCBuiltinClassTy;
6244 break;
6245 case PREDEF_TYPE_OBJC_SEL:
6246 T = Context.ObjCBuiltinSelTy;
6247 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006248#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6249 case PREDEF_TYPE_##Id##_ID: \
6250 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006251 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006252#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006253 case PREDEF_TYPE_SAMPLER_ID:
6254 T = Context.OCLSamplerTy;
6255 break;
6256 case PREDEF_TYPE_EVENT_ID:
6257 T = Context.OCLEventTy;
6258 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006259 case PREDEF_TYPE_CLK_EVENT_ID:
6260 T = Context.OCLClkEventTy;
6261 break;
6262 case PREDEF_TYPE_QUEUE_ID:
6263 T = Context.OCLQueueTy;
6264 break;
6265 case PREDEF_TYPE_NDRANGE_ID:
6266 T = Context.OCLNDRangeTy;
6267 break;
6268 case PREDEF_TYPE_RESERVE_ID_ID:
6269 T = Context.OCLReserveIDTy;
6270 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006271 case PREDEF_TYPE_AUTO_DEDUCT:
6272 T = Context.getAutoDeductType();
6273 break;
6274
6275 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6276 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 break;
6278
6279 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6280 T = Context.ARCUnbridgedCastTy;
6281 break;
6282
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 case PREDEF_TYPE_BUILTIN_FN:
6284 T = Context.BuiltinFnTy;
6285 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006286
6287 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6288 T = Context.OMPArraySectionTy;
6289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 }
6291
6292 assert(!T.isNull() && "Unknown predefined type");
6293 return T.withFastQualifiers(FastQuals);
6294 }
6295
6296 Index -= NUM_PREDEF_TYPE_IDS;
6297 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6298 if (TypesLoaded[Index].isNull()) {
6299 TypesLoaded[Index] = readTypeRecord(Index);
6300 if (TypesLoaded[Index].isNull())
6301 return QualType();
6302
6303 TypesLoaded[Index]->setFromAST();
6304 if (DeserializationListener)
6305 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6306 TypesLoaded[Index]);
6307 }
6308
6309 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6310}
6311
6312QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6313 return GetType(getGlobalTypeID(F, LocalID));
6314}
6315
6316serialization::TypeID
6317ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6318 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6319 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6320
6321 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6322 return LocalID;
6323
6324 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6325 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6326 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6327
6328 unsigned GlobalIndex = LocalIndex + I->second;
6329 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6330}
6331
6332TemplateArgumentLocInfo
6333ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6334 TemplateArgument::ArgKind Kind,
6335 const RecordData &Record,
6336 unsigned &Index) {
6337 switch (Kind) {
6338 case TemplateArgument::Expression:
6339 return ReadExpr(F);
6340 case TemplateArgument::Type:
6341 return GetTypeSourceInfo(F, Record, Index);
6342 case TemplateArgument::Template: {
6343 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6344 Index);
6345 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6346 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6347 SourceLocation());
6348 }
6349 case TemplateArgument::TemplateExpansion: {
6350 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6351 Index);
6352 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6353 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6354 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6355 EllipsisLoc);
6356 }
6357 case TemplateArgument::Null:
6358 case TemplateArgument::Integral:
6359 case TemplateArgument::Declaration:
6360 case TemplateArgument::NullPtr:
6361 case TemplateArgument::Pack:
6362 // FIXME: Is this right?
6363 return TemplateArgumentLocInfo();
6364 }
6365 llvm_unreachable("unexpected template argument loc");
6366}
6367
6368TemplateArgumentLoc
6369ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6370 const RecordData &Record, unsigned &Index) {
6371 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6372
6373 if (Arg.getKind() == TemplateArgument::Expression) {
6374 if (Record[Index++]) // bool InfoHasSameExpr.
6375 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6376 }
6377 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6378 Record, Index));
6379}
6380
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006381const ASTTemplateArgumentListInfo*
6382ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6383 const RecordData &Record,
6384 unsigned &Index) {
6385 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6386 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6387 unsigned NumArgsAsWritten = Record[Index++];
6388 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6389 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6390 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6391 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6392}
6393
Guy Benyei11169dd2012-12-18 14:30:41 +00006394Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6395 return GetDecl(ID);
6396}
6397
Richard Smith50895422015-01-31 03:04:55 +00006398template<typename TemplateSpecializationDecl>
6399static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6400 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6401 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6402}
6403
Richard Smith053f6c62014-05-16 23:01:30 +00006404void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006405 if (NumCurrentElementsDeserializing) {
6406 // We arrange to not care about the complete redeclaration chain while we're
6407 // deserializing. Just remember that the AST has marked this one as complete
6408 // but that it's not actually complete yet, so we know we still need to
6409 // complete it later.
6410 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6411 return;
6412 }
6413
Richard Smith053f6c62014-05-16 23:01:30 +00006414 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6415
Richard Smith053f6c62014-05-16 23:01:30 +00006416 // If this is a named declaration, complete it by looking it up
6417 // within its context.
6418 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006419 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006420 // all mergeable entities within it.
6421 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6422 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6423 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006424 if (!getContext().getLangOpts().CPlusPlus &&
6425 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006426 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006427 // the identifier instead. (For C++ modules, we don't store decls
6428 // in the serialized identifier table, so we do the lookup in the TU.)
6429 auto *II = Name.getAsIdentifierInfo();
6430 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006431 if (II->isOutOfDate())
6432 updateOutOfDateIdentifier(*II);
6433 } else
6434 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006435 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006436 // Find all declarations of this kind from the relevant context.
6437 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6438 auto *DC = cast<DeclContext>(DCDecl);
6439 SmallVector<Decl*, 8> Decls;
6440 FindExternalLexicalDecls(
6441 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6442 }
Richard Smith053f6c62014-05-16 23:01:30 +00006443 }
6444 }
Richard Smith50895422015-01-31 03:04:55 +00006445
6446 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6447 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6448 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6449 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6450 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6451 if (auto *Template = FD->getPrimaryTemplate())
6452 Template->LoadLazySpecializations();
6453 }
Richard Smith053f6c62014-05-16 23:01:30 +00006454}
6455
Richard Smithc2bb8182015-03-24 06:36:48 +00006456CXXCtorInitializer **
6457ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6458 RecordLocation Loc = getLocalBitOffset(Offset);
6459 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6460 SavedStreamPosition SavedPosition(Cursor);
6461 Cursor.JumpToBit(Loc.Offset);
6462 ReadingKindTracker ReadingKind(Read_Decl, *this);
6463
6464 RecordData Record;
6465 unsigned Code = Cursor.ReadCode();
6466 unsigned RecCode = Cursor.readRecord(Code, Record);
6467 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6468 Error("malformed AST file: missing C++ ctor initializers");
6469 return nullptr;
6470 }
6471
6472 unsigned Idx = 0;
6473 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6474}
6475
Guy Benyei11169dd2012-12-18 14:30:41 +00006476CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6477 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006478 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 SavedStreamPosition SavedPosition(Cursor);
6480 Cursor.JumpToBit(Loc.Offset);
6481 ReadingKindTracker ReadingKind(Read_Decl, *this);
6482 RecordData Record;
6483 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006484 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006486 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006487 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 }
6489
6490 unsigned Idx = 0;
6491 unsigned NumBases = Record[Idx++];
6492 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6493 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6494 for (unsigned I = 0; I != NumBases; ++I)
6495 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6496 return Bases;
6497}
6498
6499serialization::DeclID
6500ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6501 if (LocalID < NUM_PREDEF_DECL_IDS)
6502 return LocalID;
6503
6504 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6505 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6506 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6507
6508 return LocalID + I->second;
6509}
6510
6511bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6512 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006513 // Predefined decls aren't from any module.
6514 if (ID < NUM_PREDEF_DECL_IDS)
6515 return false;
6516
Richard Smithbcda1a92015-07-12 23:51:20 +00006517 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6518 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006519}
6520
Douglas Gregor9f782892013-01-21 15:25:38 +00006521ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006523 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6525 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6526 return I->second;
6527}
6528
6529SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6530 if (ID < NUM_PREDEF_DECL_IDS)
6531 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006532
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6534
6535 if (Index > DeclsLoaded.size()) {
6536 Error("declaration ID out-of-range for AST file");
6537 return SourceLocation();
6538 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006539
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 if (Decl *D = DeclsLoaded[Index])
6541 return D->getLocation();
6542
Richard Smithcb34bd32016-03-27 07:28:06 +00006543 SourceLocation Loc;
6544 DeclCursorForID(ID, Loc);
6545 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006546}
6547
Richard Smithfe620d22015-03-05 23:24:12 +00006548static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6549 switch (ID) {
6550 case PREDEF_DECL_NULL_ID:
6551 return nullptr;
6552
6553 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6554 return Context.getTranslationUnitDecl();
6555
6556 case PREDEF_DECL_OBJC_ID_ID:
6557 return Context.getObjCIdDecl();
6558
6559 case PREDEF_DECL_OBJC_SEL_ID:
6560 return Context.getObjCSelDecl();
6561
6562 case PREDEF_DECL_OBJC_CLASS_ID:
6563 return Context.getObjCClassDecl();
6564
6565 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6566 return Context.getObjCProtocolDecl();
6567
6568 case PREDEF_DECL_INT_128_ID:
6569 return Context.getInt128Decl();
6570
6571 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6572 return Context.getUInt128Decl();
6573
6574 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6575 return Context.getObjCInstanceTypeDecl();
6576
6577 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6578 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006579
Richard Smith9b88a4c2015-07-27 05:40:23 +00006580 case PREDEF_DECL_VA_LIST_TAG:
6581 return Context.getVaListTagDecl();
6582
Charles Davisc7d5c942015-09-17 20:55:33 +00006583 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6584 return Context.getBuiltinMSVaListDecl();
6585
Richard Smithf19e1272015-03-07 00:04:49 +00006586 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6587 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006588
6589 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6590 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006591
6592 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6593 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006594
6595 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6596 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006597
6598 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6599 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006600 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006601 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006602}
6603
Richard Smithcd45dbc2014-04-19 03:48:30 +00006604Decl *ASTReader::GetExistingDecl(DeclID ID) {
6605 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006606 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6607 if (D) {
6608 // Track that we have merged the declaration with ID \p ID into the
6609 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006610 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006611 if (Merged.empty())
6612 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 }
Richard Smithfe620d22015-03-05 23:24:12 +00006614 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6618
6619 if (Index >= DeclsLoaded.size()) {
6620 assert(0 && "declaration ID out-of-range for AST file");
6621 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006622 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006624
6625 return DeclsLoaded[Index];
6626}
6627
6628Decl *ASTReader::GetDecl(DeclID ID) {
6629 if (ID < NUM_PREDEF_DECL_IDS)
6630 return GetExistingDecl(ID);
6631
6632 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6633
6634 if (Index >= DeclsLoaded.size()) {
6635 assert(0 && "declaration ID out-of-range for AST file");
6636 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006637 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006638 }
6639
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 if (!DeclsLoaded[Index]) {
6641 ReadDeclRecord(ID);
6642 if (DeserializationListener)
6643 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6644 }
6645
6646 return DeclsLoaded[Index];
6647}
6648
6649DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6650 DeclID GlobalID) {
6651 if (GlobalID < NUM_PREDEF_DECL_IDS)
6652 return GlobalID;
6653
6654 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6655 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6656 ModuleFile *Owner = I->second;
6657
6658 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6659 = M.GlobalToLocalDeclIDs.find(Owner);
6660 if (Pos == M.GlobalToLocalDeclIDs.end())
6661 return 0;
6662
6663 return GlobalID - Owner->BaseDeclID + Pos->second;
6664}
6665
6666serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6667 const RecordData &Record,
6668 unsigned &Idx) {
6669 if (Idx >= Record.size()) {
6670 Error("Corrupted AST file");
6671 return 0;
6672 }
6673
6674 return getGlobalDeclID(F, Record[Idx++]);
6675}
6676
6677/// \brief Resolve the offset of a statement into a statement.
6678///
6679/// This operation will read a new statement from the external
6680/// source each time it is called, and is meant to be used via a
6681/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6682Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6683 // Switch case IDs are per Decl.
6684 ClearSwitchCaseIDs();
6685
6686 // Offset here is a global offset across the entire chain.
6687 RecordLocation Loc = getLocalBitOffset(Offset);
6688 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6689 return ReadStmtFromStream(*Loc.F);
6690}
6691
Richard Smith3cb15722015-08-05 22:41:45 +00006692void ASTReader::FindExternalLexicalDecls(
6693 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6694 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006695 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6696
Richard Smith9ccdd932015-08-06 22:14:12 +00006697 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006698 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6699 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6700 auto K = (Decl::Kind)+LexicalDecls[I];
6701 if (!IsKindWeWant(K))
6702 continue;
6703
6704 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6705
6706 // Don't add predefined declarations to the lexical context more
6707 // than once.
6708 if (ID < NUM_PREDEF_DECL_IDS) {
6709 if (PredefsVisited[ID])
6710 continue;
6711
6712 PredefsVisited[ID] = true;
6713 }
6714
6715 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006716 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006717 if (!DC->isDeclInLexicalTraversal(D))
6718 Decls.push_back(D);
6719 }
6720 }
6721 };
6722
6723 if (isa<TranslationUnitDecl>(DC)) {
6724 for (auto Lexical : TULexicalDecls)
6725 Visit(Lexical.first, Lexical.second);
6726 } else {
6727 auto I = LexicalDecls.find(DC);
6728 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006729 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006730 }
6731
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006733}
6734
6735namespace {
6736
6737class DeclIDComp {
6738 ASTReader &Reader;
6739 ModuleFile &Mod;
6740
6741public:
6742 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6743
6744 bool operator()(LocalDeclID L, LocalDeclID R) const {
6745 SourceLocation LHS = getLocation(L);
6746 SourceLocation RHS = getLocation(R);
6747 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6748 }
6749
6750 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6751 SourceLocation RHS = getLocation(R);
6752 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6753 }
6754
6755 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6756 SourceLocation LHS = getLocation(L);
6757 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6758 }
6759
6760 SourceLocation getLocation(LocalDeclID ID) const {
6761 return Reader.getSourceManager().getFileLoc(
6762 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6763 }
6764};
6765
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006766} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006767
6768void ASTReader::FindFileRegionDecls(FileID File,
6769 unsigned Offset, unsigned Length,
6770 SmallVectorImpl<Decl *> &Decls) {
6771 SourceManager &SM = getSourceManager();
6772
6773 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6774 if (I == FileDeclIDs.end())
6775 return;
6776
6777 FileDeclsInfo &DInfo = I->second;
6778 if (DInfo.Decls.empty())
6779 return;
6780
6781 SourceLocation
6782 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6783 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6784
6785 DeclIDComp DIDComp(*this, *DInfo.Mod);
6786 ArrayRef<serialization::LocalDeclID>::iterator
6787 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6788 BeginLoc, DIDComp);
6789 if (BeginIt != DInfo.Decls.begin())
6790 --BeginIt;
6791
6792 // If we are pointing at a top-level decl inside an objc container, we need
6793 // to backtrack until we find it otherwise we will fail to report that the
6794 // region overlaps with an objc container.
6795 while (BeginIt != DInfo.Decls.begin() &&
6796 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6797 ->isTopLevelDeclInObjCContainer())
6798 --BeginIt;
6799
6800 ArrayRef<serialization::LocalDeclID>::iterator
6801 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6802 EndLoc, DIDComp);
6803 if (EndIt != DInfo.Decls.end())
6804 ++EndIt;
6805
6806 for (ArrayRef<serialization::LocalDeclID>::iterator
6807 DIt = BeginIt; DIt != EndIt; ++DIt)
6808 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6809}
6810
Richard Smith9ce12e32013-02-07 03:30:24 +00006811bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006812ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6813 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006814 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 "DeclContext has no visible decls in storage");
6816 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006817 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006818
Richard Smithd88a7f12015-09-01 20:35:42 +00006819 auto It = Lookups.find(DC);
6820 if (It == Lookups.end())
6821 return false;
6822
Richard Smith8c913ec2014-08-14 02:21:01 +00006823 Deserializing LookupResults(this);
6824
Richard Smithd88a7f12015-09-01 20:35:42 +00006825 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006827 for (DeclID ID : It->second.Table.find(Name)) {
6828 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6829 if (ND->getDeclName() == Name)
6830 Decls.push_back(ND);
6831 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006832
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 ++NumVisibleDeclContextsRead;
6834 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006835 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006836}
6837
Guy Benyei11169dd2012-12-18 14:30:41 +00006838void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6839 if (!DC->hasExternalVisibleStorage())
6840 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006841
6842 auto It = Lookups.find(DC);
6843 assert(It != Lookups.end() &&
6844 "have external visible storage but no lookup tables");
6845
Craig Topper79be4cd2013-07-05 04:33:53 +00006846 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006847
Richard Smithd88a7f12015-09-01 20:35:42 +00006848 for (DeclID ID : It->second.Table.findAll()) {
6849 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6850 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 }
6852
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 ++NumVisibleDeclContextsRead;
6854
Craig Topper79be4cd2013-07-05 04:33:53 +00006855 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6857 }
6858 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6859}
6860
Richard Smithd88a7f12015-09-01 20:35:42 +00006861const serialization::reader::DeclContextLookupTable *
6862ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6863 auto I = Lookups.find(Primary);
6864 return I == Lookups.end() ? nullptr : &I->second;
6865}
6866
Guy Benyei11169dd2012-12-18 14:30:41 +00006867/// \brief Under non-PCH compilation the consumer receives the objc methods
6868/// before receiving the implementation, and codegen depends on this.
6869/// We simulate this by deserializing and passing to consumer the methods of the
6870/// implementation before passing the deserialized implementation decl.
6871static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6872 ASTConsumer *Consumer) {
6873 assert(ImplD && Consumer);
6874
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006875 for (auto *I : ImplD->methods())
6876 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006877
6878 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6879}
6880
6881void ASTReader::PassInterestingDeclsToConsumer() {
6882 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006883
6884 if (PassingDeclsToConsumer)
6885 return;
6886
6887 // Guard variable to avoid recursively redoing the process of passing
6888 // decls to consumer.
6889 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6890 true);
6891
Richard Smith9e2341d2015-03-23 03:25:59 +00006892 // Ensure that we've loaded all potentially-interesting declarations
6893 // that need to be eagerly loaded.
6894 for (auto ID : EagerlyDeserializedDecls)
6895 GetDecl(ID);
6896 EagerlyDeserializedDecls.clear();
6897
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 while (!InterestingDecls.empty()) {
6899 Decl *D = InterestingDecls.front();
6900 InterestingDecls.pop_front();
6901
6902 PassInterestingDeclToConsumer(D);
6903 }
6904}
6905
6906void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6907 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6908 PassObjCImplDeclToConsumer(ImplD, Consumer);
6909 else
6910 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6911}
6912
6913void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6914 this->Consumer = Consumer;
6915
Richard Smith9e2341d2015-03-23 03:25:59 +00006916 if (Consumer)
6917 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006918
6919 if (DeserializationListener)
6920 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006921}
6922
6923void ASTReader::PrintStats() {
6924 std::fprintf(stderr, "*** AST File Statistics:\n");
6925
6926 unsigned NumTypesLoaded
6927 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6928 QualType());
6929 unsigned NumDeclsLoaded
6930 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006931 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 unsigned NumIdentifiersLoaded
6933 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6934 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006935 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 unsigned NumMacrosLoaded
6937 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6938 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006939 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 unsigned NumSelectorsLoaded
6941 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6942 SelectorsLoaded.end(),
6943 Selector());
6944
6945 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6946 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6947 NumSLocEntriesRead, TotalNumSLocEntries,
6948 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6949 if (!TypesLoaded.empty())
6950 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6951 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6952 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6953 if (!DeclsLoaded.empty())
6954 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6955 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6956 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6957 if (!IdentifiersLoaded.empty())
6958 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6959 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6960 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6961 if (!MacrosLoaded.empty())
6962 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6963 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6964 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6965 if (!SelectorsLoaded.empty())
6966 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6967 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6968 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6969 if (TotalNumStatements)
6970 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6971 NumStatementsRead, TotalNumStatements,
6972 ((float)NumStatementsRead/TotalNumStatements * 100));
6973 if (TotalNumMacros)
6974 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6975 NumMacrosRead, TotalNumMacros,
6976 ((float)NumMacrosRead/TotalNumMacros * 100));
6977 if (TotalLexicalDeclContexts)
6978 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6979 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6980 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6981 * 100));
6982 if (TotalVisibleDeclContexts)
6983 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6984 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6985 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6986 * 100));
6987 if (TotalNumMethodPoolEntries) {
6988 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6989 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6990 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6991 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006993 if (NumMethodPoolLookups) {
6994 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6995 NumMethodPoolHits, NumMethodPoolLookups,
6996 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6997 }
6998 if (NumMethodPoolTableLookups) {
6999 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7000 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7001 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7002 * 100.0));
7003 }
7004
Douglas Gregor00a50f72013-01-25 00:38:33 +00007005 if (NumIdentifierLookupHits) {
7006 std::fprintf(stderr,
7007 " %u / %u identifier table lookups succeeded (%f%%)\n",
7008 NumIdentifierLookupHits, NumIdentifierLookups,
7009 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7010 }
7011
Douglas Gregore060e572013-01-25 01:03:03 +00007012 if (GlobalIndex) {
7013 std::fprintf(stderr, "\n");
7014 GlobalIndex->printStats();
7015 }
7016
Guy Benyei11169dd2012-12-18 14:30:41 +00007017 std::fprintf(stderr, "\n");
7018 dump();
7019 std::fprintf(stderr, "\n");
7020}
7021
7022template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7023static void
7024dumpModuleIDMap(StringRef Name,
7025 const ContinuousRangeMap<Key, ModuleFile *,
7026 InitialCapacity> &Map) {
7027 if (Map.begin() == Map.end())
7028 return;
7029
7030 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7031 llvm::errs() << Name << ":\n";
7032 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7033 I != IEnd; ++I) {
7034 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7035 << "\n";
7036 }
7037}
7038
Yaron Kerencdae9412016-01-29 19:38:18 +00007039LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7041 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7042 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7043 dumpModuleIDMap("Global type map", GlobalTypeMap);
7044 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7045 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7046 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7047 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7048 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7049 dumpModuleIDMap("Global preprocessed entity map",
7050 GlobalPreprocessedEntityMap);
7051
7052 llvm::errs() << "\n*** PCH/Modules Loaded:";
7053 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
7054 MEnd = ModuleMgr.end();
7055 M != MEnd; ++M)
7056 (*M)->dump();
7057}
7058
7059/// Return the amount of memory used by memory buffers, breaking down
7060/// by heap-backed versus mmap'ed memory.
7061void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7062 for (ModuleConstIterator I = ModuleMgr.begin(),
7063 E = ModuleMgr.end(); I != E; ++I) {
7064 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7065 size_t bytes = buf->getBufferSize();
7066 switch (buf->getBufferKind()) {
7067 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7068 sizes.malloc_bytes += bytes;
7069 break;
7070 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7071 sizes.mmap_bytes += bytes;
7072 break;
7073 }
7074 }
7075 }
7076}
7077
7078void ASTReader::InitializeSema(Sema &S) {
7079 SemaObj = &S;
7080 S.addExternalSource(this);
7081
7082 // Makes sure any declarations that were deserialized "too early"
7083 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007084 for (uint64_t ID : PreloadedDeclIDs) {
7085 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7086 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007088 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007089
Richard Smith3d8e97e2013-10-18 06:54:39 +00007090 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 if (!FPPragmaOptions.empty()) {
7092 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7093 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7094 }
7095
Richard Smith3d8e97e2013-10-18 06:54:39 +00007096 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 if (!OpenCLExtensions.empty()) {
7098 unsigned I = 0;
7099#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7100#include "clang/Basic/OpenCLExtensions.def"
7101
7102 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7103 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007104
7105 UpdateSema();
7106}
7107
7108void ASTReader::UpdateSema() {
7109 assert(SemaObj && "no Sema to update");
7110
7111 // Load the offsets of the declarations that Sema references.
7112 // They will be lazily deserialized when needed.
7113 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007114 assert(SemaDeclRefs.size() % 3 == 0);
7115 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007116 if (!SemaObj->StdNamespace)
7117 SemaObj->StdNamespace = SemaDeclRefs[I];
7118 if (!SemaObj->StdBadAlloc)
7119 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007120 if (!SemaObj->StdAlignValT)
7121 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007122 }
7123 SemaDeclRefs.clear();
7124 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007125
Nico Weber779355f2016-03-02 23:22:00 +00007126 // Update the state of pragmas. Use the same API as if we had encountered the
7127 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007128 if(OptimizeOffPragmaLocation.isValid())
7129 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007130 if (PragmaMSStructState != -1)
7131 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007132 if (PointersToMembersPragmaLocation.isValid()) {
7133 SemaObj->ActOnPragmaMSPointersToMembers(
7134 (LangOptions::PragmaMSPointersToMembersKind)
7135 PragmaMSPointersToMembersState,
7136 PointersToMembersPragmaLocation);
7137 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007138 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007139}
7140
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007141IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 // Note that we are loading an identifier.
7143 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007144
Douglas Gregor7211ac12013-01-25 23:32:03 +00007145 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007146 NumIdentifierLookups,
7147 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007148
7149 // We don't need to do identifier table lookups in C++ modules (we preload
7150 // all interesting declarations, and don't need to use the scope for name
7151 // lookups). Perform the lookup in PCH files, though, since we don't build
7152 // a complete initial identifier table if we're carrying on from a PCH.
7153 if (Context.getLangOpts().CPlusPlus) {
7154 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007155 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007156 break;
7157 } else {
7158 // If there is a global index, look there first to determine which modules
7159 // provably do not have any results for this identifier.
7160 GlobalModuleIndex::HitSet Hits;
7161 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7162 if (!loadGlobalIndex()) {
7163 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7164 HitsPtr = &Hits;
7165 }
7166 }
7167
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007168 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007169 }
7170
Guy Benyei11169dd2012-12-18 14:30:41 +00007171 IdentifierInfo *II = Visitor.getIdentifierInfo();
7172 markIdentifierUpToDate(II);
7173 return II;
7174}
7175
7176namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007177
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 /// \brief An identifier-lookup iterator that enumerates all of the
7179 /// identifiers stored within a set of AST files.
7180 class ASTIdentifierIterator : public IdentifierIterator {
7181 /// \brief The AST reader whose identifiers are being enumerated.
7182 const ASTReader &Reader;
7183
7184 /// \brief The current index into the chain of AST files stored in
7185 /// the AST reader.
7186 unsigned Index;
7187
7188 /// \brief The current position within the identifier lookup table
7189 /// of the current AST file.
7190 ASTIdentifierLookupTable::key_iterator Current;
7191
7192 /// \brief The end position within the identifier lookup table of
7193 /// the current AST file.
7194 ASTIdentifierLookupTable::key_iterator End;
7195
Ben Langmuir537c5b52016-05-04 00:53:13 +00007196 /// \brief Whether to skip any modules in the ASTReader.
7197 bool SkipModules;
7198
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007200 explicit ASTIdentifierIterator(const ASTReader &Reader,
7201 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007202
Craig Topper3e89dfe2014-03-13 02:13:41 +00007203 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007205
7206} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007207
Ben Langmuir537c5b52016-05-04 00:53:13 +00007208ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7209 bool SkipModules)
7210 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007211}
7212
7213StringRef ASTIdentifierIterator::Next() {
7214 while (Current == End) {
7215 // If we have exhausted all of our AST files, we're done.
7216 if (Index == 0)
7217 return StringRef();
7218
7219 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007220 ModuleFile &F = Reader.ModuleMgr[Index];
7221 if (SkipModules && F.isModule())
7222 continue;
7223
7224 ASTIdentifierLookupTable *IdTable =
7225 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 Current = IdTable->key_begin();
7227 End = IdTable->key_end();
7228 }
7229
7230 // We have any identifiers remaining in the current AST file; return
7231 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007232 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007234 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007235}
7236
Ben Langmuir537c5b52016-05-04 00:53:13 +00007237namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007238
Ben Langmuir537c5b52016-05-04 00:53:13 +00007239/// A utility for appending two IdentifierIterators.
7240class ChainedIdentifierIterator : public IdentifierIterator {
7241 std::unique_ptr<IdentifierIterator> Current;
7242 std::unique_ptr<IdentifierIterator> Queued;
7243
7244public:
7245 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7246 std::unique_ptr<IdentifierIterator> Second)
7247 : Current(std::move(First)), Queued(std::move(Second)) {}
7248
7249 StringRef Next() override {
7250 if (!Current)
7251 return StringRef();
7252
7253 StringRef result = Current->Next();
7254 if (!result.empty())
7255 return result;
7256
7257 // Try the queued iterator, which may itself be empty.
7258 Current.reset();
7259 std::swap(Current, Queued);
7260 return Next();
7261 }
7262};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007263
Ben Langmuir537c5b52016-05-04 00:53:13 +00007264} // end anonymous namespace.
7265
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007266IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007267 if (!loadGlobalIndex()) {
7268 std::unique_ptr<IdentifierIterator> ReaderIter(
7269 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7270 std::unique_ptr<IdentifierIterator> ModulesIter(
7271 GlobalIndex->createIdentifierIterator());
7272 return new ChainedIdentifierIterator(std::move(ReaderIter),
7273 std::move(ModulesIter));
7274 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 return new ASTIdentifierIterator(*this);
7277}
7278
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007279namespace clang {
7280namespace serialization {
7281
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 class ReadMethodPoolVisitor {
7283 ASTReader &Reader;
7284 Selector Sel;
7285 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007286 unsigned InstanceBits;
7287 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007288 bool InstanceHasMoreThanOneDecl;
7289 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007290 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7291 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007292
7293 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007294 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007296 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007297 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7298 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007299
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007300 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 if (!M.SelectorLookupTable)
7302 return false;
7303
7304 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007305 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 return true;
7307
Richard Smithbdf2d932015-07-30 03:37:16 +00007308 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 ASTSelectorLookupTable *PoolTable
7310 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007311 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 if (Pos == PoolTable->end())
7313 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007314
Richard Smithbdf2d932015-07-30 03:37:16 +00007315 ++Reader.NumMethodPoolTableHits;
7316 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007317 // FIXME: Not quite happy with the statistics here. We probably should
7318 // disable this tracking when called via LoadSelector.
7319 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007320 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007321 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007322 if (Reader.DeserializationListener)
7323 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007324
Richard Smithbdf2d932015-07-30 03:37:16 +00007325 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7326 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7327 InstanceBits = Data.InstanceBits;
7328 FactoryBits = Data.FactoryBits;
7329 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7330 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 return true;
7332 }
7333
7334 /// \brief Retrieve the instance methods found by this visitor.
7335 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7336 return InstanceMethods;
7337 }
7338
7339 /// \brief Retrieve the instance methods found by this visitor.
7340 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7341 return FactoryMethods;
7342 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007343
7344 unsigned getInstanceBits() const { return InstanceBits; }
7345 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007346 bool instanceHasMoreThanOneDecl() const {
7347 return InstanceHasMoreThanOneDecl;
7348 }
7349 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007351
7352} // end namespace serialization
7353} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007354
7355/// \brief Add the given set of methods to the method list.
7356static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7357 ObjCMethodList &List) {
7358 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7359 S.addMethodToGlobalList(&List, Methods[I]);
7360 }
7361}
7362
7363void ASTReader::ReadMethodPool(Selector Sel) {
7364 // Get the selector generation and update it to the current generation.
7365 unsigned &Generation = SelectorGeneration[Sel];
7366 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007367 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007368 SelectorOutOfDate[Sel] = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007369
7370 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007371 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007372 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007373 ModuleMgr.visit(Visitor);
7374
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007376 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007378
7379 ++NumMethodPoolHits;
7380
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 if (!getSema())
7382 return;
7383
7384 Sema &S = *getSema();
7385 Sema::GlobalMethodPool::iterator Pos
7386 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007387
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007388 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007389 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007390 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007391 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007392
7393 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7394 // when building a module we keep every method individually and may need to
7395 // update hasMoreThanOneDecl as we add the methods.
7396 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7397 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007398}
7399
Manman Rena0f31a02016-04-29 19:04:05 +00007400void ASTReader::updateOutOfDateSelector(Selector Sel) {
7401 if (SelectorOutOfDate[Sel])
7402 ReadMethodPool(Sel);
7403}
7404
Guy Benyei11169dd2012-12-18 14:30:41 +00007405void ASTReader::ReadKnownNamespaces(
7406 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7407 Namespaces.clear();
7408
7409 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7410 if (NamespaceDecl *Namespace
7411 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7412 Namespaces.push_back(Namespace);
7413 }
7414}
7415
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007416void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007417 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007418 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7419 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007420 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007421 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007422 Undefined.insert(std::make_pair(D, Loc));
7423 }
7424}
Nick Lewycky8334af82013-01-26 00:35:08 +00007425
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007426void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7427 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7428 Exprs) {
7429 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7430 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7431 uint64_t Count = DelayedDeleteExprs[Idx++];
7432 for (uint64_t C = 0; C < Count; ++C) {
7433 SourceLocation DeleteLoc =
7434 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7435 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7436 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7437 }
7438 }
7439}
7440
Guy Benyei11169dd2012-12-18 14:30:41 +00007441void ASTReader::ReadTentativeDefinitions(
7442 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7443 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7444 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7445 if (Var)
7446 TentativeDefs.push_back(Var);
7447 }
7448 TentativeDefinitions.clear();
7449}
7450
7451void ASTReader::ReadUnusedFileScopedDecls(
7452 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7453 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7454 DeclaratorDecl *D
7455 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7456 if (D)
7457 Decls.push_back(D);
7458 }
7459 UnusedFileScopedDecls.clear();
7460}
7461
7462void ASTReader::ReadDelegatingConstructors(
7463 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7464 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7465 CXXConstructorDecl *D
7466 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7467 if (D)
7468 Decls.push_back(D);
7469 }
7470 DelegatingCtorDecls.clear();
7471}
7472
7473void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7474 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7475 TypedefNameDecl *D
7476 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7477 if (D)
7478 Decls.push_back(D);
7479 }
7480 ExtVectorDecls.clear();
7481}
7482
Nico Weber72889432014-09-06 01:25:55 +00007483void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7484 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7485 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7486 ++I) {
7487 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7488 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7489 if (D)
7490 Decls.insert(D);
7491 }
7492 UnusedLocalTypedefNameCandidates.clear();
7493}
7494
Guy Benyei11169dd2012-12-18 14:30:41 +00007495void ASTReader::ReadReferencedSelectors(
7496 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7497 if (ReferencedSelectorsData.empty())
7498 return;
7499
7500 // If there are @selector references added them to its pool. This is for
7501 // implementation of -Wselector.
7502 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7503 unsigned I = 0;
7504 while (I < DataSize) {
7505 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7506 SourceLocation SelLoc
7507 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7508 Sels.push_back(std::make_pair(Sel, SelLoc));
7509 }
7510 ReferencedSelectorsData.clear();
7511}
7512
7513void ASTReader::ReadWeakUndeclaredIdentifiers(
7514 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7515 if (WeakUndeclaredIdentifiers.empty())
7516 return;
7517
7518 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7519 IdentifierInfo *WeakId
7520 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7521 IdentifierInfo *AliasId
7522 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7523 SourceLocation Loc
7524 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7525 bool Used = WeakUndeclaredIdentifiers[I++];
7526 WeakInfo WI(AliasId, Loc);
7527 WI.setUsed(Used);
7528 WeakIDs.push_back(std::make_pair(WeakId, WI));
7529 }
7530 WeakUndeclaredIdentifiers.clear();
7531}
7532
7533void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7534 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7535 ExternalVTableUse VT;
7536 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7537 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7538 VT.DefinitionRequired = VTableUses[Idx++];
7539 VTables.push_back(VT);
7540 }
7541
7542 VTableUses.clear();
7543}
7544
7545void ASTReader::ReadPendingInstantiations(
7546 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7547 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7548 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7549 SourceLocation Loc
7550 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7551
7552 Pending.push_back(std::make_pair(D, Loc));
7553 }
7554 PendingInstantiations.clear();
7555}
7556
Richard Smithe40f2ba2013-08-07 21:41:30 +00007557void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007558 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7559 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007560 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7561 /* In loop */) {
7562 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7563
Justin Lebar28f09c52016-10-10 16:26:08 +00007564 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007565 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7566
7567 ModuleFile *F = getOwningModuleFile(LT->D);
7568 assert(F && "No module");
7569
7570 unsigned TokN = LateParsedTemplates[Idx++];
7571 LT->Toks.reserve(TokN);
7572 for (unsigned T = 0; T < TokN; ++T)
7573 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7574
Justin Lebar28f09c52016-10-10 16:26:08 +00007575 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007576 }
7577
7578 LateParsedTemplates.clear();
7579}
7580
Guy Benyei11169dd2012-12-18 14:30:41 +00007581void ASTReader::LoadSelector(Selector Sel) {
7582 // It would be complicated to avoid reading the methods anyway. So don't.
7583 ReadMethodPool(Sel);
7584}
7585
7586void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7587 assert(ID && "Non-zero identifier ID required");
7588 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7589 IdentifiersLoaded[ID - 1] = II;
7590 if (DeserializationListener)
7591 DeserializationListener->IdentifierRead(ID, II);
7592}
7593
7594/// \brief Set the globally-visible declarations associated with the given
7595/// identifier.
7596///
7597/// If the AST reader is currently in a state where the given declaration IDs
7598/// cannot safely be resolved, they are queued until it is safe to resolve
7599/// them.
7600///
7601/// \param II an IdentifierInfo that refers to one or more globally-visible
7602/// declarations.
7603///
7604/// \param DeclIDs the set of declaration IDs with the name @p II that are
7605/// visible at global scope.
7606///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007607/// \param Decls if non-null, this vector will be populated with the set of
7608/// deserialized declarations. These declarations will not be pushed into
7609/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007610void
7611ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7612 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007613 SmallVectorImpl<Decl *> *Decls) {
7614 if (NumCurrentElementsDeserializing && !Decls) {
7615 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 return;
7617 }
7618
7619 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007620 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 // Queue this declaration so that it will be added to the
7622 // translation unit scope and identifier's declaration chain
7623 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007624 PreloadedDeclIDs.push_back(DeclIDs[I]);
7625 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007626 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007627
7628 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7629
7630 // If we're simply supposed to record the declarations, do so now.
7631 if (Decls) {
7632 Decls->push_back(D);
7633 continue;
7634 }
7635
7636 // Introduce this declaration into the translation-unit scope
7637 // and add it to the declaration chain for this identifier, so
7638 // that (unqualified) name lookup will find it.
7639 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007640 }
7641}
7642
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007643IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007645 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007646
7647 if (IdentifiersLoaded.empty()) {
7648 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007649 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 }
7651
7652 ID -= 1;
7653 if (!IdentifiersLoaded[ID]) {
7654 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7655 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7656 ModuleFile *M = I->second;
7657 unsigned Index = ID - M->BaseIdentifierID;
7658 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7659
7660 // All of the strings in the AST file are preceded by a 16-bit length.
7661 // Extract that 16-bit length to avoid having to execute strlen().
7662 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7663 // unsigned integers. This is important to avoid integer overflow when
7664 // we cast them to 'unsigned'.
7665 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7666 unsigned StrLen = (((unsigned) StrLenPtr[0])
7667 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007668 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7669 IdentifiersLoaded[ID] = &II;
7670 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007672 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 }
7674
7675 return IdentifiersLoaded[ID];
7676}
7677
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007678IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7679 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007680}
7681
7682IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7683 if (LocalID < NUM_PREDEF_IDENT_IDS)
7684 return LocalID;
7685
7686 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7687 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7688 assert(I != M.IdentifierRemap.end()
7689 && "Invalid index into identifier index remap");
7690
7691 return LocalID + I->second;
7692}
7693
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007694MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007695 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007696 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007697
7698 if (MacrosLoaded.empty()) {
7699 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007700 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 }
7702
7703 ID -= NUM_PREDEF_MACRO_IDS;
7704 if (!MacrosLoaded[ID]) {
7705 GlobalMacroMapType::iterator I
7706 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7707 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7708 ModuleFile *M = I->second;
7709 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007710 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7711
7712 if (DeserializationListener)
7713 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7714 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 }
7716
7717 return MacrosLoaded[ID];
7718}
7719
7720MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7721 if (LocalID < NUM_PREDEF_MACRO_IDS)
7722 return LocalID;
7723
7724 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7725 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7726 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7727
7728 return LocalID + I->second;
7729}
7730
7731serialization::SubmoduleID
7732ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7733 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7734 return LocalID;
7735
7736 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7737 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7738 assert(I != M.SubmoduleRemap.end()
7739 && "Invalid index into submodule index remap");
7740
7741 return LocalID + I->second;
7742}
7743
7744Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7745 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7746 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007747 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 }
7749
7750 if (GlobalID > SubmodulesLoaded.size()) {
7751 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007752 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 }
7754
7755 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7756}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007757
7758Module *ASTReader::getModule(unsigned ID) {
7759 return getSubmodule(ID);
7760}
7761
Richard Smithd88a7f12015-09-01 20:35:42 +00007762ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7763 if (ID & 1) {
7764 // It's a module, look it up by submodule ID.
7765 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7766 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7767 } else {
7768 // It's a prefix (preamble, PCH, ...). Look it up by index.
7769 unsigned IndexFromEnd = ID >> 1;
7770 assert(IndexFromEnd && "got reference to unknown module file");
7771 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7772 }
7773}
7774
7775unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7776 if (!F)
7777 return 1;
7778
7779 // For a file representing a module, use the submodule ID of the top-level
7780 // module as the file ID. For any other kind of file, the number of such
7781 // files loaded beforehand will be the same on reload.
7782 // FIXME: Is this true even if we have an explicit module file and a PCH?
7783 if (F->isModule())
7784 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7785
7786 auto PCHModules = getModuleManager().pch_modules();
7787 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7788 assert(I != PCHModules.end() && "emitting reference to unknown file");
7789 return (I - PCHModules.end()) << 1;
7790}
7791
Adrian Prantl15bcf702015-06-30 17:39:43 +00007792llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7793ASTReader::getSourceDescriptor(unsigned ID) {
7794 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007795 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007796
7797 // If there is only a single PCH, return it instead.
7798 // Chained PCH are not suported.
7799 if (ModuleMgr.size() == 1) {
7800 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007801 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007802 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7803 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7804 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007805 }
7806 return None;
7807}
7808
Guy Benyei11169dd2012-12-18 14:30:41 +00007809Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7810 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7811}
7812
7813Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7814 if (ID == 0)
7815 return Selector();
7816
7817 if (ID > SelectorsLoaded.size()) {
7818 Error("selector ID out of range in AST file");
7819 return Selector();
7820 }
7821
Craig Toppera13603a2014-05-22 05:54:18 +00007822 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007823 // Load this selector from the selector table.
7824 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7825 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7826 ModuleFile &M = *I->second;
7827 ASTSelectorLookupTrait Trait(*this, M);
7828 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7829 SelectorsLoaded[ID - 1] =
7830 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7831 if (DeserializationListener)
7832 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7833 }
7834
7835 return SelectorsLoaded[ID - 1];
7836}
7837
7838Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7839 return DecodeSelector(ID);
7840}
7841
7842uint32_t ASTReader::GetNumExternalSelectors() {
7843 // ID 0 (the null selector) is considered an external selector.
7844 return getTotalNumSelectors() + 1;
7845}
7846
7847serialization::SelectorID
7848ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7849 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7850 return LocalID;
7851
7852 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7853 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7854 assert(I != M.SelectorRemap.end()
7855 && "Invalid index into selector index remap");
7856
7857 return LocalID + I->second;
7858}
7859
7860DeclarationName
7861ASTReader::ReadDeclarationName(ModuleFile &F,
7862 const RecordData &Record, unsigned &Idx) {
7863 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7864 switch (Kind) {
7865 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007866 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007867
7868 case DeclarationName::ObjCZeroArgSelector:
7869 case DeclarationName::ObjCOneArgSelector:
7870 case DeclarationName::ObjCMultiArgSelector:
7871 return DeclarationName(ReadSelector(F, Record, Idx));
7872
7873 case DeclarationName::CXXConstructorName:
7874 return Context.DeclarationNames.getCXXConstructorName(
7875 Context.getCanonicalType(readType(F, Record, Idx)));
7876
7877 case DeclarationName::CXXDestructorName:
7878 return Context.DeclarationNames.getCXXDestructorName(
7879 Context.getCanonicalType(readType(F, Record, Idx)));
7880
7881 case DeclarationName::CXXConversionFunctionName:
7882 return Context.DeclarationNames.getCXXConversionFunctionName(
7883 Context.getCanonicalType(readType(F, Record, Idx)));
7884
7885 case DeclarationName::CXXOperatorName:
7886 return Context.DeclarationNames.getCXXOperatorName(
7887 (OverloadedOperatorKind)Record[Idx++]);
7888
7889 case DeclarationName::CXXLiteralOperatorName:
7890 return Context.DeclarationNames.getCXXLiteralOperatorName(
7891 GetIdentifierInfo(F, Record, Idx));
7892
7893 case DeclarationName::CXXUsingDirective:
7894 return DeclarationName::getUsingDirectiveName();
7895 }
7896
7897 llvm_unreachable("Invalid NameKind!");
7898}
7899
7900void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7901 DeclarationNameLoc &DNLoc,
7902 DeclarationName Name,
7903 const RecordData &Record, unsigned &Idx) {
7904 switch (Name.getNameKind()) {
7905 case DeclarationName::CXXConstructorName:
7906 case DeclarationName::CXXDestructorName:
7907 case DeclarationName::CXXConversionFunctionName:
7908 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7909 break;
7910
7911 case DeclarationName::CXXOperatorName:
7912 DNLoc.CXXOperatorName.BeginOpNameLoc
7913 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7914 DNLoc.CXXOperatorName.EndOpNameLoc
7915 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7916 break;
7917
7918 case DeclarationName::CXXLiteralOperatorName:
7919 DNLoc.CXXLiteralOperatorName.OpNameLoc
7920 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7921 break;
7922
7923 case DeclarationName::Identifier:
7924 case DeclarationName::ObjCZeroArgSelector:
7925 case DeclarationName::ObjCOneArgSelector:
7926 case DeclarationName::ObjCMultiArgSelector:
7927 case DeclarationName::CXXUsingDirective:
7928 break;
7929 }
7930}
7931
7932void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7933 DeclarationNameInfo &NameInfo,
7934 const RecordData &Record, unsigned &Idx) {
7935 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7936 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7937 DeclarationNameLoc DNLoc;
7938 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7939 NameInfo.setInfo(DNLoc);
7940}
7941
7942void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7943 const RecordData &Record, unsigned &Idx) {
7944 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7945 unsigned NumTPLists = Record[Idx++];
7946 Info.NumTemplParamLists = NumTPLists;
7947 if (NumTPLists) {
7948 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007949 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00007950 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7951 }
7952}
7953
7954TemplateName
7955ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7956 unsigned &Idx) {
7957 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7958 switch (Kind) {
7959 case TemplateName::Template:
7960 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7961
7962 case TemplateName::OverloadedTemplate: {
7963 unsigned size = Record[Idx++];
7964 UnresolvedSet<8> Decls;
7965 while (size--)
7966 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7967
7968 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7969 }
7970
7971 case TemplateName::QualifiedTemplate: {
7972 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7973 bool hasTemplKeyword = Record[Idx++];
7974 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7975 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7976 }
7977
7978 case TemplateName::DependentTemplate: {
7979 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7980 if (Record[Idx++]) // isIdentifier
7981 return Context.getDependentTemplateName(NNS,
7982 GetIdentifierInfo(F, Record,
7983 Idx));
7984 return Context.getDependentTemplateName(NNS,
7985 (OverloadedOperatorKind)Record[Idx++]);
7986 }
7987
7988 case TemplateName::SubstTemplateTemplateParm: {
7989 TemplateTemplateParmDecl *param
7990 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7991 if (!param) return TemplateName();
7992 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7993 return Context.getSubstTemplateTemplateParm(param, replacement);
7994 }
7995
7996 case TemplateName::SubstTemplateTemplateParmPack: {
7997 TemplateTemplateParmDecl *Param
7998 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7999 if (!Param)
8000 return TemplateName();
8001
8002 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8003 if (ArgPack.getKind() != TemplateArgument::Pack)
8004 return TemplateName();
8005
8006 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8007 }
8008 }
8009
8010 llvm_unreachable("Unhandled template name kind!");
8011}
8012
Richard Smith2bb3c342015-08-09 01:05:31 +00008013TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8014 const RecordData &Record,
8015 unsigned &Idx,
8016 bool Canonicalize) {
8017 if (Canonicalize) {
8018 // The caller wants a canonical template argument. Sometimes the AST only
8019 // wants template arguments in canonical form (particularly as the template
8020 // argument lists of template specializations) so ensure we preserve that
8021 // canonical form across serialization.
8022 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8023 return Context.getCanonicalTemplateArgument(Arg);
8024 }
8025
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8027 switch (Kind) {
8028 case TemplateArgument::Null:
8029 return TemplateArgument();
8030 case TemplateArgument::Type:
8031 return TemplateArgument(readType(F, Record, Idx));
8032 case TemplateArgument::Declaration: {
8033 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008034 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008035 }
8036 case TemplateArgument::NullPtr:
8037 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8038 case TemplateArgument::Integral: {
8039 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8040 QualType T = readType(F, Record, Idx);
8041 return TemplateArgument(Context, Value, T);
8042 }
8043 case TemplateArgument::Template:
8044 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8045 case TemplateArgument::TemplateExpansion: {
8046 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008047 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 if (unsigned NumExpansions = Record[Idx++])
8049 NumTemplateExpansions = NumExpansions - 1;
8050 return TemplateArgument(Name, NumTemplateExpansions);
8051 }
8052 case TemplateArgument::Expression:
8053 return TemplateArgument(ReadExpr(F));
8054 case TemplateArgument::Pack: {
8055 unsigned NumArgs = Record[Idx++];
8056 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8057 for (unsigned I = 0; I != NumArgs; ++I)
8058 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008059 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 }
8061 }
8062
8063 llvm_unreachable("Unhandled template argument kind!");
8064}
8065
8066TemplateParameterList *
8067ASTReader::ReadTemplateParameterList(ModuleFile &F,
8068 const RecordData &Record, unsigned &Idx) {
8069 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8070 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8071 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8072
8073 unsigned NumParams = Record[Idx++];
8074 SmallVector<NamedDecl *, 16> Params;
8075 Params.reserve(NumParams);
8076 while (NumParams--)
8077 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8078
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008079 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 TemplateParameterList* TemplateParams =
8081 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008082 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 return TemplateParams;
8084}
8085
8086void
8087ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008088ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008090 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 unsigned NumTemplateArgs = Record[Idx++];
8092 TemplArgs.reserve(NumTemplateArgs);
8093 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008094 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008095}
8096
8097/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008098void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 const RecordData &Record, unsigned &Idx) {
8100 unsigned NumDecls = Record[Idx++];
8101 Set.reserve(Context, NumDecls);
8102 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008103 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008105 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 }
8107}
8108
8109CXXBaseSpecifier
8110ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8111 const RecordData &Record, unsigned &Idx) {
8112 bool isVirtual = static_cast<bool>(Record[Idx++]);
8113 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8114 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8115 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8116 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8117 SourceRange Range = ReadSourceRange(F, Record, Idx);
8118 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8119 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8120 EllipsisLoc);
8121 Result.setInheritConstructors(inheritConstructors);
8122 return Result;
8123}
8124
Richard Smithc2bb8182015-03-24 06:36:48 +00008125CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008126ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8127 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008129 assert(NumInitializers && "wrote ctor initializers but have no inits");
8130 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8131 for (unsigned i = 0; i != NumInitializers; ++i) {
8132 TypeSourceInfo *TInfo = nullptr;
8133 bool IsBaseVirtual = false;
8134 FieldDecl *Member = nullptr;
8135 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008136
Richard Smithc2bb8182015-03-24 06:36:48 +00008137 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8138 switch (Type) {
8139 case CTOR_INITIALIZER_BASE:
8140 TInfo = GetTypeSourceInfo(F, Record, Idx);
8141 IsBaseVirtual = Record[Idx++];
8142 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008143
Richard Smithc2bb8182015-03-24 06:36:48 +00008144 case CTOR_INITIALIZER_DELEGATING:
8145 TInfo = GetTypeSourceInfo(F, Record, Idx);
8146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008147
Richard Smithc2bb8182015-03-24 06:36:48 +00008148 case CTOR_INITIALIZER_MEMBER:
8149 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008151
Richard Smithc2bb8182015-03-24 06:36:48 +00008152 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8153 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8154 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008156
8157 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8158 Expr *Init = ReadExpr(F);
8159 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8160 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8161 bool IsWritten = Record[Idx++];
8162 unsigned SourceOrderOrNumArrayIndices;
8163 SmallVector<VarDecl *, 8> Indices;
8164 if (IsWritten) {
8165 SourceOrderOrNumArrayIndices = Record[Idx++];
8166 } else {
8167 SourceOrderOrNumArrayIndices = Record[Idx++];
8168 Indices.reserve(SourceOrderOrNumArrayIndices);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008169 for (unsigned i = 0; i != SourceOrderOrNumArrayIndices; ++i)
Richard Smithc2bb8182015-03-24 06:36:48 +00008170 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8171 }
8172
8173 CXXCtorInitializer *BOMInit;
8174 if (Type == CTOR_INITIALIZER_BASE) {
8175 BOMInit = new (Context)
8176 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8177 RParenLoc, MemberOrEllipsisLoc);
8178 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8179 BOMInit = new (Context)
8180 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8181 } else if (IsWritten) {
8182 if (Member)
8183 BOMInit = new (Context) CXXCtorInitializer(
8184 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8185 else
8186 BOMInit = new (Context)
8187 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8188 LParenLoc, Init, RParenLoc);
8189 } else {
8190 if (IndirectMember) {
8191 assert(Indices.empty() && "Indirect field improperly initialized");
8192 BOMInit = new (Context)
8193 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8194 LParenLoc, Init, RParenLoc);
8195 } else {
8196 BOMInit = CXXCtorInitializer::Create(
8197 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8198 Indices.data(), Indices.size());
8199 }
8200 }
8201
8202 if (IsWritten)
8203 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8204 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 }
8206
Richard Smithc2bb8182015-03-24 06:36:48 +00008207 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008208}
8209
8210NestedNameSpecifier *
8211ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8212 const RecordData &Record, unsigned &Idx) {
8213 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008214 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008215 for (unsigned I = 0; I != N; ++I) {
8216 NestedNameSpecifier::SpecifierKind Kind
8217 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8218 switch (Kind) {
8219 case NestedNameSpecifier::Identifier: {
8220 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8221 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8222 break;
8223 }
8224
8225 case NestedNameSpecifier::Namespace: {
8226 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8227 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8228 break;
8229 }
8230
8231 case NestedNameSpecifier::NamespaceAlias: {
8232 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8233 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8234 break;
8235 }
8236
8237 case NestedNameSpecifier::TypeSpec:
8238 case NestedNameSpecifier::TypeSpecWithTemplate: {
8239 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8240 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008241 return nullptr;
8242
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 bool Template = Record[Idx++];
8244 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8245 break;
8246 }
8247
8248 case NestedNameSpecifier::Global: {
8249 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8250 // No associated value, and there can't be a prefix.
8251 break;
8252 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008253
8254 case NestedNameSpecifier::Super: {
8255 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8256 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8257 break;
8258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 }
8260 Prev = NNS;
8261 }
8262 return NNS;
8263}
8264
8265NestedNameSpecifierLoc
8266ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8267 unsigned &Idx) {
8268 unsigned N = Record[Idx++];
8269 NestedNameSpecifierLocBuilder Builder;
8270 for (unsigned I = 0; I != N; ++I) {
8271 NestedNameSpecifier::SpecifierKind Kind
8272 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8273 switch (Kind) {
8274 case NestedNameSpecifier::Identifier: {
8275 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8276 SourceRange Range = ReadSourceRange(F, Record, Idx);
8277 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8278 break;
8279 }
8280
8281 case NestedNameSpecifier::Namespace: {
8282 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8283 SourceRange Range = ReadSourceRange(F, Record, Idx);
8284 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8285 break;
8286 }
8287
8288 case NestedNameSpecifier::NamespaceAlias: {
8289 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8290 SourceRange Range = ReadSourceRange(F, Record, Idx);
8291 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8292 break;
8293 }
8294
8295 case NestedNameSpecifier::TypeSpec:
8296 case NestedNameSpecifier::TypeSpecWithTemplate: {
8297 bool Template = Record[Idx++];
8298 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8299 if (!T)
8300 return NestedNameSpecifierLoc();
8301 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8302
8303 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8304 Builder.Extend(Context,
8305 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8306 T->getTypeLoc(), ColonColonLoc);
8307 break;
8308 }
8309
8310 case NestedNameSpecifier::Global: {
8311 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8312 Builder.MakeGlobal(Context, ColonColonLoc);
8313 break;
8314 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008315
8316 case NestedNameSpecifier::Super: {
8317 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8318 SourceRange Range = ReadSourceRange(F, Record, Idx);
8319 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8320 break;
8321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 }
8323 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008324
Guy Benyei11169dd2012-12-18 14:30:41 +00008325 return Builder.getWithLocInContext(Context);
8326}
8327
8328SourceRange
8329ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8330 unsigned &Idx) {
8331 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8332 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8333 return SourceRange(beg, end);
8334}
8335
8336/// \brief Read an integral value
8337llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8338 unsigned BitWidth = Record[Idx++];
8339 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8340 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8341 Idx += NumWords;
8342 return Result;
8343}
8344
8345/// \brief Read a signed integral value
8346llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8347 bool isUnsigned = Record[Idx++];
8348 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8349}
8350
8351/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008352llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8353 const llvm::fltSemantics &Sem,
8354 unsigned &Idx) {
8355 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008356}
8357
8358// \brief Read a string
8359std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8360 unsigned Len = Record[Idx++];
8361 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8362 Idx += Len;
8363 return Result;
8364}
8365
Richard Smith7ed1bc92014-12-05 22:42:13 +00008366std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8367 unsigned &Idx) {
8368 std::string Filename = ReadString(Record, Idx);
8369 ResolveImportedPath(F, Filename);
8370 return Filename;
8371}
8372
Guy Benyei11169dd2012-12-18 14:30:41 +00008373VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8374 unsigned &Idx) {
8375 unsigned Major = Record[Idx++];
8376 unsigned Minor = Record[Idx++];
8377 unsigned Subminor = Record[Idx++];
8378 if (Minor == 0)
8379 return VersionTuple(Major);
8380 if (Subminor == 0)
8381 return VersionTuple(Major, Minor - 1);
8382 return VersionTuple(Major, Minor - 1, Subminor - 1);
8383}
8384
8385CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8386 const RecordData &Record,
8387 unsigned &Idx) {
8388 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8389 return CXXTemporary::Create(Context, Decl);
8390}
8391
8392DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008393 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008394}
8395
8396DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8397 return Diags.Report(Loc, DiagID);
8398}
8399
8400/// \brief Retrieve the identifier table associated with the
8401/// preprocessor.
8402IdentifierTable &ASTReader::getIdentifierTable() {
8403 return PP.getIdentifierTable();
8404}
8405
8406/// \brief Record that the given ID maps to the given switch-case
8407/// statement.
8408void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008409 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008410 "Already have a SwitchCase with this ID");
8411 (*CurrSwitchCaseStmts)[ID] = SC;
8412}
8413
8414/// \brief Retrieve the switch-case statement with the given ID.
8415SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008416 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 return (*CurrSwitchCaseStmts)[ID];
8418}
8419
8420void ASTReader::ClearSwitchCaseIDs() {
8421 CurrSwitchCaseStmts->clear();
8422}
8423
8424void ASTReader::ReadComments() {
8425 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008426 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 serialization::ModuleFile *> >::iterator
8428 I = CommentsCursors.begin(),
8429 E = CommentsCursors.end();
8430 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008431 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008432 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008433 serialization::ModuleFile &F = *I->second;
8434 SavedStreamPosition SavedPosition(Cursor);
8435
8436 RecordData Record;
8437 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008438 llvm::BitstreamEntry Entry =
8439 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008440
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008441 switch (Entry.Kind) {
8442 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8443 case llvm::BitstreamEntry::Error:
8444 Error("malformed block record in AST file");
8445 return;
8446 case llvm::BitstreamEntry::EndBlock:
8447 goto NextCursor;
8448 case llvm::BitstreamEntry::Record:
8449 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008451 }
8452
8453 // Read a record.
8454 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008455 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 case COMMENTS_RAW_COMMENT: {
8457 unsigned Idx = 0;
8458 SourceRange SR = ReadSourceRange(F, Record, Idx);
8459 RawComment::CommentKind Kind =
8460 (RawComment::CommentKind) Record[Idx++];
8461 bool IsTrailingComment = Record[Idx++];
8462 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008463 Comments.push_back(new (Context) RawComment(
8464 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8465 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 break;
8467 }
8468 }
8469 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008470 NextCursor:
8471 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008472 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008473}
8474
Richard Smithcd45dbc2014-04-19 03:48:30 +00008475std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8476 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008477 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008478 return M->getFullModuleName();
8479
8480 // Otherwise, use the name of the top-level module the decl is within.
8481 if (ModuleFile *M = getOwningModuleFile(D))
8482 return M->ModuleName;
8483
8484 // Not from a module.
8485 return "";
8486}
8487
Guy Benyei11169dd2012-12-18 14:30:41 +00008488void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008489 while (!PendingIdentifierInfos.empty() ||
8490 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008491 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008492 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008493 // If any identifiers with corresponding top-level declarations have
8494 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008495 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8496 TopLevelDeclsMap;
8497 TopLevelDeclsMap TopLevelDecls;
8498
Guy Benyei11169dd2012-12-18 14:30:41 +00008499 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008500 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008501 SmallVector<uint32_t, 4> DeclIDs =
8502 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008503 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008504
8505 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008507
Richard Smith851072e2014-05-19 20:59:20 +00008508 // For each decl chain that we wanted to complete while deserializing, mark
8509 // it as "still needs to be completed".
8510 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8511 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8512 }
8513 PendingIncompleteDeclChains.clear();
8514
Guy Benyei11169dd2012-12-18 14:30:41 +00008515 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008516 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008517 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 PendingDeclChains.clear();
8519
Douglas Gregor6168bd22013-02-18 15:53:43 +00008520 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008521 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8522 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008523 IdentifierInfo *II = TLD->first;
8524 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008525 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008526 }
8527 }
8528
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 // Load any pending macro definitions.
8530 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008531 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8532 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8533 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8534 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008535 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008536 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008537 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008538 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008539 resolvePendingMacro(II, Info);
8540 }
8541 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008542 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008543 ++IDIdx) {
8544 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008545 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008546 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008547 }
8548 }
8549 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008550
8551 // Wire up the DeclContexts for Decls that we delayed setting until
8552 // recursive loading is completed.
8553 while (!PendingDeclContextInfos.empty()) {
8554 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8555 PendingDeclContextInfos.pop_front();
8556 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8557 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8558 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8559 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008560
Richard Smithd1c46742014-04-30 02:24:17 +00008561 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008562 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008563 auto Update = PendingUpdateRecords.pop_back_val();
8564 ReadingKindTracker ReadingKind(Read_Decl, *this);
8565 loadDeclUpdateRecords(Update.first, Update.second);
8566 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008567 }
Richard Smith8a639892015-01-24 01:07:20 +00008568
8569 // At this point, all update records for loaded decls are in place, so any
8570 // fake class definitions should have become real.
8571 assert(PendingFakeDefinitionData.empty() &&
8572 "faked up a class definition but never saw the real one");
8573
Guy Benyei11169dd2012-12-18 14:30:41 +00008574 // If we deserialized any C++ or Objective-C class definitions, any
8575 // Objective-C protocol definitions, or any redeclarable templates, make sure
8576 // that all redeclarations point to the definitions. Note that this can only
8577 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008578 for (Decl *D : PendingDefinitions) {
8579 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008580 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008581 // Make sure that the TagType points at the definition.
8582 const_cast<TagType*>(TagT)->decl = TD;
8583 }
Richard Smith8ce51082015-03-11 01:44:51 +00008584
Craig Topperc6914d02014-08-25 04:15:02 +00008585 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008586 for (auto *R = getMostRecentExistingDecl(RD); R;
8587 R = R->getPreviousDecl()) {
8588 assert((R == D) ==
8589 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008590 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008591 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008592 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008593 }
8594
8595 continue;
8596 }
Richard Smith8ce51082015-03-11 01:44:51 +00008597
Craig Topperc6914d02014-08-25 04:15:02 +00008598 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008599 // Make sure that the ObjCInterfaceType points at the definition.
8600 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8601 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008602
8603 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8604 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8605
Guy Benyei11169dd2012-12-18 14:30:41 +00008606 continue;
8607 }
Richard Smith8ce51082015-03-11 01:44:51 +00008608
Craig Topperc6914d02014-08-25 04:15:02 +00008609 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008610 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8611 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8612
Guy Benyei11169dd2012-12-18 14:30:41 +00008613 continue;
8614 }
Richard Smith8ce51082015-03-11 01:44:51 +00008615
Craig Topperc6914d02014-08-25 04:15:02 +00008616 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008617 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8618 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 }
8620 PendingDefinitions.clear();
8621
8622 // Load the bodies of any functions or methods we've encountered. We do
8623 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008624 // have been fully wired up (hasBody relies on this).
8625 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008626 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8627 PBEnd = PendingBodies.end();
8628 PB != PBEnd; ++PB) {
8629 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8630 // FIXME: Check for =delete/=default?
8631 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008632 const FunctionDecl *Defn = nullptr;
8633 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008634 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008635 else
Richard Smith6561f922016-09-12 21:06:40 +00008636 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008637 continue;
8638 }
8639
8640 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8641 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8642 MD->setLazyBody(PB->second);
8643 }
8644 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008645
8646 // Do some cleanup.
8647 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8648 getContext().deduplicateMergedDefinitonsFor(ND);
8649 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008650}
8651
8652void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008653 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8654 return;
8655
Richard Smitha0ce9c42014-07-29 23:23:27 +00008656 // Trigger the import of the full definition of each class that had any
8657 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008658 // These updates may in turn find and diagnose some ODR failures, so take
8659 // ownership of the set first.
8660 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8661 PendingOdrMergeFailures.clear();
8662 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008663 Merge.first->buildLookup();
8664 Merge.first->decls_begin();
8665 Merge.first->bases_begin();
8666 Merge.first->vbases_begin();
8667 for (auto *RD : Merge.second) {
8668 RD->decls_begin();
8669 RD->bases_begin();
8670 RD->vbases_begin();
8671 }
8672 }
8673
8674 // For each declaration from a merged context, check that the canonical
8675 // definition of that context also contains a declaration of the same
8676 // entity.
8677 //
8678 // Caution: this loop does things that might invalidate iterators into
8679 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8680 while (!PendingOdrMergeChecks.empty()) {
8681 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8682
8683 // FIXME: Skip over implicit declarations for now. This matters for things
8684 // like implicitly-declared special member functions. This isn't entirely
8685 // correct; we can end up with multiple unmerged declarations of the same
8686 // implicit entity.
8687 if (D->isImplicit())
8688 continue;
8689
8690 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008691
8692 bool Found = false;
8693 const Decl *DCanon = D->getCanonicalDecl();
8694
Richard Smith01bdb7a2014-08-28 05:44:07 +00008695 for (auto RI : D->redecls()) {
8696 if (RI->getLexicalDeclContext() == CanonDef) {
8697 Found = true;
8698 break;
8699 }
8700 }
8701 if (Found)
8702 continue;
8703
Richard Smith0f4e2c42015-08-06 04:23:48 +00008704 // Quick check failed, time to do the slow thing. Note, we can't just
8705 // look up the name of D in CanonDef here, because the member that is
8706 // in CanonDef might not be found by name lookup (it might have been
8707 // replaced by a more recent declaration in the lookup table), and we
8708 // can't necessarily find it in the redeclaration chain because it might
8709 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008710 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008711 for (auto *CanonMember : CanonDef->decls()) {
8712 if (CanonMember->getCanonicalDecl() == DCanon) {
8713 // This can happen if the declaration is merely mergeable and not
8714 // actually redeclarable (we looked for redeclarations earlier).
8715 //
8716 // FIXME: We should be able to detect this more efficiently, without
8717 // pulling in all of the members of CanonDef.
8718 Found = true;
8719 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008720 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008721 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8722 if (ND->getDeclName() == D->getDeclName())
8723 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008724 }
8725
8726 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008727 // The AST doesn't like TagDecls becoming invalid after they've been
8728 // completed. We only really need to mark FieldDecls as invalid here.
8729 if (!isa<TagDecl>(D))
8730 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008731
8732 // Ensure we don't accidentally recursively enter deserialization while
8733 // we're producing our diagnostic.
8734 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008735
8736 std::string CanonDefModule =
8737 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8738 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8739 << D << getOwningModuleNameForDiagnostic(D)
8740 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8741
8742 if (Candidates.empty())
8743 Diag(cast<Decl>(CanonDef)->getLocation(),
8744 diag::note_module_odr_violation_no_possible_decls) << D;
8745 else {
8746 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8747 Diag(Candidates[I]->getLocation(),
8748 diag::note_module_odr_violation_possible_decl)
8749 << Candidates[I];
8750 }
8751
8752 DiagnosedOdrMergeFailures.insert(CanonDef);
8753 }
8754 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008755
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008756 if (OdrMergeFailures.empty())
8757 return;
8758
8759 // Ensure we don't accidentally recursively enter deserialization while
8760 // we're producing our diagnostics.
8761 Deserializing RecursionGuard(this);
8762
Richard Smithcd45dbc2014-04-19 03:48:30 +00008763 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008764 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008765 // If we've already pointed out a specific problem with this class, don't
8766 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008767 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008768 continue;
8769
8770 bool Diagnosed = false;
8771 for (auto *RD : Merge.second) {
8772 // Multiple different declarations got merged together; tell the user
8773 // where they came from.
8774 if (Merge.first != RD) {
8775 // FIXME: Walk the definition, figure out what's different,
8776 // and diagnose that.
8777 if (!Diagnosed) {
8778 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8779 Diag(Merge.first->getLocation(),
8780 diag::err_module_odr_violation_different_definitions)
8781 << Merge.first << Module.empty() << Module;
8782 Diagnosed = true;
8783 }
8784
8785 Diag(RD->getLocation(),
8786 diag::note_module_odr_violation_different_definitions)
8787 << getOwningModuleNameForDiagnostic(RD);
8788 }
8789 }
8790
8791 if (!Diagnosed) {
8792 // All definitions are updates to the same declaration. This happens if a
8793 // module instantiates the declaration of a class template specialization
8794 // and two or more other modules instantiate its definition.
8795 //
8796 // FIXME: Indicate which modules had instantiations of this definition.
8797 // FIXME: How can this even happen?
8798 Diag(Merge.first->getLocation(),
8799 diag::err_module_odr_violation_different_instantiations)
8800 << Merge.first;
8801 }
8802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008803}
8804
Richard Smithce18a182015-07-14 00:26:00 +00008805void ASTReader::StartedDeserializing() {
8806 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8807 ReadTimer->startTimer();
8808}
8809
Guy Benyei11169dd2012-12-18 14:30:41 +00008810void ASTReader::FinishedDeserializing() {
8811 assert(NumCurrentElementsDeserializing &&
8812 "FinishedDeserializing not paired with StartedDeserializing");
8813 if (NumCurrentElementsDeserializing == 1) {
8814 // We decrease NumCurrentElementsDeserializing only after pending actions
8815 // are finished, to avoid recursively re-calling finishPendingActions().
8816 finishPendingActions();
8817 }
8818 --NumCurrentElementsDeserializing;
8819
Richard Smitha0ce9c42014-07-29 23:23:27 +00008820 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008821 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008822 while (!PendingExceptionSpecUpdates.empty()) {
8823 auto Updates = std::move(PendingExceptionSpecUpdates);
8824 PendingExceptionSpecUpdates.clear();
8825 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008826 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008827 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008828 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008829 if (auto *Listener = Context.getASTMutationListener())
8830 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008831 for (auto *Redecl : Update.second->redecls())
8832 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008833 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008834 }
8835
Richard Smithce18a182015-07-14 00:26:00 +00008836 if (ReadTimer)
8837 ReadTimer->stopTimer();
8838
Richard Smith0f4e2c42015-08-06 04:23:48 +00008839 diagnoseOdrViolations();
8840
Richard Smith04d05b52014-03-23 00:27:18 +00008841 // We are not in recursive loading, so it's safe to pass the "interesting"
8842 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008843 if (Consumer)
8844 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008845 }
8846}
8847
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008848void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008849 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8850 // Remove any fake results before adding any real ones.
8851 auto It = PendingFakeLookupResults.find(II);
8852 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008853 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008854 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008855 // FIXME: this works around module+PCH performance issue.
8856 // Rather than erase the result from the map, which is O(n), just clear
8857 // the vector of NamedDecls.
8858 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008859 }
8860 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008861
8862 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8863 SemaObj->TUScope->AddDecl(D);
8864 } else if (SemaObj->TUScope) {
8865 // Adding the decl to IdResolver may have failed because it was already in
8866 // (even though it was not added in scope). If it is already in, make sure
8867 // it gets in the scope as well.
8868 if (std::find(SemaObj->IdResolver.begin(Name),
8869 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8870 SemaObj->TUScope->AddDecl(D);
8871 }
8872}
8873
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008874ASTReader::ASTReader(
8875 Preprocessor &PP, ASTContext &Context,
8876 const PCHContainerReader &PCHContainerRdr,
8877 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8878 StringRef isysroot, bool DisableValidation,
8879 bool AllowASTWithCompilerErrors,
8880 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8881 bool UseGlobalIndex,
8882 std::unique_ptr<llvm::Timer> ReadTimer)
Yaxun Liu43712e02016-09-07 18:40:20 +00008883 : Listener(DisableValidation ?
8884 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8885 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8886 DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008887 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008888 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008889 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008890 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smith10379092016-05-06 23:14:07 +00008891 DummyIdResolver(PP),
Richard Smithce18a182015-07-14 00:26:00 +00008892 ReadTimer(std::move(ReadTimer)),
Nico Weber779355f2016-03-02 23:22:00 +00008893 PragmaMSStructState(-1),
Nico Weber42932312016-03-03 00:17:35 +00008894 PragmaMSPointersToMembersState(-1),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008895 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008896 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8897 AllowConfigurationMismatch(AllowConfigurationMismatch),
8898 ValidateSystemInputs(ValidateSystemInputs),
8899 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008900 ProcessingUpdateRecords(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008901 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8902 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8903 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8904 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008905 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8906 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8907 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8908 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8909 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8910 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008911 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008912 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008913
8914 for (const auto &Ext : Extensions) {
8915 auto BlockName = Ext->getExtensionMetadata().BlockName;
8916 auto Known = ModuleFileExtensions.find(BlockName);
8917 if (Known != ModuleFileExtensions.end()) {
8918 Diags.Report(diag::warn_duplicate_module_file_extension)
8919 << BlockName;
8920 continue;
8921 }
8922
8923 ModuleFileExtensions.insert({BlockName, Ext});
8924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008925}
8926
8927ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008928 if (OwnsDeserializationListener)
8929 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008930}
Richard Smith10379092016-05-06 23:14:07 +00008931
8932IdentifierResolver &ASTReader::getIdResolver() {
8933 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8934}