blob: 6ae825b9709bd4126747d3dd214071f6141e1917 [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
Richard Smith7ed1bc92014-12-05 22:42:13 +00001603 if (llvm::sys::path::is_absolute(a.Filename) &&
1604 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605 return true;
1606
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001608 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001609 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1610 if (!Key.Imported)
1611 return FileMgr.getFile(Key.Filename);
1612
1613 std::string Resolved = Key.Filename;
1614 Reader.ResolveImportedPath(M, Resolved);
1615 return FileMgr.getFile(Resolved);
1616 };
1617
1618 const FileEntry *FEA = GetFile(a);
1619 const FileEntry *FEB = GetFile(b);
1620 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621}
1622
1623std::pair<unsigned, unsigned>
1624HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001625 using namespace llvm::support;
1626 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001627 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001628 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001629}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001630
1631HeaderFileInfoTrait::internal_key_type
1632HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001633 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001634 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001635 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1636 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001637 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001638 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001639 return ikey;
1640}
1641
Guy Benyei11169dd2012-12-18 14:30:41 +00001642HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001643HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 unsigned DataLen) {
1645 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001646 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 HeaderFileInfo HFI;
1648 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001649 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1650 HFI.isImport |= (Flags >> 4) & 0x01;
1651 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1652 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001654 // FIXME: Find a better way to handle this. Maybe just store a
1655 // "has been included" flag?
1656 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1657 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001658 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1659 M, endian::readNext<uint32_t, little, unaligned>(d));
1660 if (unsigned FrameworkOffset =
1661 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 // The framework offset is 1 greater than the actual offset,
1663 // since 0 is used as an indicator for "no framework name".
1664 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1665 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1666 }
Richard Smith386bb072015-08-18 23:42:23 +00001667
1668 assert((End - d) % 4 == 0 &&
1669 "Wrong data length in HeaderFileInfo deserialization");
1670 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001671 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001672 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1673 LocalSMID >>= 2;
1674
1675 // This header is part of a module. Associate it with the module to enable
1676 // implicit module import.
1677 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1678 Module *Mod = Reader.getSubmodule(GlobalSMID);
1679 FileManager &FileMgr = Reader.getFileManager();
1680 ModuleMap &ModMap =
1681 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1682
1683 std::string Filename = key.Filename;
1684 if (key.Imported)
1685 Reader.ResolveImportedPath(M, Filename);
1686 // FIXME: This is not always the right filename-as-written, but we're not
1687 // going to use this information to rebuild the module, so it doesn't make
1688 // a lot of difference.
1689 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001690 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1691 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001692 }
1693
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 // This HeaderFileInfo was externally loaded.
1695 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001696 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 return HFI;
1698}
1699
Richard Smithd7329392015-04-21 21:46:32 +00001700void ASTReader::addPendingMacro(IdentifierInfo *II,
1701 ModuleFile *M,
1702 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001703 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1704 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001705}
1706
1707void ASTReader::ReadDefinedMacros() {
1708 // Note that we are loading defined macros.
1709 Deserializing Macros(this);
1710
Pete Cooper57d3f142015-07-30 17:22:52 +00001711 for (auto &I : llvm::reverse(ModuleMgr)) {
1712 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001713
1714 // If there was no preprocessor block, skip this file.
1715 if (!MacroCursor.getBitStreamReader())
1716 continue;
1717
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001718 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001719 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001720
1721 RecordData Record;
1722 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001723 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1724
1725 switch (E.Kind) {
1726 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1727 case llvm::BitstreamEntry::Error:
1728 Error("malformed block record in AST file");
1729 return;
1730 case llvm::BitstreamEntry::EndBlock:
1731 goto NextCursor;
1732
1733 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001734 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001735 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001736 default: // Default behavior: ignore.
1737 break;
1738
1739 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001740 case PP_MACRO_FUNCTION_LIKE: {
1741 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1742 if (II->isOutOfDate())
1743 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001744 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001745 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001746
1747 case PP_TOKEN:
1748 // Ignore tokens.
1749 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001750 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 break;
1752 }
1753 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001754 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 }
1756}
1757
1758namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001759
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 /// \brief Visitor class used to look up identifirs in an AST file.
1761 class IdentifierLookupVisitor {
1762 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001763 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001765 unsigned &NumIdentifierLookups;
1766 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001767 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001768
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001770 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1771 unsigned &NumIdentifierLookups,
1772 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001773 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1774 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001775 NumIdentifierLookups(NumIdentifierLookups),
1776 NumIdentifierLookupHits(NumIdentifierLookupHits),
1777 Found()
1778 {
1779 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001780
1781 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001783 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 ASTIdentifierLookupTable *IdTable
1787 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1788 if (!IdTable)
1789 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001790
1791 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001792 Found);
1793 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001794 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001795 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 if (Pos == IdTable->end())
1797 return false;
1798
1799 // Dereferencing the iterator has the effect of building the
1800 // IdentifierInfo node and populating it with the various
1801 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001802 ++NumIdentifierLookupHits;
1803 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 return true;
1805 }
1806
1807 // \brief Retrieve the identifier info found within the module
1808 // files.
1809 IdentifierInfo *getIdentifierInfo() const { return Found; }
1810 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001811
1812} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001813
1814void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1815 // Note that we are loading an identifier.
1816 Deserializing AnIdentifier(this);
1817
1818 unsigned PriorGeneration = 0;
1819 if (getContext().getLangOpts().Modules)
1820 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001821
1822 // If there is a global index, look there first to determine which modules
1823 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001824 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001825 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001826 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001827 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1828 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001829 }
1830 }
1831
Douglas Gregor7211ac12013-01-25 23:32:03 +00001832 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001833 NumIdentifierLookups,
1834 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001835 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001836 markIdentifierUpToDate(&II);
1837}
1838
1839void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1840 if (!II)
1841 return;
1842
1843 II->setOutOfDate(false);
1844
1845 // Update the generation for this identifier.
1846 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001847 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001848}
1849
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001850void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1851 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001852 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001853
1854 BitstreamCursor &Cursor = M.MacroCursor;
1855 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001856 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001857
Richard Smith713369b2015-04-23 20:40:50 +00001858 struct ModuleMacroRecord {
1859 SubmoduleID SubModID;
1860 MacroInfo *MI;
1861 SmallVector<SubmoduleID, 8> Overrides;
1862 };
1863 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864
Richard Smithd7329392015-04-21 21:46:32 +00001865 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1866 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1867 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001868 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001869 while (true) {
1870 llvm::BitstreamEntry Entry =
1871 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1872 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1873 Error("malformed block record in AST file");
1874 return;
1875 }
1876
1877 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001878 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001879 case PP_MACRO_DIRECTIVE_HISTORY:
1880 break;
1881
1882 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001883 ModuleMacros.push_back(ModuleMacroRecord());
1884 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001885 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1886 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001887 for (int I = 2, N = Record.size(); I != N; ++I)
1888 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001889 continue;
1890 }
1891
1892 default:
1893 Error("malformed block record in AST file");
1894 return;
1895 }
1896
1897 // We found the macro directive history; that's the last record
1898 // for this macro.
1899 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001900 }
1901
Richard Smithd7329392015-04-21 21:46:32 +00001902 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001903 {
1904 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001905 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001906 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001907 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001908 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001909 Module *Mod = getSubmodule(ModID);
1910 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001911 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001912 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001913 }
1914
1915 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001916 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001917 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001918 }
1919 }
1920
1921 // Don't read the directive history for a module; we don't have anywhere
1922 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001923 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001924 return;
1925
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001926 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001927 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001928 unsigned Idx = 0, N = Record.size();
1929 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001930 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001931 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001932 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1933 switch (K) {
1934 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001935 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001936 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001937 break;
1938 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001939 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001940 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001941 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001942 }
1943 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001944 bool isPublic = Record[Idx++];
1945 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1946 break;
1947 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001948
1949 if (!Latest)
1950 Latest = MD;
1951 if (Earliest)
1952 Earliest->setPrevious(MD);
1953 Earliest = MD;
1954 }
1955
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001956 if (Latest)
1957 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001958}
1959
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001960ASTReader::InputFileInfo
1961ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001962 // Go find this input file.
1963 BitstreamCursor &Cursor = F.InputFilesCursor;
1964 SavedStreamPosition SavedPosition(Cursor);
1965 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1966
1967 unsigned Code = Cursor.ReadCode();
1968 RecordData Record;
1969 StringRef Blob;
1970
1971 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1972 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1973 "invalid record type for input file");
1974 (void)Result;
1975
1976 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001977 InputFileInfo R;
1978 R.StoredSize = static_cast<off_t>(Record[1]);
1979 R.StoredTime = static_cast<time_t>(Record[2]);
1980 R.Overridden = static_cast<bool>(Record[3]);
1981 R.Transient = static_cast<bool>(Record[4]);
1982 R.Filename = Blob;
1983 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001984 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001985}
1986
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001987InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 // If this ID is bogus, just return an empty input file.
1989 if (ID == 0 || ID > F.InputFilesLoaded.size())
1990 return InputFile();
1991
1992 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001993 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 return F.InputFilesLoaded[ID-1];
1995
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001996 if (F.InputFilesLoaded[ID-1].isNotFound())
1997 return InputFile();
1998
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002000 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 SavedStreamPosition SavedPosition(Cursor);
2002 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2003
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002004 InputFileInfo FI = readInputFileInfo(F, ID);
2005 off_t StoredSize = FI.StoredSize;
2006 time_t StoredTime = FI.StoredTime;
2007 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002008 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002009 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002010
Richard Smitha8cfffa2015-11-26 02:04:16 +00002011 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002012
2013 // If we didn't find the file, resolve it relative to the
2014 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002015 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 F.OriginalDir != CurrentDir) {
2017 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2018 F.OriginalDir,
2019 CurrentDir);
2020 if (!Resolved.empty())
2021 File = FileMgr.getFile(Resolved);
2022 }
2023
2024 // For an overridden file, create a virtual file with the stored
2025 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002026 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002027 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002028
Craig Toppera13603a2014-05-22 05:54:18 +00002029 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002030 if (Complain) {
2031 std::string ErrorStr = "could not find file '";
2032 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002033 ErrorStr += "' referenced by AST file '";
2034 ErrorStr += F.FileName;
2035 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002036 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002038 // Record that we didn't find the file.
2039 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2040 return InputFile();
2041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002042
Ben Langmuir198c1682014-03-07 07:27:49 +00002043 // Check if there was a request to override the contents of the file
2044 // that was part of the precompiled header. Overridding such a file
2045 // can lead to problems when lexing using the source locations from the
2046 // PCH.
2047 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002048 // FIXME: Reject if the overrides are different.
2049 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002050 if (Complain)
2051 Error(diag::err_fe_pch_file_overridden, Filename);
2052 // After emitting the diagnostic, recover by disabling the override so
2053 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002054 //
2055 // FIXME: This recovery is just as broken as the original state; there may
2056 // be another precompiled module that's using the overridden contents, or
2057 // we might be half way through parsing it. Instead, we should treat the
2058 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002059 SM.disableFileContentsOverride(File);
2060 // The FileEntry is a virtual file entry with the size of the contents
2061 // that would override the original contents. Set it to the original's
2062 // size/time.
2063 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2064 StoredSize, StoredTime);
2065 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002066
Ben Langmuir198c1682014-03-07 07:27:49 +00002067 bool IsOutOfDate = false;
2068
2069 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002070 if (!Overridden && //
2071 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002072 (StoredTime && StoredTime != File->getModificationTime() &&
2073 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002074 )) {
2075 if (Complain) {
2076 // Build a list of the PCH imports that got us here (in reverse).
2077 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2078 while (ImportStack.back()->ImportedBy.size() > 0)
2079 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002080
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 // The top-level PCH is stale.
2082 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2083 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002084
Ben Langmuir198c1682014-03-07 07:27:49 +00002085 // Print the import stack.
2086 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2087 Diag(diag::note_pch_required_by)
2088 << Filename << ImportStack[0]->FileName;
2089 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002090 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002091 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002092 }
2093
Ben Langmuir198c1682014-03-07 07:27:49 +00002094 if (!Diags.isDiagnosticInFlight())
2095 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 }
2097
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002100 // FIXME: If the file is overridden and we've already opened it,
2101 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002102
Richard Smitha8cfffa2015-11-26 02:04:16 +00002103 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002104
2105 // Note that we've loaded this input file.
2106 F.InputFilesLoaded[ID-1] = IF;
2107 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002108}
2109
Richard Smith7ed1bc92014-12-05 22:42:13 +00002110/// \brief If we are loading a relocatable PCH or module file, and the filename
2111/// is not an absolute path, add the system or module root to the beginning of
2112/// the file name.
2113void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2114 // Resolve relative to the base directory, if we have one.
2115 if (!M.BaseDirectory.empty())
2116 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002117}
2118
Richard Smith7ed1bc92014-12-05 22:42:13 +00002119void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2121 return;
2122
Richard Smith7ed1bc92014-12-05 22:42:13 +00002123 SmallString<128> Buffer;
2124 llvm::sys::path::append(Buffer, Prefix, Filename);
2125 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002126}
2127
Richard Smith0f99d6a2015-08-09 08:48:41 +00002128static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2129 switch (ARR) {
2130 case ASTReader::Failure: return true;
2131 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2132 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2133 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2134 case ASTReader::ConfigurationMismatch:
2135 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2136 case ASTReader::HadErrors: return true;
2137 case ASTReader::Success: return false;
2138 }
2139
2140 llvm_unreachable("unknown ASTReadResult");
2141}
2142
Richard Smith0516b182015-09-08 19:40:14 +00002143ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2144 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2145 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002146 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002147 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2148 return Failure;
2149
2150 // Read all of the records in the options block.
2151 RecordData Record;
2152 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002153 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002154 llvm::BitstreamEntry Entry = Stream.advance();
2155
2156 switch (Entry.Kind) {
2157 case llvm::BitstreamEntry::Error:
2158 case llvm::BitstreamEntry::SubBlock:
2159 return Failure;
2160
2161 case llvm::BitstreamEntry::EndBlock:
2162 return Result;
2163
2164 case llvm::BitstreamEntry::Record:
2165 // The interesting case.
2166 break;
2167 }
2168
2169 // Read and process a record.
2170 Record.clear();
2171 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2172 case LANGUAGE_OPTIONS: {
2173 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2174 if (ParseLanguageOptions(Record, Complain, Listener,
2175 AllowCompatibleConfigurationMismatch))
2176 Result = ConfigurationMismatch;
2177 break;
2178 }
2179
2180 case TARGET_OPTIONS: {
2181 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2182 if (ParseTargetOptions(Record, Complain, Listener,
2183 AllowCompatibleConfigurationMismatch))
2184 Result = ConfigurationMismatch;
2185 break;
2186 }
2187
2188 case DIAGNOSTIC_OPTIONS: {
2189 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002190 if (ValidateDiagnosticOptions &&
2191 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002192 ParseDiagnosticOptions(Record, Complain, Listener))
2193 return OutOfDate;
2194 break;
2195 }
2196
2197 case FILE_SYSTEM_OPTIONS: {
2198 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2199 if (!AllowCompatibleConfigurationMismatch &&
2200 ParseFileSystemOptions(Record, Complain, Listener))
2201 Result = ConfigurationMismatch;
2202 break;
2203 }
2204
2205 case HEADER_SEARCH_OPTIONS: {
2206 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2207 if (!AllowCompatibleConfigurationMismatch &&
2208 ParseHeaderSearchOptions(Record, Complain, Listener))
2209 Result = ConfigurationMismatch;
2210 break;
2211 }
2212
2213 case PREPROCESSOR_OPTIONS:
2214 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2215 if (!AllowCompatibleConfigurationMismatch &&
2216 ParsePreprocessorOptions(Record, Complain, Listener,
2217 SuggestedPredefines))
2218 Result = ConfigurationMismatch;
2219 break;
2220 }
2221 }
2222}
2223
Guy Benyei11169dd2012-12-18 14:30:41 +00002224ASTReader::ASTReadResult
2225ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002226 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002227 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002229 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002230 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002231
2232 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2233 Error("malformed block record in AST file");
2234 return Failure;
2235 }
2236
2237 // Read all of the records and blocks in the control block.
2238 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002239 unsigned NumInputs = 0;
2240 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002241 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002242 llvm::BitstreamEntry Entry = Stream.advance();
2243
2244 switch (Entry.Kind) {
2245 case llvm::BitstreamEntry::Error:
2246 Error("malformed block record in AST file");
2247 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002248 case llvm::BitstreamEntry::EndBlock: {
2249 // Validate input files.
2250 const HeaderSearchOptions &HSOpts =
2251 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002252
Richard Smitha1825302014-10-23 22:18:29 +00002253 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002254 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2255 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002256 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2257 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002259
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002260 // If we are reading a module, we will create a verification timestamp,
2261 // so we verify all input files. Otherwise, verify only user input
2262 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002263
2264 unsigned N = NumUserInputs;
2265 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002266 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002267 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002268 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002269 N = NumInputs;
2270
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002271 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002272 InputFile IF = getInputFile(F, I+1, Complain);
2273 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002275 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002277
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002278 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002279 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002280
Ben Langmuircb69b572014-03-07 06:40:32 +00002281 if (Listener && Listener->needsInputFileVisitation()) {
2282 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2283 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002284 for (unsigned I = 0; I < N; ++I) {
2285 bool IsSystem = I >= NumUserInputs;
2286 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002287 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002288 F.Kind == MK_ExplicitModule ||
2289 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002290 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002291 }
2292
Richard Smith8a308ec2015-11-05 00:54:55 +00002293 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002294 }
2295
Chris Lattnere7b154b2013-01-19 21:39:22 +00002296 case llvm::BitstreamEntry::SubBlock:
2297 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 case INPUT_FILES_BLOCK_ID:
2299 F.InputFilesCursor = Stream;
2300 if (Stream.SkipBlock() || // Skip with the main cursor
2301 // Read the abbreviations
2302 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2303 Error("malformed block record in AST file");
2304 return Failure;
2305 }
2306 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002307
2308 case OPTIONS_BLOCK_ID:
2309 // If we're reading the first module for this group, check its options
2310 // are compatible with ours. For modules it imports, no further checking
2311 // is required, because we checked them when we built it.
2312 if (Listener && !ImportedBy) {
2313 // Should we allow the configuration of the module file to differ from
2314 // the configuration of the current translation unit in a compatible
2315 // way?
2316 //
2317 // FIXME: Allow this for files explicitly specified with -include-pch.
2318 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002319 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002320 const HeaderSearchOptions &HSOpts =
2321 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002322
Richard Smith8a308ec2015-11-05 00:54:55 +00002323 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2324 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002325 *Listener, SuggestedPredefines,
2326 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002327 if (Result == Failure) {
2328 Error("malformed block record in AST file");
2329 return Result;
2330 }
2331
Richard Smith8a308ec2015-11-05 00:54:55 +00002332 if (DisableValidation ||
2333 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2334 Result = Success;
2335
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002336 // If we can't load the module, exit early since we likely
2337 // will rebuild the module anyway. The stream may be in the
2338 // middle of a block.
2339 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002340 return Result;
2341 } else if (Stream.SkipBlock()) {
2342 Error("malformed block record in AST file");
2343 return Failure;
2344 }
2345 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002346
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002348 if (Stream.SkipBlock()) {
2349 Error("malformed block record in AST file");
2350 return Failure;
2351 }
2352 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354
2355 case llvm::BitstreamEntry::Record:
2356 // The interesting case.
2357 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 }
2359
2360 // Read and process a record.
2361 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002362 StringRef Blob;
2363 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 case METADATA: {
2365 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2366 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002367 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2368 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 return VersionMismatch;
2370 }
2371
Richard Smithe75ee0f2015-08-17 07:13:32 +00002372 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2374 Diag(diag::err_pch_with_compiler_errors);
2375 return HadErrors;
2376 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002377 if (hasErrors) {
2378 Diags.ErrorOccurred = true;
2379 Diags.UncompilableErrorOccurred = true;
2380 Diags.UnrecoverableErrorOccurred = true;
2381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002382
2383 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002384 // Relative paths in a relocatable PCH are relative to our sysroot.
2385 if (F.RelocatablePCH)
2386 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002387
Richard Smithe75ee0f2015-08-17 07:13:32 +00002388 F.HasTimestamps = Record[5];
2389
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002391 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2393 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002394 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 return VersionMismatch;
2396 }
2397 break;
2398 }
2399
Ben Langmuir487ea142014-10-23 18:05:36 +00002400 case SIGNATURE:
2401 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2402 F.Signature = Record[0];
2403 break;
2404
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case IMPORTS: {
2406 // Load each of the imported PCH files.
2407 unsigned Idx = 0, N = Record.size();
2408 while (Idx < N) {
2409 // Read information about the AST file.
2410 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2411 // The import location will be the local one for now; we will adjust
2412 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002413 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002415 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002416 off_t StoredSize = (off_t)Record[Idx++];
2417 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002418 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002419 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002420
Richard Smith0f99d6a2015-08-09 08:48:41 +00002421 // If our client can't cope with us being out of date, we can't cope with
2422 // our dependency being missing.
2423 unsigned Capabilities = ClientLoadCapabilities;
2424 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2425 Capabilities &= ~ARR_Missing;
2426
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002428 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2429 Loaded, StoredSize, StoredModTime,
2430 StoredSignature, Capabilities);
2431
2432 // If we diagnosed a problem, produce a backtrace.
2433 if (isDiagnosedResult(Result, Capabilities))
2434 Diag(diag::note_module_file_imported_by)
2435 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2436
2437 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 case Failure: return Failure;
2439 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002440 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 case OutOfDate: return OutOfDate;
2442 case VersionMismatch: return VersionMismatch;
2443 case ConfigurationMismatch: return ConfigurationMismatch;
2444 case HadErrors: return HadErrors;
2445 case Success: break;
2446 }
2447 }
2448 break;
2449 }
2450
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 case ORIGINAL_FILE:
2452 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002453 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002455 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 break;
2457
2458 case ORIGINAL_FILE_ID:
2459 F.OriginalSourceFileID = FileID::get(Record[0]);
2460 break;
2461
2462 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002463 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 break;
2465
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002466 case MODULE_NAME:
2467 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002468 if (Listener)
2469 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002470 break;
2471
Richard Smith223d3f22014-12-06 03:21:08 +00002472 case MODULE_DIRECTORY: {
2473 assert(!F.ModuleName.empty() &&
2474 "MODULE_DIRECTORY found before MODULE_NAME");
2475 // If we've already loaded a module map file covering this module, we may
2476 // have a better path for it (relative to the current build).
2477 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2478 if (M && M->Directory) {
2479 // If we're implicitly loading a module, the base directory can't
2480 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002481 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002482 const DirectoryEntry *BuildDir =
2483 PP.getFileManager().getDirectory(Blob);
2484 if (!BuildDir || BuildDir != M->Directory) {
2485 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2486 Diag(diag::err_imported_module_relocated)
2487 << F.ModuleName << Blob << M->Directory->getName();
2488 return OutOfDate;
2489 }
2490 }
2491 F.BaseDirectory = M->Directory->getName();
2492 } else {
2493 F.BaseDirectory = Blob;
2494 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002495 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002496 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002497
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002498 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002499 if (ASTReadResult Result =
2500 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2501 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002502 break;
2503
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002504 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002505 NumInputs = Record[0];
2506 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002507 F.InputFileOffsets =
2508 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002509 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 break;
2511 }
2512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002513}
2514
Ben Langmuir2c9af442014-04-10 17:57:43 +00002515ASTReader::ASTReadResult
2516ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002517 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518
2519 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2520 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002521 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 }
2523
2524 // Read all of the records and blocks for the AST file.
2525 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002526 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002527 llvm::BitstreamEntry Entry = Stream.advance();
2528
2529 switch (Entry.Kind) {
2530 case llvm::BitstreamEntry::Error:
2531 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002532 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002533 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002534 // Outside of C++, we do not store a lookup map for the translation unit.
2535 // Instead, mark it as needing a lookup map to be built if this module
2536 // contains any declarations lexically within it (which it always does!).
2537 // This usually has no cost, since we very rarely need the lookup map for
2538 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002540 if (DC->hasExternalLexicalStorage() &&
2541 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002543
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002546 case llvm::BitstreamEntry::SubBlock:
2547 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 case DECLTYPES_BLOCK_ID:
2549 // We lazily load the decls block, but we want to set up the
2550 // DeclsCursor cursor to point into it. Clone our current bitcode
2551 // cursor to it, enter the block and read the abbrevs in that block.
2552 // With the main cursor, we just skip over it.
2553 F.DeclsCursor = Stream;
2554 if (Stream.SkipBlock() || // Skip with the main cursor.
2555 // Read the abbrevs.
2556 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2557 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002558 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 }
2560 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002561
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 case PREPROCESSOR_BLOCK_ID:
2563 F.MacroCursor = Stream;
2564 if (!PP.getExternalSource())
2565 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002566
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 if (Stream.SkipBlock() ||
2568 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2569 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002570 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 }
2572 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2573 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002574
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 case PREPROCESSOR_DETAIL_BLOCK_ID:
2576 F.PreprocessorDetailCursor = Stream;
2577 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002578 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002580 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002581 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002582 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002584 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2585
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 if (!PP.getPreprocessingRecord())
2587 PP.createPreprocessingRecord();
2588 if (!PP.getPreprocessingRecord()->getExternalSource())
2589 PP.getPreprocessingRecord()->SetExternalSource(*this);
2590 break;
2591
2592 case SOURCE_MANAGER_BLOCK_ID:
2593 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002594 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002598 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2599 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002603 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 if (Stream.SkipBlock() ||
2605 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2606 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002607 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 }
2609 CommentsCursors.push_back(std::make_pair(C, &F));
2610 break;
2611 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002614 if (Stream.SkipBlock()) {
2615 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617 }
2618 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 }
2620 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002621
2622 case llvm::BitstreamEntry::Record:
2623 // The interesting case.
2624 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626
2627 // Read and process a record.
2628 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002629 StringRef Blob;
2630 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 default: // Default behavior: ignore.
2632 break;
2633
2634 case TYPE_OFFSET: {
2635 if (F.LocalNumTypes != 0) {
2636 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002637 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002639 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 F.LocalNumTypes = Record[0];
2641 unsigned LocalBaseTypeIndex = Record[1];
2642 F.BaseTypeIndex = getTotalNumTypes();
2643
2644 if (F.LocalNumTypes > 0) {
2645 // Introduce the global -> local mapping for types within this module.
2646 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2647
2648 // Introduce the local -> global mapping for types within this module.
2649 F.TypeRemap.insertOrReplace(
2650 std::make_pair(LocalBaseTypeIndex,
2651 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002652
2653 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
2655 break;
2656 }
2657
2658 case DECL_OFFSET: {
2659 if (F.LocalNumDecls != 0) {
2660 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002661 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002663 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 F.LocalNumDecls = Record[0];
2665 unsigned LocalBaseDeclID = Record[1];
2666 F.BaseDeclID = getTotalNumDecls();
2667
2668 if (F.LocalNumDecls > 0) {
2669 // Introduce the global -> local mapping for declarations within this
2670 // module.
2671 GlobalDeclMap.insert(
2672 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2673
2674 // Introduce the local -> global mapping for declarations within this
2675 // module.
2676 F.DeclRemap.insertOrReplace(
2677 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2678
2679 // Introduce the global -> local mapping for declarations within this
2680 // module.
2681 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002682
Ben Langmuir52ca6782014-10-20 16:27:32 +00002683 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2684 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 break;
2686 }
2687
2688 case TU_UPDATE_LEXICAL: {
2689 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002690 LexicalContents Contents(
2691 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2692 Blob.data()),
2693 static_cast<unsigned int>(Blob.size() / 4));
2694 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 TU->setHasExternalLexicalStorage(true);
2696 break;
2697 }
2698
2699 case UPDATE_VISIBLE: {
2700 unsigned Idx = 0;
2701 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002702 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002703 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002704 // If we've already loaded the decl, perform the updates when we finish
2705 // loading this block.
2706 if (Decl *D = GetExistingDecl(ID))
2707 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 break;
2709 }
2710
2711 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002712 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002714 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2715 (const unsigned char *)F.IdentifierTableData + Record[0],
2716 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2717 (const unsigned char *)F.IdentifierTableData,
2718 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002719
2720 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2721 }
2722 break;
2723
2724 case IDENTIFIER_OFFSET: {
2725 if (F.LocalNumIdentifiers != 0) {
2726 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002727 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 F.LocalNumIdentifiers = Record[0];
2731 unsigned LocalBaseIdentifierID = Record[1];
2732 F.BaseIdentifierID = getTotalNumIdentifiers();
2733
2734 if (F.LocalNumIdentifiers > 0) {
2735 // Introduce the global -> local mapping for identifiers within this
2736 // module.
2737 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2738 &F));
2739
2740 // Introduce the local -> global mapping for identifiers within this
2741 // module.
2742 F.IdentifierRemap.insertOrReplace(
2743 std::make_pair(LocalBaseIdentifierID,
2744 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002745
Ben Langmuir52ca6782014-10-20 16:27:32 +00002746 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2747 + F.LocalNumIdentifiers);
2748 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 break;
2750 }
2751
Richard Smith33e0f7e2015-07-22 02:08:40 +00002752 case INTERESTING_IDENTIFIERS:
2753 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2754 break;
2755
Ben Langmuir332aafe2014-01-31 01:06:56 +00002756 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002757 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2758 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002760 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
2762
2763 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002764 if (SpecialTypes.empty()) {
2765 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2766 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2767 break;
2768 }
2769
2770 if (SpecialTypes.size() != Record.size()) {
2771 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002772 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002773 }
2774
2775 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2776 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2777 if (!SpecialTypes[I])
2778 SpecialTypes[I] = ID;
2779 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2780 // merge step?
2781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 break;
2783
2784 case STATISTICS:
2785 TotalNumStatements += Record[0];
2786 TotalNumMacros += Record[1];
2787 TotalLexicalDeclContexts += Record[2];
2788 TotalVisibleDeclContexts += Record[3];
2789 break;
2790
2791 case UNUSED_FILESCOPED_DECLS:
2792 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2793 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2794 break;
2795
2796 case DELEGATING_CTORS:
2797 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2798 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2799 break;
2800
2801 case WEAK_UNDECLARED_IDENTIFIERS:
2802 if (Record.size() % 4 != 0) {
2803 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002804 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 }
2806
2807 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2808 // files. This isn't the way to do it :)
2809 WeakUndeclaredIdentifiers.clear();
2810
2811 // Translate the weak, undeclared identifiers into global IDs.
2812 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2813 WeakUndeclaredIdentifiers.push_back(
2814 getGlobalIdentifierID(F, Record[I++]));
2815 WeakUndeclaredIdentifiers.push_back(
2816 getGlobalIdentifierID(F, Record[I++]));
2817 WeakUndeclaredIdentifiers.push_back(
2818 ReadSourceLocation(F, Record, I).getRawEncoding());
2819 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2820 }
2821 break;
2822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002824 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 F.LocalNumSelectors = Record[0];
2826 unsigned LocalBaseSelectorID = Record[1];
2827 F.BaseSelectorID = getTotalNumSelectors();
2828
2829 if (F.LocalNumSelectors > 0) {
2830 // Introduce the global -> local mapping for selectors within this
2831 // module.
2832 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2833
2834 // Introduce the local -> global mapping for selectors within this
2835 // module.
2836 F.SelectorRemap.insertOrReplace(
2837 std::make_pair(LocalBaseSelectorID,
2838 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002839
2840 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842 break;
2843 }
2844
2845 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002846 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 if (Record[0])
2848 F.SelectorLookupTable
2849 = ASTSelectorLookupTable::Create(
2850 F.SelectorLookupTableData + Record[0],
2851 F.SelectorLookupTableData,
2852 ASTSelectorLookupTrait(*this, F));
2853 TotalNumMethodPoolEntries += Record[1];
2854 break;
2855
2856 case REFERENCED_SELECTOR_POOL:
2857 if (!Record.empty()) {
2858 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2859 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2860 Record[Idx++]));
2861 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2862 getRawEncoding());
2863 }
2864 }
2865 break;
2866
2867 case PP_COUNTER_VALUE:
2868 if (!Record.empty() && Listener)
2869 Listener->ReadCounter(F, Record[0]);
2870 break;
2871
2872 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002873 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 F.NumFileSortedDecls = Record[0];
2875 break;
2876
2877 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002878 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 F.LocalNumSLocEntries = Record[0];
2880 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002881 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002882 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002884 if (!F.SLocEntryBaseID) {
2885 Error("ran out of source locations");
2886 break;
2887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 // Make our entry in the range map. BaseID is negative and growing, so
2889 // we invert it. Because we invert it, though, we need the other end of
2890 // the range.
2891 unsigned RangeStart =
2892 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2893 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2894 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2895
2896 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2897 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2898 GlobalSLocOffsetMap.insert(
2899 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2900 - SLocSpaceSize,&F));
2901
2902 // Initialize the remapping table.
2903 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002904 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002906 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2908
2909 TotalNumSLocEntries += F.LocalNumSLocEntries;
2910 break;
2911 }
2912
2913 case MODULE_OFFSET_MAP: {
2914 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002915 const unsigned char *Data = (const unsigned char*)Blob.data();
2916 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002917
2918 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2919 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2920 F.SLocRemap.insert(std::make_pair(0U, 0));
2921 F.SLocRemap.insert(std::make_pair(2U, 1));
2922 }
2923
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002925 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2926 RemapBuilder;
2927 RemapBuilder SLocRemap(F.SLocRemap);
2928 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2929 RemapBuilder MacroRemap(F.MacroRemap);
2930 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2931 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2932 RemapBuilder SelectorRemap(F.SelectorRemap);
2933 RemapBuilder DeclRemap(F.DeclRemap);
2934 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002935
Richard Smithd8879c82015-08-24 21:59:32 +00002936 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002937 using namespace llvm::support;
2938 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 StringRef Name = StringRef((const char*)Data, Len);
2940 Data += Len;
2941 ModuleFile *OM = ModuleMgr.lookup(Name);
2942 if (!OM) {
2943 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002944 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 }
2946
Justin Bogner57ba0b22014-03-28 22:03:24 +00002947 uint32_t SLocOffset =
2948 endian::readNext<uint32_t, little, unaligned>(Data);
2949 uint32_t IdentifierIDOffset =
2950 endian::readNext<uint32_t, little, unaligned>(Data);
2951 uint32_t MacroIDOffset =
2952 endian::readNext<uint32_t, little, unaligned>(Data);
2953 uint32_t PreprocessedEntityIDOffset =
2954 endian::readNext<uint32_t, little, unaligned>(Data);
2955 uint32_t SubmoduleIDOffset =
2956 endian::readNext<uint32_t, little, unaligned>(Data);
2957 uint32_t SelectorIDOffset =
2958 endian::readNext<uint32_t, little, unaligned>(Data);
2959 uint32_t DeclIDOffset =
2960 endian::readNext<uint32_t, little, unaligned>(Data);
2961 uint32_t TypeIndexOffset =
2962 endian::readNext<uint32_t, little, unaligned>(Data);
2963
Ben Langmuir785180e2014-10-20 16:27:30 +00002964 uint32_t None = std::numeric_limits<uint32_t>::max();
2965
2966 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2967 RemapBuilder &Remap) {
2968 if (Offset != None)
2969 Remap.insert(std::make_pair(Offset,
2970 static_cast<int>(BaseOffset - Offset)));
2971 };
2972 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2973 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2974 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2975 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2976 PreprocessedEntityRemap);
2977 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2978 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2979 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2980 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002981
2982 // Global -> local mappings.
2983 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2984 }
2985 break;
2986 }
2987
2988 case SOURCE_MANAGER_LINE_TABLE:
2989 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002990 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 break;
2992
2993 case SOURCE_LOCATION_PRELOADS: {
2994 // Need to transform from the local view (1-based IDs) to the global view,
2995 // which is based off F.SLocEntryBaseID.
2996 if (!F.PreloadSLocEntries.empty()) {
2997 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002998 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 }
3000
3001 F.PreloadSLocEntries.swap(Record);
3002 break;
3003 }
3004
3005 case EXT_VECTOR_DECLS:
3006 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3007 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3008 break;
3009
3010 case VTABLE_USES:
3011 if (Record.size() % 3 != 0) {
3012 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003013 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003014 }
3015
3016 // Later tables overwrite earlier ones.
3017 // FIXME: Modules will have some trouble with this. This is clearly not
3018 // the right way to do this.
3019 VTableUses.clear();
3020
3021 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3022 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3023 VTableUses.push_back(
3024 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3025 VTableUses.push_back(Record[Idx++]);
3026 }
3027 break;
3028
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 case PENDING_IMPLICIT_INSTANTIATIONS:
3030 if (PendingInstantiations.size() % 2 != 0) {
3031 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003032 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 }
3034
3035 if (Record.size() % 2 != 0) {
3036 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003037 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 }
3039
3040 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3041 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3042 PendingInstantiations.push_back(
3043 ReadSourceLocation(F, Record, I).getRawEncoding());
3044 }
3045 break;
3046
3047 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003048 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003049 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003050 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003051 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3053 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3054 break;
3055
3056 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003057 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3058 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3059 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003060
3061 unsigned LocalBasePreprocessedEntityID = Record[0];
3062
3063 unsigned StartingID;
3064 if (!PP.getPreprocessingRecord())
3065 PP.createPreprocessingRecord();
3066 if (!PP.getPreprocessingRecord()->getExternalSource())
3067 PP.getPreprocessingRecord()->SetExternalSource(*this);
3068 StartingID
3069 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003070 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 F.BasePreprocessedEntityID = StartingID;
3072
3073 if (F.NumPreprocessedEntities > 0) {
3074 // Introduce the global -> local mapping for preprocessed entities in
3075 // this module.
3076 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3077
3078 // Introduce the local -> global mapping for preprocessed entities in
3079 // this module.
3080 F.PreprocessedEntityRemap.insertOrReplace(
3081 std::make_pair(LocalBasePreprocessedEntityID,
3082 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3083 }
3084
3085 break;
3086 }
3087
3088 case DECL_UPDATE_OFFSETS: {
3089 if (Record.size() % 2 != 0) {
3090 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003091 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003093 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3094 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3095 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3096
3097 // If we've already loaded the decl, perform the updates when we finish
3098 // loading this block.
3099 if (Decl *D = GetExistingDecl(ID))
3100 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3101 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 break;
3103 }
3104
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 case OBJC_CATEGORIES_MAP: {
3106 if (F.LocalNumObjCCategoriesInMap != 0) {
3107 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003108 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 }
3110
3111 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003112 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 break;
3114 }
3115
3116 case OBJC_CATEGORIES:
3117 F.ObjCCategories.swap(Record);
3118 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 case DIAG_PRAGMA_MAPPINGS:
3121 if (F.PragmaDiagMappings.empty())
3122 F.PragmaDiagMappings.swap(Record);
3123 else
3124 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3125 Record.begin(), Record.end());
3126 break;
3127
3128 case CUDA_SPECIAL_DECL_REFS:
3129 // Later tables overwrite earlier ones.
3130 // FIXME: Modules will have trouble with this.
3131 CUDASpecialDeclRefs.clear();
3132 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3133 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3134 break;
3135
3136 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003137 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 if (Record[0]) {
3140 F.HeaderFileInfoTable
3141 = HeaderFileInfoLookupTable::Create(
3142 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3143 (const unsigned char *)F.HeaderFileInfoTableData,
3144 HeaderFileInfoTrait(*this, F,
3145 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003146 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003147
3148 PP.getHeaderSearchInfo().SetExternalSource(this);
3149 if (!PP.getHeaderSearchInfo().getExternalLookup())
3150 PP.getHeaderSearchInfo().SetExternalLookup(this);
3151 }
3152 break;
3153 }
3154
3155 case FP_PRAGMA_OPTIONS:
3156 // Later tables overwrite earlier ones.
3157 FPPragmaOptions.swap(Record);
3158 break;
3159
3160 case OPENCL_EXTENSIONS:
3161 // Later tables overwrite earlier ones.
3162 OpenCLExtensions.swap(Record);
3163 break;
3164
3165 case TENTATIVE_DEFINITIONS:
3166 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3167 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3168 break;
3169
3170 case KNOWN_NAMESPACES:
3171 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3172 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3173 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003174
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003175 case UNDEFINED_BUT_USED:
3176 if (UndefinedButUsed.size() % 2 != 0) {
3177 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003178 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003179 }
3180
3181 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003182 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003183 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003184 }
3185 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003186 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3187 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003188 ReadSourceLocation(F, Record, I).getRawEncoding());
3189 }
3190 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003191 case DELETE_EXPRS_TO_ANALYZE:
3192 for (unsigned I = 0, N = Record.size(); I != N;) {
3193 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3194 const uint64_t Count = Record[I++];
3195 DelayedDeleteExprs.push_back(Count);
3196 for (uint64_t C = 0; C < Count; ++C) {
3197 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3198 bool IsArrayForm = Record[I++] == 1;
3199 DelayedDeleteExprs.push_back(IsArrayForm);
3200 }
3201 }
3202 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003205 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 // If we aren't loading a module (which has its own exports), make
3207 // all of the imported modules visible.
3208 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003209 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3210 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3211 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3212 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003213 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 }
3215 }
3216 break;
3217 }
3218
Guy Benyei11169dd2012-12-18 14:30:41 +00003219 case MACRO_OFFSET: {
3220 if (F.LocalNumMacros != 0) {
3221 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003222 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003224 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 F.LocalNumMacros = Record[0];
3226 unsigned LocalBaseMacroID = Record[1];
3227 F.BaseMacroID = getTotalNumMacros();
3228
3229 if (F.LocalNumMacros > 0) {
3230 // Introduce the global -> local mapping for macros within this module.
3231 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3232
3233 // Introduce the local -> global mapping for macros within this module.
3234 F.MacroRemap.insertOrReplace(
3235 std::make_pair(LocalBaseMacroID,
3236 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003237
3238 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 }
3240 break;
3241 }
3242
Richard Smithe40f2ba2013-08-07 21:41:30 +00003243 case LATE_PARSED_TEMPLATE: {
3244 LateParsedTemplates.append(Record.begin(), Record.end());
3245 break;
3246 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003247
3248 case OPTIMIZE_PRAGMA_OPTIONS:
3249 if (Record.size() != 1) {
3250 Error("invalid pragma optimize record");
3251 return Failure;
3252 }
3253 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3254 break;
Nico Weber72889432014-09-06 01:25:55 +00003255
Nico Weber779355f2016-03-02 23:22:00 +00003256 case MSSTRUCT_PRAGMA_OPTIONS:
3257 if (Record.size() != 1) {
3258 Error("invalid pragma ms_struct record");
3259 return Failure;
3260 }
3261 PragmaMSStructState = Record[0];
3262 break;
3263
Nico Weber42932312016-03-03 00:17:35 +00003264 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3265 if (Record.size() != 2) {
3266 Error("invalid pragma ms_struct record");
3267 return Failure;
3268 }
3269 PragmaMSPointersToMembersState = Record[0];
3270 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3271 break;
3272
Nico Weber72889432014-09-06 01:25:55 +00003273 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3274 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3275 UnusedLocalTypedefNameCandidates.push_back(
3276 getGlobalDeclID(F, Record[I]));
3277 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 }
3279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003280}
3281
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003282ASTReader::ASTReadResult
3283ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3284 const ModuleFile *ImportedBy,
3285 unsigned ClientLoadCapabilities) {
3286 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003287 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003288
Manman Ren11f2a472016-08-18 17:42:15 +00003289 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003290 // For an explicitly-loaded module, we don't care whether the original
3291 // module map file exists or matches.
3292 return Success;
3293 }
3294
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003295 // Try to resolve ModuleName in the current header search context and
3296 // verify that it is found in the same module map file as we saved. If the
3297 // top-level AST file is a main file, skip this check because there is no
3298 // usable header search context.
3299 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003300 "MODULE_NAME should come before MODULE_MAP_FILE");
3301 if (F.Kind == MK_ImplicitModule &&
3302 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3303 // An implicitly-loaded module file should have its module listed in some
3304 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003305 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003306 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3307 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3308 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003309 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003310 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3311 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3312 // This module was defined by an imported (explicit) module.
3313 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3314 << ASTFE->getName();
3315 else
3316 // This module was built with a different module map.
3317 Diag(diag::err_imported_module_not_found)
3318 << F.ModuleName << F.FileName << ImportedBy->FileName
3319 << F.ModuleMapPath;
3320 }
3321 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003322 }
3323
Richard Smithe842a472014-10-22 02:05:46 +00003324 assert(M->Name == F.ModuleName && "found module with different name");
3325
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003326 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003327 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003328 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3329 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003330 assert(ImportedBy && "top-level import should be verified");
3331 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3332 Diag(diag::err_imported_module_modmap_changed)
3333 << F.ModuleName << ImportedBy->FileName
3334 << ModMap->getName() << F.ModuleMapPath;
3335 return OutOfDate;
3336 }
3337
3338 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3339 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3340 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003341 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003342 const FileEntry *F =
3343 FileMgr.getFile(Filename, false, false);
3344 if (F == nullptr) {
3345 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3346 Error("could not find file '" + Filename +"' referenced by AST file");
3347 return OutOfDate;
3348 }
3349 AdditionalStoredMaps.insert(F);
3350 }
3351
3352 // Check any additional module map files (e.g. module.private.modulemap)
3353 // that are not in the pcm.
3354 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3355 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3356 // Remove files that match
3357 // Note: SmallPtrSet::erase is really remove
3358 if (!AdditionalStoredMaps.erase(ModMap)) {
3359 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3360 Diag(diag::err_module_different_modmap)
3361 << F.ModuleName << /*new*/0 << ModMap->getName();
3362 return OutOfDate;
3363 }
3364 }
3365 }
3366
3367 // Check any additional module map files that are in the pcm, but not
3368 // found in header search. Cases that match are already removed.
3369 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3370 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3371 Diag(diag::err_module_different_modmap)
3372 << F.ModuleName << /*not new*/1 << ModMap->getName();
3373 return OutOfDate;
3374 }
3375 }
3376
3377 if (Listener)
3378 Listener->ReadModuleMapFile(F.ModuleMapPath);
3379 return Success;
3380}
3381
3382
Douglas Gregorc1489562013-02-12 23:36:21 +00003383/// \brief Move the given method to the back of the global list of methods.
3384static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3385 // Find the entry for this selector in the method pool.
3386 Sema::GlobalMethodPool::iterator Known
3387 = S.MethodPool.find(Method->getSelector());
3388 if (Known == S.MethodPool.end())
3389 return;
3390
3391 // Retrieve the appropriate method list.
3392 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3393 : Known->second.second;
3394 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003395 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003396 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003397 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003398 Found = true;
3399 } else {
3400 // Keep searching.
3401 continue;
3402 }
3403 }
3404
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003405 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003406 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003407 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003408 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003409 }
3410}
3411
Richard Smithde711422015-04-23 21:20:19 +00003412void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003413 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003414 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003415 bool wasHidden = D->Hidden;
3416 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
Richard Smith49f906a2014-03-01 00:08:04 +00003418 if (wasHidden && SemaObj) {
3419 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3420 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003421 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003422 }
3423 }
3424}
3425
Richard Smith49f906a2014-03-01 00:08:04 +00003426void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003427 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003428 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003430 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003431 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003433 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003434
3435 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003436 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 // there is nothing more to do.
3438 continue;
3439 }
Richard Smith49f906a2014-03-01 00:08:04 +00003440
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 if (!Mod->isAvailable()) {
3442 // Modules that aren't available cannot be made visible.
3443 continue;
3444 }
3445
3446 // Update the module's name visibility.
3447 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003448
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 // If we've already deserialized any names from this module,
3450 // mark them as visible.
3451 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3452 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003453 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003455 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003456 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3457 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003459
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003461 SmallVector<Module *, 16> Exports;
3462 Mod->getExportedModules(Exports);
3463 for (SmallVectorImpl<Module *>::iterator
3464 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3465 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003466 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003467 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 }
3469 }
3470}
3471
Richard Smith6561f922016-09-12 21:06:40 +00003472/// We've merged the definition \p MergedDef into the existing definition
3473/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3474/// visible.
3475void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3476 NamedDecl *MergedDef) {
Eric Liu762b4882016-09-14 10:05:10 +00003477 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3478 // in modules other than its owning module. We should instead give the
3479 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003480 if (Def->isHidden()) {
3481 // If MergedDef is visible or becomes visible, make the definition visible.
Eric Liu762b4882016-09-14 10:05:10 +00003482 if (!MergedDef->isHidden())
3483 Def->Hidden = false;
3484 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3485 getContext().mergeDefinitionIntoModule(
3486 Def, MergedDef->getImportedOwningModule(),
3487 /*NotifyListeners*/ false);
3488 PendingMergedDefinitionsToDeduplicate.insert(Def);
3489 } else {
3490 auto SubmoduleID = MergedDef->getOwningModuleID();
3491 assert(SubmoduleID && "hidden definition in no module");
3492 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3493 }
Richard Smith6561f922016-09-12 21:06:40 +00003494 }
3495}
3496
Douglas Gregore060e572013-01-25 01:03:03 +00003497bool ASTReader::loadGlobalIndex() {
3498 if (GlobalIndex)
3499 return false;
3500
3501 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3502 !Context.getLangOpts().Modules)
3503 return true;
3504
3505 // Try to load the global index.
3506 TriedLoadingGlobalIndex = true;
3507 StringRef ModuleCachePath
3508 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3509 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003510 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003511 if (!Result.first)
3512 return true;
3513
3514 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003515 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003516 return false;
3517}
3518
3519bool ASTReader::isGlobalIndexUnavailable() const {
3520 return Context.getLangOpts().Modules && UseGlobalIndex &&
3521 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3522}
3523
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003524static void updateModuleTimestamp(ModuleFile &MF) {
3525 // Overwrite the timestamp file contents so that file's mtime changes.
3526 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003527 std::error_code EC;
3528 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3529 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003530 return;
3531 OS << "Timestamp file\n";
3532}
3533
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003534/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3535/// cursor into the start of the given block ID, returning false on success and
3536/// true on failure.
3537static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003538 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003539 llvm::BitstreamEntry Entry = Cursor.advance();
3540 switch (Entry.Kind) {
3541 case llvm::BitstreamEntry::Error:
3542 case llvm::BitstreamEntry::EndBlock:
3543 return true;
3544
3545 case llvm::BitstreamEntry::Record:
3546 // Ignore top-level records.
3547 Cursor.skipRecord(Entry.ID);
3548 break;
3549
3550 case llvm::BitstreamEntry::SubBlock:
3551 if (Entry.ID == BlockID) {
3552 if (Cursor.EnterSubBlock(BlockID))
3553 return true;
3554 // Found it!
3555 return false;
3556 }
3557
3558 if (Cursor.SkipBlock())
3559 return true;
3560 }
3561 }
3562}
3563
Benjamin Kramer0772c422016-02-13 13:42:54 +00003564ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 ModuleKind Type,
3566 SourceLocation ImportLoc,
3567 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003568 llvm::SaveAndRestore<SourceLocation>
3569 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3570
Richard Smithd1c46742014-04-30 02:24:17 +00003571 // Defer any pending actions until we get to the end of reading the AST file.
3572 Deserializing AnASTFile(this);
3573
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003575 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003576
3577 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003578 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003580 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003581 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 ClientLoadCapabilities)) {
3583 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003584 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 case OutOfDate:
3586 case VersionMismatch:
3587 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003588 case HadErrors: {
3589 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3590 for (const ImportedModule &IM : Loaded)
3591 LoadedSet.insert(IM.Mod);
3592
Douglas Gregor7029ce12013-03-19 00:28:20 +00003593 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003594 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003595 Context.getLangOpts().Modules
3596 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003597 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003598
3599 // If we find that any modules are unusable, the global index is going
3600 // to be out-of-date. Just remove it.
3601 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003602 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003604 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 case Success:
3606 break;
3607 }
3608
3609 // Here comes stuff that we only do once the entire chain is loaded.
3610
3611 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003612 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3613 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003614 M != MEnd; ++M) {
3615 ModuleFile &F = *M->Mod;
3616
3617 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003618 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3619 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003620
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003621 // Read the extension blocks.
3622 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3623 if (ASTReadResult Result = ReadExtensionBlock(F))
3624 return Result;
3625 }
3626
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 // Once read, set the ModuleFile bit base offset and update the size in
3628 // bits of all files we've seen.
3629 F.GlobalBitOffset = TotalModulesSizeInBits;
3630 TotalModulesSizeInBits += F.SizeInBits;
3631 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3632
3633 // Preload SLocEntries.
3634 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3635 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3636 // Load it through the SourceManager and don't call ReadSLocEntry()
3637 // directly because the entry may have already been loaded in which case
3638 // calling ReadSLocEntry() directly would trigger an assertion in
3639 // SourceManager.
3640 SourceMgr.getLoadedSLocEntryByID(Index);
3641 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003642
3643 // Preload all the pending interesting identifiers by marking them out of
3644 // date.
3645 for (auto Offset : F.PreloadIdentifierOffsets) {
3646 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3647 F.IdentifierTableData + Offset);
3648
3649 ASTIdentifierLookupTrait Trait(*this, F);
3650 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3651 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003652 auto &II = PP.getIdentifierTable().getOwn(Key);
3653 II.setOutOfDate(true);
3654
3655 // Mark this identifier as being from an AST file so that we can track
3656 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003657 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003658
3659 // Associate the ID with the identifier so that the writer can reuse it.
3660 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3661 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 }
3664
Douglas Gregor603cd862013-03-22 18:50:14 +00003665 // Setup the import locations and notify the module manager that we've
3666 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003667 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3668 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 M != MEnd; ++M) {
3670 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003671
3672 ModuleMgr.moduleFileAccepted(&F);
3673
3674 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003675 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003676 // FIXME: We assume that locations from PCH / preamble do not need
3677 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 if (!M->ImportedBy)
3679 F.ImportLoc = M->ImportLoc;
3680 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003681 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 }
3683
Richard Smith33e0f7e2015-07-22 02:08:40 +00003684 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003685 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3686 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003687 // Mark all of the identifiers in the identifier table as being out of date,
3688 // so that various accessors know to check the loaded modules when the
3689 // identifier is used.
3690 //
3691 // For C++ modules, we don't need information on many identifiers (just
3692 // those that provide macros or are poisoned), so we mark all of
3693 // the interesting ones via PreloadIdentifierOffsets.
3694 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3695 IdEnd = PP.getIdentifierTable().end();
3696 Id != IdEnd; ++Id)
3697 Id->second->setOutOfDate(true);
3698 }
Manman Rena0f31a02016-04-29 19:04:05 +00003699 // Mark selectors as out of date.
3700 for (auto Sel : SelectorGeneration)
3701 SelectorOutOfDate[Sel.first] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003702
3703 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003704 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3705 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3707 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003708
3709 switch (Unresolved.Kind) {
3710 case UnresolvedModuleRef::Conflict:
3711 if (ResolvedMod) {
3712 Module::Conflict Conflict;
3713 Conflict.Other = ResolvedMod;
3714 Conflict.Message = Unresolved.String.str();
3715 Unresolved.Mod->Conflicts.push_back(Conflict);
3716 }
3717 continue;
3718
3719 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003721 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003723
Douglas Gregorfb912652013-03-20 21:10:35 +00003724 case UnresolvedModuleRef::Export:
3725 if (ResolvedMod || Unresolved.IsWildcard)
3726 Unresolved.Mod->Exports.push_back(
3727 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3728 continue;
3729 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003731 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003732
3733 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3734 // Might be unnecessary as use declarations are only used to build the
3735 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003736
3737 InitializeContext();
3738
Richard Smith3d8e97e2013-10-18 06:54:39 +00003739 if (SemaObj)
3740 UpdateSema();
3741
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 if (DeserializationListener)
3743 DeserializationListener->ReaderInitialized(this);
3744
3745 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003746 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 PrimaryModule.OriginalSourceFileID
3748 = FileID::get(PrimaryModule.SLocEntryBaseID
3749 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3750
3751 // If this AST file is a precompiled preamble, then set the
3752 // preamble file ID of the source manager to the file source file
3753 // from which the preamble was built.
3754 if (Type == MK_Preamble) {
3755 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3756 } else if (Type == MK_MainFile) {
3757 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3758 }
3759 }
3760
3761 // For any Objective-C class definitions we have already loaded, make sure
3762 // that we load any additional categories.
3763 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3764 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3765 ObjCClassesLoaded[I],
3766 PreviousGeneration);
3767 }
Douglas Gregore060e572013-01-25 01:03:03 +00003768
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003769 if (PP.getHeaderSearchInfo()
3770 .getHeaderSearchOpts()
3771 .ModulesValidateOncePerBuildSession) {
3772 // Now we are certain that the module and all modules it depends on are
3773 // up to date. Create or update timestamp files for modules that are
3774 // located in the module cache (not for PCH files that could be anywhere
3775 // in the filesystem).
3776 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3777 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003778 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003779 updateModuleTimestamp(*M.Mod);
3780 }
3781 }
3782 }
3783
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 return Success;
3785}
3786
Ben Langmuir487ea142014-10-23 18:05:36 +00003787static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3788
Ben Langmuir70a1b812015-03-24 04:43:52 +00003789/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3790static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3791 return Stream.Read(8) == 'C' &&
3792 Stream.Read(8) == 'P' &&
3793 Stream.Read(8) == 'C' &&
3794 Stream.Read(8) == 'H';
3795}
3796
Richard Smith0f99d6a2015-08-09 08:48:41 +00003797static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3798 switch (Kind) {
3799 case MK_PCH:
3800 return 0; // PCH
3801 case MK_ImplicitModule:
3802 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003803 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003804 return 1; // module
3805 case MK_MainFile:
3806 case MK_Preamble:
3807 return 2; // main source file
3808 }
3809 llvm_unreachable("unknown module kind");
3810}
3811
Guy Benyei11169dd2012-12-18 14:30:41 +00003812ASTReader::ASTReadResult
3813ASTReader::ReadASTCore(StringRef FileName,
3814 ModuleKind Type,
3815 SourceLocation ImportLoc,
3816 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003817 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003818 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003819 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003820 unsigned ClientLoadCapabilities) {
3821 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003823 ModuleManager::AddModuleResult AddResult
3824 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003825 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003826 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003827 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003828
Douglas Gregor7029ce12013-03-19 00:28:20 +00003829 switch (AddResult) {
3830 case ModuleManager::AlreadyLoaded:
3831 return Success;
3832
3833 case ModuleManager::NewlyLoaded:
3834 // Load module file below.
3835 break;
3836
3837 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003838 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003839 // it.
3840 if (ClientLoadCapabilities & ARR_Missing)
3841 return Missing;
3842
3843 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003844 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003845 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003846 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003847 return Failure;
3848
3849 case ModuleManager::OutOfDate:
3850 // We couldn't load the module file because it is out-of-date. If the
3851 // client can handle out-of-date, return it.
3852 if (ClientLoadCapabilities & ARR_OutOfDate)
3853 return OutOfDate;
3854
3855 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003856 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003857 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003858 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 return Failure;
3860 }
3861
Douglas Gregor7029ce12013-03-19 00:28:20 +00003862 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003863
3864 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3865 // module?
3866 if (FileName != "-") {
3867 CurrentDir = llvm::sys::path::parent_path(FileName);
3868 if (CurrentDir.empty()) CurrentDir = ".";
3869 }
3870
3871 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003872 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003873 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003874 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003875 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3876
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003878 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003879 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3880 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 return Failure;
3882 }
3883
3884 // This is used for compatibility with older PCH formats.
3885 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003886 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003887 llvm::BitstreamEntry Entry = Stream.advance();
3888
3889 switch (Entry.Kind) {
3890 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003891 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003892 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 Error("invalid record at top-level of AST file");
3894 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003895
3896 case llvm::BitstreamEntry::SubBlock:
3897 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 }
3899
Chris Lattnerefa77172013-01-20 00:00:22 +00003900 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003901 case CONTROL_BLOCK_ID:
3902 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003903 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003905 // Check that we didn't try to load a non-module AST file as a module.
3906 //
3907 // FIXME: Should we also perform the converse check? Loading a module as
3908 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003909 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3910 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003911 F.ModuleName.empty()) {
3912 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3913 if (Result != OutOfDate ||
3914 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3915 Diag(diag::err_module_file_not_module) << FileName;
3916 return Result;
3917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 break;
3919
3920 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003921 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 case OutOfDate: return OutOfDate;
3923 case VersionMismatch: return VersionMismatch;
3924 case ConfigurationMismatch: return ConfigurationMismatch;
3925 case HadErrors: return HadErrors;
3926 }
3927 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003928
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 case AST_BLOCK_ID:
3930 if (!HaveReadControlBlock) {
3931 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003932 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 return VersionMismatch;
3934 }
3935
3936 // Record that we've loaded this module.
3937 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3938 return Success;
3939
3940 default:
3941 if (Stream.SkipBlock()) {
3942 Error("malformed block record in AST file");
3943 return Failure;
3944 }
3945 break;
3946 }
3947 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003948
3949 return Success;
3950}
3951
3952/// Parse a record and blob containing module file extension metadata.
3953static bool parseModuleFileExtensionMetadata(
3954 const SmallVectorImpl<uint64_t> &Record,
3955 StringRef Blob,
3956 ModuleFileExtensionMetadata &Metadata) {
3957 if (Record.size() < 4) return true;
3958
3959 Metadata.MajorVersion = Record[0];
3960 Metadata.MinorVersion = Record[1];
3961
3962 unsigned BlockNameLen = Record[2];
3963 unsigned UserInfoLen = Record[3];
3964
3965 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3966
3967 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3968 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3969 Blob.data() + BlockNameLen + UserInfoLen);
3970 return false;
3971}
3972
3973ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3974 BitstreamCursor &Stream = F.Stream;
3975
3976 RecordData Record;
3977 while (true) {
3978 llvm::BitstreamEntry Entry = Stream.advance();
3979 switch (Entry.Kind) {
3980 case llvm::BitstreamEntry::SubBlock:
3981 if (Stream.SkipBlock())
3982 return Failure;
3983
3984 continue;
3985
3986 case llvm::BitstreamEntry::EndBlock:
3987 return Success;
3988
3989 case llvm::BitstreamEntry::Error:
3990 return HadErrors;
3991
3992 case llvm::BitstreamEntry::Record:
3993 break;
3994 }
3995
3996 Record.clear();
3997 StringRef Blob;
3998 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3999 switch (RecCode) {
4000 case EXTENSION_METADATA: {
4001 ModuleFileExtensionMetadata Metadata;
4002 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4003 return Failure;
4004
4005 // Find a module file extension with this block name.
4006 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4007 if (Known == ModuleFileExtensions.end()) break;
4008
4009 // Form a reader.
4010 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4011 F, Stream)) {
4012 F.ExtensionReaders.push_back(std::move(Reader));
4013 }
4014
4015 break;
4016 }
4017 }
4018 }
4019
4020 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004021}
4022
Richard Smitha7e2cc62015-05-01 01:53:09 +00004023void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 // If there's a listener, notify them that we "read" the translation unit.
4025 if (DeserializationListener)
4026 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4027 Context.getTranslationUnitDecl());
4028
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 // FIXME: Find a better way to deal with collisions between these
4030 // built-in types. Right now, we just ignore the problem.
4031
4032 // Load the special types.
4033 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4034 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4035 if (!Context.CFConstantStringTypeDecl)
4036 Context.setCFConstantStringType(GetType(String));
4037 }
4038
4039 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4040 QualType FileType = GetType(File);
4041 if (FileType.isNull()) {
4042 Error("FILE type is NULL");
4043 return;
4044 }
4045
4046 if (!Context.FILEDecl) {
4047 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4048 Context.setFILEDecl(Typedef->getDecl());
4049 else {
4050 const TagType *Tag = FileType->getAs<TagType>();
4051 if (!Tag) {
4052 Error("Invalid FILE type in AST file");
4053 return;
4054 }
4055 Context.setFILEDecl(Tag->getDecl());
4056 }
4057 }
4058 }
4059
4060 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4061 QualType Jmp_bufType = GetType(Jmp_buf);
4062 if (Jmp_bufType.isNull()) {
4063 Error("jmp_buf type is NULL");
4064 return;
4065 }
4066
4067 if (!Context.jmp_bufDecl) {
4068 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4069 Context.setjmp_bufDecl(Typedef->getDecl());
4070 else {
4071 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4072 if (!Tag) {
4073 Error("Invalid jmp_buf type in AST file");
4074 return;
4075 }
4076 Context.setjmp_bufDecl(Tag->getDecl());
4077 }
4078 }
4079 }
4080
4081 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4082 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4083 if (Sigjmp_bufType.isNull()) {
4084 Error("sigjmp_buf type is NULL");
4085 return;
4086 }
4087
4088 if (!Context.sigjmp_bufDecl) {
4089 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4090 Context.setsigjmp_bufDecl(Typedef->getDecl());
4091 else {
4092 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4093 assert(Tag && "Invalid sigjmp_buf type in AST file");
4094 Context.setsigjmp_bufDecl(Tag->getDecl());
4095 }
4096 }
4097 }
4098
4099 if (unsigned ObjCIdRedef
4100 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4101 if (Context.ObjCIdRedefinitionType.isNull())
4102 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4103 }
4104
4105 if (unsigned ObjCClassRedef
4106 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4107 if (Context.ObjCClassRedefinitionType.isNull())
4108 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4109 }
4110
4111 if (unsigned ObjCSelRedef
4112 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4113 if (Context.ObjCSelRedefinitionType.isNull())
4114 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4115 }
4116
4117 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4118 QualType Ucontext_tType = GetType(Ucontext_t);
4119 if (Ucontext_tType.isNull()) {
4120 Error("ucontext_t type is NULL");
4121 return;
4122 }
4123
4124 if (!Context.ucontext_tDecl) {
4125 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4126 Context.setucontext_tDecl(Typedef->getDecl());
4127 else {
4128 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4129 assert(Tag && "Invalid ucontext_t type in AST file");
4130 Context.setucontext_tDecl(Tag->getDecl());
4131 }
4132 }
4133 }
4134 }
4135
4136 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4137
4138 // If there were any CUDA special declarations, deserialize them.
4139 if (!CUDASpecialDeclRefs.empty()) {
4140 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4141 Context.setcudaConfigureCallDecl(
4142 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4143 }
Richard Smith56be7542014-03-21 00:33:59 +00004144
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004146 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004147 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004148 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004149 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004150 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004151 if (Import.ImportLoc.isValid())
4152 PP.makeModuleVisible(Imported, Import.ImportLoc);
4153 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 }
4156 ImportedModules.clear();
4157}
4158
4159void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004160 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004161}
4162
Ben Langmuir70a1b812015-03-24 04:43:52 +00004163/// \brief Reads and return the signature record from \p StreamFile's control
4164/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004165static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4166 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004167 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004168 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004169
4170 // Scan for the CONTROL_BLOCK_ID block.
4171 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4172 return 0;
4173
4174 // Scan for SIGNATURE inside the control block.
4175 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004176 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004177 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4178 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4179 Entry.Kind != llvm::BitstreamEntry::Record)
4180 return 0;
4181
4182 Record.clear();
4183 StringRef Blob;
4184 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4185 return Record[0];
4186 }
4187}
4188
Guy Benyei11169dd2012-12-18 14:30:41 +00004189/// \brief Retrieve the name of the original source file name
4190/// directly from the AST file, without actually loading the AST
4191/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004192std::string ASTReader::getOriginalSourceFile(
4193 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004194 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004196 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004198 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4199 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 return std::string();
4201 }
4202
4203 // Initialize the stream
4204 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004205 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004206 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004207
4208 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004209 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4211 return std::string();
4212 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213
Chris Lattnere7b154b2013-01-19 21:39:22 +00004214 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004215 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004216 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4217 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004218 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004219
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004220 // Scan for ORIGINAL_FILE inside the control block.
4221 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004222 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004223 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004224 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4225 return std::string();
4226
4227 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4228 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4229 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004231
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004233 StringRef Blob;
4234 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4235 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004237}
4238
4239namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004240
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 class SimplePCHValidator : public ASTReaderListener {
4242 const LangOptions &ExistingLangOpts;
4243 const TargetOptions &ExistingTargetOpts;
4244 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004245 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004247
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 public:
4249 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4250 const TargetOptions &ExistingTargetOpts,
4251 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004252 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 FileManager &FileMgr)
4254 : ExistingLangOpts(ExistingLangOpts),
4255 ExistingTargetOpts(ExistingTargetOpts),
4256 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004257 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 FileMgr(FileMgr)
4259 {
4260 }
4261
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004262 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4263 bool AllowCompatibleDifferences) override {
4264 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4265 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004267
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004268 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4269 bool AllowCompatibleDifferences) override {
4270 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4271 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004273
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004274 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4275 StringRef SpecificModuleCachePath,
4276 bool Complain) override {
4277 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4278 ExistingModuleCachePath,
4279 nullptr, ExistingLangOpts);
4280 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004281
Craig Topper3e89dfe2014-03-13 02:13:41 +00004282 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4283 bool Complain,
4284 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004285 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004286 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 }
4288 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004289
4290} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004291
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004292bool ASTReader::readASTFileControlBlock(
4293 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004294 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004295 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004296 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004298 // FIXME: This allows use of the VFS; we do not allow use of the
4299 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004300 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 if (!Buffer) {
4302 return true;
4303 }
4304
4305 // Initialize the stream
4306 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004307 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004308 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004309
4310 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004311 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004314 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004315 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004316 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004317
4318 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004319 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004320 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004321 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004322
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004324 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004325 bool DoneWithControlBlock = false;
4326 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004327 llvm::BitstreamEntry Entry = Stream.advance();
4328
4329 switch (Entry.Kind) {
4330 case llvm::BitstreamEntry::SubBlock: {
4331 switch (Entry.ID) {
4332 case OPTIONS_BLOCK_ID: {
4333 std::string IgnoredSuggestedPredefines;
4334 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4335 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004336 Listener, IgnoredSuggestedPredefines,
4337 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004338 return true;
4339 break;
4340 }
4341
4342 case INPUT_FILES_BLOCK_ID:
4343 InputFilesCursor = Stream;
4344 if (Stream.SkipBlock() ||
4345 (NeedsInputFiles &&
4346 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4347 return true;
4348 break;
4349
4350 default:
4351 if (Stream.SkipBlock())
4352 return true;
4353 break;
4354 }
4355
4356 continue;
4357 }
4358
4359 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004360 DoneWithControlBlock = true;
4361 break;
Richard Smith0516b182015-09-08 19:40:14 +00004362
4363 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004364 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004365
4366 case llvm::BitstreamEntry::Record:
4367 break;
4368 }
4369
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004370 if (DoneWithControlBlock) break;
4371
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004373 StringRef Blob;
4374 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004375 switch ((ControlRecordTypes)RecCode) {
4376 case METADATA: {
4377 if (Record[0] != VERSION_MAJOR)
4378 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004379
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004380 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004381 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004382
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004383 break;
4384 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004385 case MODULE_NAME:
4386 Listener.ReadModuleName(Blob);
4387 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004388 case MODULE_DIRECTORY:
4389 ModuleDir = Blob;
4390 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004391 case MODULE_MAP_FILE: {
4392 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004393 auto Path = ReadString(Record, Idx);
4394 ResolveImportedPath(Path, ModuleDir);
4395 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004396 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004397 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004398 case INPUT_FILE_OFFSETS: {
4399 if (!NeedsInputFiles)
4400 break;
4401
4402 unsigned NumInputFiles = Record[0];
4403 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004404 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004405 for (unsigned I = 0; I != NumInputFiles; ++I) {
4406 // Go find this input file.
4407 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004408
4409 if (isSystemFile && !NeedsSystemInputFiles)
4410 break; // the rest are system input files
4411
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004412 BitstreamCursor &Cursor = InputFilesCursor;
4413 SavedStreamPosition SavedPosition(Cursor);
4414 Cursor.JumpToBit(InputFileOffs[I]);
4415
4416 unsigned Code = Cursor.ReadCode();
4417 RecordData Record;
4418 StringRef Blob;
4419 bool shouldContinue = false;
4420 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4421 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004422 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004423 std::string Filename = Blob;
4424 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004425 shouldContinue = Listener.visitInputFile(
4426 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004427 break;
4428 }
4429 if (!shouldContinue)
4430 break;
4431 }
4432 break;
4433 }
4434
Richard Smithd4b230b2014-10-27 23:01:16 +00004435 case IMPORTS: {
4436 if (!NeedsImports)
4437 break;
4438
4439 unsigned Idx = 0, N = Record.size();
4440 while (Idx < N) {
4441 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004442 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004443 std::string Filename = ReadString(Record, Idx);
4444 ResolveImportedPath(Filename, ModuleDir);
4445 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004446 }
4447 break;
4448 }
4449
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004450 default:
4451 // No other validation to perform.
4452 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004455
4456 // Look for module file extension blocks, if requested.
4457 if (FindModuleFileExtensions) {
4458 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4459 bool DoneWithExtensionBlock = false;
4460 while (!DoneWithExtensionBlock) {
4461 llvm::BitstreamEntry Entry = Stream.advance();
4462
4463 switch (Entry.Kind) {
4464 case llvm::BitstreamEntry::SubBlock:
4465 if (Stream.SkipBlock())
4466 return true;
4467
4468 continue;
4469
4470 case llvm::BitstreamEntry::EndBlock:
4471 DoneWithExtensionBlock = true;
4472 continue;
4473
4474 case llvm::BitstreamEntry::Error:
4475 return true;
4476
4477 case llvm::BitstreamEntry::Record:
4478 break;
4479 }
4480
4481 Record.clear();
4482 StringRef Blob;
4483 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4484 switch (RecCode) {
4485 case EXTENSION_METADATA: {
4486 ModuleFileExtensionMetadata Metadata;
4487 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4488 return true;
4489
4490 Listener.readModuleFileExtension(Metadata);
4491 break;
4492 }
4493 }
4494 }
4495 }
4496 }
4497
4498 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499}
4500
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004501bool ASTReader::isAcceptableASTFile(
4502 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004503 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004504 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4505 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004506 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4507 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004508 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004509 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004510 validator,
4511 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004512}
4513
Ben Langmuir2c9af442014-04-10 17:57:43 +00004514ASTReader::ASTReadResult
4515ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 // Enter the submodule block.
4517 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4518 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004519 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4523 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004524 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 RecordData Record;
4526 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004527 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4528
4529 switch (Entry.Kind) {
4530 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4531 case llvm::BitstreamEntry::Error:
4532 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004533 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004534 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004535 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004536 case llvm::BitstreamEntry::Record:
4537 // The interesting case.
4538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004540
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004542 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004544 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4545
4546 if ((Kind == SUBMODULE_METADATA) != First) {
4547 Error("submodule metadata record should be at beginning of block");
4548 return Failure;
4549 }
4550 First = false;
4551
4552 // Submodule information is only valid if we have a current module.
4553 // FIXME: Should we error on these cases?
4554 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4555 Kind != SUBMODULE_DEFINITION)
4556 continue;
4557
4558 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 default: // Default behavior: ignore.
4560 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004561
Richard Smith03478d92014-10-23 22:12:14 +00004562 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004563 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004565 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
Richard Smith03478d92014-10-23 22:12:14 +00004567
Chris Lattner0e6c9402013-01-20 02:38:54 +00004568 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004569 unsigned Idx = 0;
4570 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4571 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4572 bool IsFramework = Record[Idx++];
4573 bool IsExplicit = Record[Idx++];
4574 bool IsSystem = Record[Idx++];
4575 bool IsExternC = Record[Idx++];
4576 bool InferSubmodules = Record[Idx++];
4577 bool InferExplicitSubmodules = Record[Idx++];
4578 bool InferExportWildcard = Record[Idx++];
4579 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004580
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004581 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004582 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004584
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 // Retrieve this (sub)module from the module map, creating it if
4586 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004587 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004589
4590 // FIXME: set the definition loc for CurrentModule, or call
4591 // ModMap.setInferredModuleAllowedBy()
4592
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4594 if (GlobalIndex >= SubmodulesLoaded.size() ||
4595 SubmodulesLoaded[GlobalIndex]) {
4596 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004599
Douglas Gregor7029ce12013-03-19 00:28:20 +00004600 if (!ParentModule) {
4601 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4602 if (CurFile != F.File) {
4603 if (!Diags.isDiagnosticInFlight()) {
4604 Diag(diag::err_module_file_conflict)
4605 << CurrentModule->getTopLevelModuleName()
4606 << CurFile->getName()
4607 << F.File->getName();
4608 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004609 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004610 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004611 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004612
4613 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004614 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004615
Adrian Prantl15bcf702015-06-30 17:39:43 +00004616 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 CurrentModule->IsFromModuleFile = true;
4618 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004619 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 CurrentModule->InferSubmodules = InferSubmodules;
4621 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4622 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004623 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 if (DeserializationListener)
4625 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4626
4627 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004628
Richard Smith8a3e39a2016-03-28 21:31:09 +00004629 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004630 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004631 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004632 CurrentModule->UnresolvedConflicts.clear();
4633 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004634
4635 // The module is available unless it's missing a requirement; relevant
4636 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4637 // Missing headers that were present when the module was built do not
4638 // make it unavailable -- if we got this far, this must be an explicitly
4639 // imported module file.
4640 CurrentModule->Requirements.clear();
4641 CurrentModule->MissingHeaders.clear();
4642 CurrentModule->IsMissingRequirement =
4643 ParentModule && ParentModule->IsMissingRequirement;
4644 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 break;
4646 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004647
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004649 std::string Filename = Blob;
4650 ResolveImportedPath(F, Filename);
4651 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004653 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4654 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004655 // This can be a spurious difference caused by changing the VFS to
4656 // point to a different copy of the file, and it is too late to
4657 // to rebuild safely.
4658 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4659 // after input file validation only real problems would remain and we
4660 // could just error. For now, assume it's okay.
4661 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 }
4663 }
4664 break;
4665 }
4666
Richard Smith202210b2014-10-24 20:23:01 +00004667 case SUBMODULE_HEADER:
4668 case SUBMODULE_EXCLUDED_HEADER:
4669 case SUBMODULE_PRIVATE_HEADER:
4670 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004671 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4672 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004673 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004674
Richard Smith202210b2014-10-24 20:23:01 +00004675 case SUBMODULE_TEXTUAL_HEADER:
4676 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4677 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4678 // them here.
4679 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004680
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004682 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 break;
4684 }
4685
4686 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004687 std::string Dirname = Blob;
4688 ResolveImportedPath(F, Dirname);
4689 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004691 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4692 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004693 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4694 Error("mismatched umbrella directories in submodule");
4695 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 }
4697 }
4698 break;
4699 }
4700
4701 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 F.BaseSubmoduleID = getTotalNumSubmodules();
4703 F.LocalNumSubmodules = Record[0];
4704 unsigned LocalBaseSubmoduleID = Record[1];
4705 if (F.LocalNumSubmodules > 0) {
4706 // Introduce the global -> local mapping for submodules within this
4707 // module.
4708 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4709
4710 // Introduce the local -> global mapping for submodules within this
4711 // module.
4712 F.SubmoduleRemap.insertOrReplace(
4713 std::make_pair(LocalBaseSubmoduleID,
4714 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004715
Ben Langmuir52ca6782014-10-20 16:27:32 +00004716 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4717 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 break;
4719 }
4720
4721 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004723 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 Unresolved.File = &F;
4725 Unresolved.Mod = CurrentModule;
4726 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004727 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004729 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 }
4731 break;
4732 }
4733
4734 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004736 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 Unresolved.File = &F;
4738 Unresolved.Mod = CurrentModule;
4739 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004740 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004742 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 }
4744
4745 // Once we've loaded the set of exports, there's no reason to keep
4746 // the parsed, unresolved exports around.
4747 CurrentModule->UnresolvedExports.clear();
4748 break;
4749 }
4750 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004751 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 Context.getTargetInfo());
4753 break;
4754 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004755
4756 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004757 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004758 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004759 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004760
4761 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004762 CurrentModule->ConfigMacros.push_back(Blob.str());
4763 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004764
4765 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004766 UnresolvedModuleRef Unresolved;
4767 Unresolved.File = &F;
4768 Unresolved.Mod = CurrentModule;
4769 Unresolved.ID = Record[0];
4770 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4771 Unresolved.IsWildcard = false;
4772 Unresolved.String = Blob;
4773 UnresolvedModuleRefs.push_back(Unresolved);
4774 break;
4775 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004776
4777 case SUBMODULE_INITIALIZERS:
4778 SmallVector<uint32_t, 16> Inits;
4779 for (auto &ID : Record)
4780 Inits.push_back(getGlobalDeclID(F, ID));
4781 Context.addLazyModuleInitializers(CurrentModule, Inits);
4782 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 }
4784 }
4785}
4786
4787/// \brief Parse the record that corresponds to a LangOptions data
4788/// structure.
4789///
4790/// This routine parses the language options from the AST file and then gives
4791/// them to the AST listener if one is set.
4792///
4793/// \returns true if the listener deems the file unacceptable, false otherwise.
4794bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4795 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004796 ASTReaderListener &Listener,
4797 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 LangOptions LangOpts;
4799 unsigned Idx = 0;
4800#define LANGOPT(Name, Bits, Default, Description) \
4801 LangOpts.Name = Record[Idx++];
4802#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4803 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4804#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004805#define SANITIZER(NAME, ID) \
4806 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004807#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004808
Ben Langmuircd98cb72015-06-23 18:20:18 +00004809 for (unsigned N = Record[Idx++]; N; --N)
4810 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4811
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4813 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4814 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004815
Ben Langmuird4a667a2015-06-23 18:20:23 +00004816 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004817
4818 // Comment options.
4819 for (unsigned N = Record[Idx++]; N; --N) {
4820 LangOpts.CommentOpts.BlockCommandNames.push_back(
4821 ReadString(Record, Idx));
4822 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004823 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004824
Samuel Antaoee8fb302016-01-06 13:42:12 +00004825 // OpenMP offloading options.
4826 for (unsigned N = Record[Idx++]; N; --N) {
4827 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4828 }
4829
4830 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4831
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004832 return Listener.ReadLanguageOptions(LangOpts, Complain,
4833 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004834}
4835
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004836bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4837 ASTReaderListener &Listener,
4838 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 unsigned Idx = 0;
4840 TargetOptions TargetOpts;
4841 TargetOpts.Triple = ReadString(Record, Idx);
4842 TargetOpts.CPU = ReadString(Record, Idx);
4843 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 for (unsigned N = Record[Idx++]; N; --N) {
4845 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4846 }
4847 for (unsigned N = Record[Idx++]; N; --N) {
4848 TargetOpts.Features.push_back(ReadString(Record, Idx));
4849 }
4850
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004851 return Listener.ReadTargetOptions(TargetOpts, Complain,
4852 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004853}
4854
4855bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4856 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004857 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004859#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004860#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004861 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004862#include "clang/Basic/DiagnosticOptions.def"
4863
Richard Smith3be1cb22014-08-07 00:24:21 +00004864 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004865 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004866 for (unsigned N = Record[Idx++]; N; --N)
4867 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004868
4869 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4870}
4871
4872bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4873 ASTReaderListener &Listener) {
4874 FileSystemOptions FSOpts;
4875 unsigned Idx = 0;
4876 FSOpts.WorkingDir = ReadString(Record, Idx);
4877 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4878}
4879
4880bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4881 bool Complain,
4882 ASTReaderListener &Listener) {
4883 HeaderSearchOptions HSOpts;
4884 unsigned Idx = 0;
4885 HSOpts.Sysroot = ReadString(Record, Idx);
4886
4887 // Include entries.
4888 for (unsigned N = Record[Idx++]; N; --N) {
4889 std::string Path = ReadString(Record, Idx);
4890 frontend::IncludeDirGroup Group
4891 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 bool IsFramework = Record[Idx++];
4893 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004894 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4895 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 }
4897
4898 // System header prefixes.
4899 for (unsigned N = Record[Idx++]; N; --N) {
4900 std::string Prefix = ReadString(Record, Idx);
4901 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004902 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 }
4904
4905 HSOpts.ResourceDir = ReadString(Record, Idx);
4906 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004907 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 HSOpts.DisableModuleHash = Record[Idx++];
4909 HSOpts.UseBuiltinIncludes = Record[Idx++];
4910 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4911 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4912 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004913 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004914
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004915 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4916 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004917}
4918
4919bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4920 bool Complain,
4921 ASTReaderListener &Listener,
4922 std::string &SuggestedPredefines) {
4923 PreprocessorOptions PPOpts;
4924 unsigned Idx = 0;
4925
4926 // Macro definitions/undefs
4927 for (unsigned N = Record[Idx++]; N; --N) {
4928 std::string Macro = ReadString(Record, Idx);
4929 bool IsUndef = Record[Idx++];
4930 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4931 }
4932
4933 // Includes
4934 for (unsigned N = Record[Idx++]; N; --N) {
4935 PPOpts.Includes.push_back(ReadString(Record, Idx));
4936 }
4937
4938 // Macro Includes
4939 for (unsigned N = Record[Idx++]; N; --N) {
4940 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4941 }
4942
4943 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004944 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4946 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4947 PPOpts.ObjCXXARCStandardLibrary =
4948 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4949 SuggestedPredefines.clear();
4950 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4951 SuggestedPredefines);
4952}
4953
4954std::pair<ModuleFile *, unsigned>
4955ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4956 GlobalPreprocessedEntityMapType::iterator
4957 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4958 assert(I != GlobalPreprocessedEntityMap.end() &&
4959 "Corrupted global preprocessed entity map");
4960 ModuleFile *M = I->second;
4961 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4962 return std::make_pair(M, LocalIndex);
4963}
4964
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004965llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004966ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4967 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4968 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4969 Mod.NumPreprocessedEntities);
4970
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004971 return llvm::make_range(PreprocessingRecord::iterator(),
4972 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004973}
4974
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004975llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004976ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004977 return llvm::make_range(
4978 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4979 ModuleDeclIterator(this, &Mod,
4980 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004981}
4982
4983PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4984 PreprocessedEntityID PPID = Index+1;
4985 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4986 ModuleFile &M = *PPInfo.first;
4987 unsigned LocalIndex = PPInfo.second;
4988 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4989
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 if (!PP.getPreprocessingRecord()) {
4991 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004992 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
4994
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004995 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4996 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4997
4998 llvm::BitstreamEntry Entry =
4999 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5000 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005001 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005002
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005004 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5005 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005007 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 RecordData Record;
5009 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005010 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5011 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 switch (RecType) {
5013 case PPD_MACRO_EXPANSION: {
5014 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005015 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005016 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 if (isBuiltin)
5018 Name = getLocalIdentifier(M, Record[1]);
5019 else {
Richard Smith66a81862015-05-04 02:25:31 +00005020 PreprocessedEntityID GlobalID =
5021 getGlobalPreprocessedEntityID(M, Record[1]);
5022 Def = cast<MacroDefinitionRecord>(
5023 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 }
5025
5026 MacroExpansion *ME;
5027 if (isBuiltin)
5028 ME = new (PPRec) MacroExpansion(Name, Range);
5029 else
5030 ME = new (PPRec) MacroExpansion(Def, Range);
5031
5032 return ME;
5033 }
5034
5035 case PPD_MACRO_DEFINITION: {
5036 // Decode the identifier info and then check again; if the macro is
5037 // still defined and associated with the identifier,
5038 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005039 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005040
5041 if (DeserializationListener)
5042 DeserializationListener->MacroDefinitionRead(PPID, MD);
5043
5044 return MD;
5045 }
5046
5047 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005048 const char *FullFileNameStart = Blob.data() + Record[0];
5049 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005050 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 if (!FullFileName.empty())
5052 File = PP.getFileManager().getFile(FullFileName);
5053
5054 // FIXME: Stable encoding
5055 InclusionDirective::InclusionKind Kind
5056 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5057 InclusionDirective *ID
5058 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005059 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 Record[1], Record[3],
5061 File,
5062 Range);
5063 return ID;
5064 }
5065 }
5066
5067 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5068}
5069
5070/// \brief \arg SLocMapI points at a chunk of a module that contains no
5071/// preprocessed entities or the entities it contains are not the ones we are
5072/// looking for. Find the next module that contains entities and return the ID
5073/// of the first entry.
5074PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5075 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5076 ++SLocMapI;
5077 for (GlobalSLocOffsetMapType::const_iterator
5078 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5079 ModuleFile &M = *SLocMapI->second;
5080 if (M.NumPreprocessedEntities)
5081 return M.BasePreprocessedEntityID;
5082 }
5083
5084 return getTotalNumPreprocessedEntities();
5085}
5086
5087namespace {
5088
Guy Benyei11169dd2012-12-18 14:30:41 +00005089struct PPEntityComp {
5090 const ASTReader &Reader;
5091 ModuleFile &M;
5092
5093 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5094
5095 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5096 SourceLocation LHS = getLoc(L);
5097 SourceLocation RHS = getLoc(R);
5098 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5099 }
5100
5101 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5102 SourceLocation LHS = getLoc(L);
5103 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5104 }
5105
5106 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5107 SourceLocation RHS = getLoc(R);
5108 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5109 }
5110
5111 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005112 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 }
5114};
5115
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005116} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005117
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005118PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5119 bool EndsAfter) const {
5120 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 return getTotalNumPreprocessedEntities();
5122
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005123 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5124 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5126 "Corrupted global sloc offset map");
5127
5128 if (SLocMapI->second->NumPreprocessedEntities == 0)
5129 return findNextPreprocessedEntity(SLocMapI);
5130
5131 ModuleFile &M = *SLocMapI->second;
5132 typedef const PPEntityOffset *pp_iterator;
5133 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5134 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5135
5136 size_t Count = M.NumPreprocessedEntities;
5137 size_t Half;
5138 pp_iterator First = pp_begin;
5139 pp_iterator PPI;
5140
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005141 if (EndsAfter) {
5142 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005143 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005144 } else {
5145 // Do a binary search manually instead of using std::lower_bound because
5146 // The end locations of entities may be unordered (when a macro expansion
5147 // is inside another macro argument), but for this case it is not important
5148 // whether we get the first macro expansion or its containing macro.
5149 while (Count > 0) {
5150 Half = Count / 2;
5151 PPI = First;
5152 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005153 if (SourceMgr.isBeforeInTranslationUnit(
5154 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005155 First = PPI;
5156 ++First;
5157 Count = Count - Half - 1;
5158 } else
5159 Count = Half;
5160 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 }
5162
5163 if (PPI == pp_end)
5164 return findNextPreprocessedEntity(SLocMapI);
5165
5166 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5167}
5168
Guy Benyei11169dd2012-12-18 14:30:41 +00005169/// \brief Returns a pair of [Begin, End) indices of preallocated
5170/// preprocessed entities that \arg Range encompasses.
5171std::pair<unsigned, unsigned>
5172 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5173 if (Range.isInvalid())
5174 return std::make_pair(0,0);
5175 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5176
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005177 PreprocessedEntityID BeginID =
5178 findPreprocessedEntity(Range.getBegin(), false);
5179 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 return std::make_pair(BeginID, EndID);
5181}
5182
5183/// \brief Optionally returns true or false if the preallocated preprocessed
5184/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005185Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 FileID FID) {
5187 if (FID.isInvalid())
5188 return false;
5189
5190 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5191 ModuleFile &M = *PPInfo.first;
5192 unsigned LocalIndex = PPInfo.second;
5193 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5194
Richard Smithcb34bd32016-03-27 07:28:06 +00005195 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 if (Loc.isInvalid())
5197 return false;
5198
5199 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5200 return true;
5201 else
5202 return false;
5203}
5204
5205namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005206
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 /// \brief Visitor used to search for information about a header file.
5208 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 const FileEntry *FE;
5210
David Blaikie05785d12013-02-20 22:23:23 +00005211 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005212
5213 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005214 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5215 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005216
5217 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 HeaderFileInfoLookupTable *Table
5219 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5220 if (!Table)
5221 return false;
5222
5223 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005224 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 if (Pos == Table->end())
5226 return false;
5227
Richard Smithbdf2d932015-07-30 03:37:16 +00005228 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 return true;
5230 }
5231
David Blaikie05785d12013-02-20 22:23:23 +00005232 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005234
5235} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005236
5237HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005238 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005239 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005240 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005242
5243 return HeaderFileInfo();
5244}
5245
5246void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5247 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005248 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5250 ModuleFile &F = *(*I);
5251 unsigned Idx = 0;
5252 DiagStates.clear();
5253 assert(!Diag.DiagStates.empty());
5254 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5255 while (Idx < F.PragmaDiagMappings.size()) {
5256 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5257 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5258 if (DiagStateID != 0) {
5259 Diag.DiagStatePoints.push_back(
5260 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5261 FullSourceLoc(Loc, SourceMgr)));
5262 continue;
5263 }
5264
5265 assert(DiagStateID == 0);
5266 // A new DiagState was created here.
5267 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5268 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5269 DiagStates.push_back(NewState);
5270 Diag.DiagStatePoints.push_back(
5271 DiagnosticsEngine::DiagStatePoint(NewState,
5272 FullSourceLoc(Loc, SourceMgr)));
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005273 while (true) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 assert(Idx < F.PragmaDiagMappings.size() &&
5275 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5276 if (Idx >= F.PragmaDiagMappings.size()) {
5277 break; // Something is messed up but at least avoid infinite loop in
5278 // release build.
5279 }
5280 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5281 if (DiagID == (unsigned)-1) {
5282 break; // no more diag/map pairs for this location.
5283 }
Alp Tokerc726c362014-06-10 09:31:37 +00005284 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5285 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5286 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 }
5288 }
5289 }
5290}
5291
5292/// \brief Get the correct cursor and offset for loading a type.
5293ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5294 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5295 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5296 ModuleFile *M = I->second;
5297 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5298}
5299
5300/// \brief Read and return the type with the given index..
5301///
5302/// The index is the type ID, shifted and minus the number of predefs. This
5303/// routine actually reads the record corresponding to the type at the given
5304/// location. It is a helper routine for GetType, which deals with reading type
5305/// IDs.
5306QualType ASTReader::readTypeRecord(unsigned Index) {
5307 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005308 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005309
5310 // Keep track of where we are in the stream, then jump back there
5311 // after reading this type.
5312 SavedStreamPosition SavedPosition(DeclsCursor);
5313
5314 ReadingKindTracker ReadingKind(Read_Type, *this);
5315
5316 // Note that we are loading a type record.
5317 Deserializing AType(this);
5318
5319 unsigned Idx = 0;
5320 DeclsCursor.JumpToBit(Loc.Offset);
5321 RecordData Record;
5322 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005323 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case TYPE_EXT_QUAL: {
5325 if (Record.size() != 2) {
5326 Error("Incorrect encoding of extended qualifier type");
5327 return QualType();
5328 }
5329 QualType Base = readType(*Loc.F, Record, Idx);
5330 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5331 return Context.getQualifiedType(Base, Quals);
5332 }
5333
5334 case TYPE_COMPLEX: {
5335 if (Record.size() != 1) {
5336 Error("Incorrect encoding of complex type");
5337 return QualType();
5338 }
5339 QualType ElemType = readType(*Loc.F, Record, Idx);
5340 return Context.getComplexType(ElemType);
5341 }
5342
5343 case TYPE_POINTER: {
5344 if (Record.size() != 1) {
5345 Error("Incorrect encoding of pointer type");
5346 return QualType();
5347 }
5348 QualType PointeeType = readType(*Loc.F, Record, Idx);
5349 return Context.getPointerType(PointeeType);
5350 }
5351
Reid Kleckner8a365022013-06-24 17:51:48 +00005352 case TYPE_DECAYED: {
5353 if (Record.size() != 1) {
5354 Error("Incorrect encoding of decayed type");
5355 return QualType();
5356 }
5357 QualType OriginalType = readType(*Loc.F, Record, Idx);
5358 QualType DT = Context.getAdjustedParameterType(OriginalType);
5359 if (!isa<DecayedType>(DT))
5360 Error("Decayed type does not decay");
5361 return DT;
5362 }
5363
Reid Kleckner0503a872013-12-05 01:23:43 +00005364 case TYPE_ADJUSTED: {
5365 if (Record.size() != 2) {
5366 Error("Incorrect encoding of adjusted type");
5367 return QualType();
5368 }
5369 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5370 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5371 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5372 }
5373
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 case TYPE_BLOCK_POINTER: {
5375 if (Record.size() != 1) {
5376 Error("Incorrect encoding of block pointer type");
5377 return QualType();
5378 }
5379 QualType PointeeType = readType(*Loc.F, Record, Idx);
5380 return Context.getBlockPointerType(PointeeType);
5381 }
5382
5383 case TYPE_LVALUE_REFERENCE: {
5384 if (Record.size() != 2) {
5385 Error("Incorrect encoding of lvalue reference type");
5386 return QualType();
5387 }
5388 QualType PointeeType = readType(*Loc.F, Record, Idx);
5389 return Context.getLValueReferenceType(PointeeType, Record[1]);
5390 }
5391
5392 case TYPE_RVALUE_REFERENCE: {
5393 if (Record.size() != 1) {
5394 Error("Incorrect encoding of rvalue reference type");
5395 return QualType();
5396 }
5397 QualType PointeeType = readType(*Loc.F, Record, Idx);
5398 return Context.getRValueReferenceType(PointeeType);
5399 }
5400
5401 case TYPE_MEMBER_POINTER: {
5402 if (Record.size() != 2) {
5403 Error("Incorrect encoding of member pointer type");
5404 return QualType();
5405 }
5406 QualType PointeeType = readType(*Loc.F, Record, Idx);
5407 QualType ClassType = readType(*Loc.F, Record, Idx);
5408 if (PointeeType.isNull() || ClassType.isNull())
5409 return QualType();
5410
5411 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5412 }
5413
5414 case TYPE_CONSTANT_ARRAY: {
5415 QualType ElementType = readType(*Loc.F, Record, Idx);
5416 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5417 unsigned IndexTypeQuals = Record[2];
5418 unsigned Idx = 3;
5419 llvm::APInt Size = ReadAPInt(Record, Idx);
5420 return Context.getConstantArrayType(ElementType, Size,
5421 ASM, IndexTypeQuals);
5422 }
5423
5424 case TYPE_INCOMPLETE_ARRAY: {
5425 QualType ElementType = readType(*Loc.F, Record, Idx);
5426 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5427 unsigned IndexTypeQuals = Record[2];
5428 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5429 }
5430
5431 case TYPE_VARIABLE_ARRAY: {
5432 QualType ElementType = readType(*Loc.F, Record, Idx);
5433 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5434 unsigned IndexTypeQuals = Record[2];
5435 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5436 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5437 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5438 ASM, IndexTypeQuals,
5439 SourceRange(LBLoc, RBLoc));
5440 }
5441
5442 case TYPE_VECTOR: {
5443 if (Record.size() != 3) {
5444 Error("incorrect encoding of vector type in AST file");
5445 return QualType();
5446 }
5447
5448 QualType ElementType = readType(*Loc.F, Record, Idx);
5449 unsigned NumElements = Record[1];
5450 unsigned VecKind = Record[2];
5451 return Context.getVectorType(ElementType, NumElements,
5452 (VectorType::VectorKind)VecKind);
5453 }
5454
5455 case TYPE_EXT_VECTOR: {
5456 if (Record.size() != 3) {
5457 Error("incorrect encoding of extended vector type in AST file");
5458 return QualType();
5459 }
5460
5461 QualType ElementType = readType(*Loc.F, Record, Idx);
5462 unsigned NumElements = Record[1];
5463 return Context.getExtVectorType(ElementType, NumElements);
5464 }
5465
5466 case TYPE_FUNCTION_NO_PROTO: {
5467 if (Record.size() != 6) {
5468 Error("incorrect encoding of no-proto function type");
5469 return QualType();
5470 }
5471 QualType ResultType = readType(*Loc.F, Record, Idx);
5472 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5473 (CallingConv)Record[4], Record[5]);
5474 return Context.getFunctionNoProtoType(ResultType, Info);
5475 }
5476
5477 case TYPE_FUNCTION_PROTO: {
5478 QualType ResultType = readType(*Loc.F, Record, Idx);
5479
5480 FunctionProtoType::ExtProtoInfo EPI;
5481 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5482 /*hasregparm*/ Record[2],
5483 /*regparm*/ Record[3],
5484 static_cast<CallingConv>(Record[4]),
5485 /*produces*/ Record[5]);
5486
5487 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005488
5489 EPI.Variadic = Record[Idx++];
5490 EPI.HasTrailingReturn = Record[Idx++];
5491 EPI.TypeQuals = Record[Idx++];
5492 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005493 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005494 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005495
5496 unsigned NumParams = Record[Idx++];
5497 SmallVector<QualType, 16> ParamTypes;
5498 for (unsigned I = 0; I != NumParams; ++I)
5499 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5500
John McCall18afab72016-03-01 00:49:02 +00005501 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5502 if (Idx != Record.size()) {
5503 for (unsigned I = 0; I != NumParams; ++I)
5504 ExtParameterInfos.push_back(
5505 FunctionProtoType::ExtParameterInfo
5506 ::getFromOpaqueValue(Record[Idx++]));
5507 EPI.ExtParameterInfos = ExtParameterInfos.data();
5508 }
5509
5510 assert(Idx == Record.size());
5511
Jordan Rose5c382722013-03-08 21:51:21 +00005512 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 }
5514
5515 case TYPE_UNRESOLVED_USING: {
5516 unsigned Idx = 0;
5517 return Context.getTypeDeclType(
5518 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5519 }
5520
5521 case TYPE_TYPEDEF: {
5522 if (Record.size() != 2) {
5523 Error("incorrect encoding of typedef type");
5524 return QualType();
5525 }
5526 unsigned Idx = 0;
5527 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5528 QualType Canonical = readType(*Loc.F, Record, Idx);
5529 if (!Canonical.isNull())
5530 Canonical = Context.getCanonicalType(Canonical);
5531 return Context.getTypedefType(Decl, Canonical);
5532 }
5533
5534 case TYPE_TYPEOF_EXPR:
5535 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5536
5537 case TYPE_TYPEOF: {
5538 if (Record.size() != 1) {
5539 Error("incorrect encoding of typeof(type) in AST file");
5540 return QualType();
5541 }
5542 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5543 return Context.getTypeOfType(UnderlyingType);
5544 }
5545
5546 case TYPE_DECLTYPE: {
5547 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5548 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5549 }
5550
5551 case TYPE_UNARY_TRANSFORM: {
5552 QualType BaseType = readType(*Loc.F, Record, Idx);
5553 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5554 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5555 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5556 }
5557
Richard Smith74aeef52013-04-26 16:15:35 +00005558 case TYPE_AUTO: {
5559 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005560 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005561 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005562 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005563 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005564
5565 case TYPE_RECORD: {
5566 if (Record.size() != 2) {
5567 Error("incorrect encoding of record type");
5568 return QualType();
5569 }
5570 unsigned Idx = 0;
5571 bool IsDependent = Record[Idx++];
5572 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5573 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5574 QualType T = Context.getRecordType(RD);
5575 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5576 return T;
5577 }
5578
5579 case TYPE_ENUM: {
5580 if (Record.size() != 2) {
5581 Error("incorrect encoding of enum type");
5582 return QualType();
5583 }
5584 unsigned Idx = 0;
5585 bool IsDependent = Record[Idx++];
5586 QualType T
5587 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5588 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5589 return T;
5590 }
5591
5592 case TYPE_ATTRIBUTED: {
5593 if (Record.size() != 3) {
5594 Error("incorrect encoding of attributed type");
5595 return QualType();
5596 }
5597 QualType modifiedType = readType(*Loc.F, Record, Idx);
5598 QualType equivalentType = readType(*Loc.F, Record, Idx);
5599 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5600 return Context.getAttributedType(kind, modifiedType, equivalentType);
5601 }
5602
5603 case TYPE_PAREN: {
5604 if (Record.size() != 1) {
5605 Error("incorrect encoding of paren type");
5606 return QualType();
5607 }
5608 QualType InnerType = readType(*Loc.F, Record, Idx);
5609 return Context.getParenType(InnerType);
5610 }
5611
5612 case TYPE_PACK_EXPANSION: {
5613 if (Record.size() != 2) {
5614 Error("incorrect encoding of pack expansion type");
5615 return QualType();
5616 }
5617 QualType Pattern = readType(*Loc.F, Record, Idx);
5618 if (Pattern.isNull())
5619 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005620 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005621 if (Record[1])
5622 NumExpansions = Record[1] - 1;
5623 return Context.getPackExpansionType(Pattern, NumExpansions);
5624 }
5625
5626 case TYPE_ELABORATED: {
5627 unsigned Idx = 0;
5628 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5629 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5630 QualType NamedType = readType(*Loc.F, Record, Idx);
5631 return Context.getElaboratedType(Keyword, NNS, NamedType);
5632 }
5633
5634 case TYPE_OBJC_INTERFACE: {
5635 unsigned Idx = 0;
5636 ObjCInterfaceDecl *ItfD
5637 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5638 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5639 }
5640
Manman Rene6be26c2016-09-13 17:25:08 +00005641 case TYPE_OBJC_TYPE_PARAM: {
5642 unsigned Idx = 0;
5643 ObjCTypeParamDecl *Decl
5644 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5645 unsigned NumProtos = Record[Idx++];
5646 SmallVector<ObjCProtocolDecl*, 4> Protos;
5647 for (unsigned I = 0; I != NumProtos; ++I)
5648 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5649 return Context.getObjCTypeParamType(Decl, Protos);
5650 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005651 case TYPE_OBJC_OBJECT: {
5652 unsigned Idx = 0;
5653 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005654 unsigned NumTypeArgs = Record[Idx++];
5655 SmallVector<QualType, 4> TypeArgs;
5656 for (unsigned I = 0; I != NumTypeArgs; ++I)
5657 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 unsigned NumProtos = Record[Idx++];
5659 SmallVector<ObjCProtocolDecl*, 4> Protos;
5660 for (unsigned I = 0; I != NumProtos; ++I)
5661 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005662 bool IsKindOf = Record[Idx++];
5663 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005664 }
5665
5666 case TYPE_OBJC_OBJECT_POINTER: {
5667 unsigned Idx = 0;
5668 QualType Pointee = readType(*Loc.F, Record, Idx);
5669 return Context.getObjCObjectPointerType(Pointee);
5670 }
5671
5672 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5673 unsigned Idx = 0;
5674 QualType Parm = readType(*Loc.F, Record, Idx);
5675 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005676 return Context.getSubstTemplateTypeParmType(
5677 cast<TemplateTypeParmType>(Parm),
5678 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 }
5680
5681 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5682 unsigned Idx = 0;
5683 QualType Parm = readType(*Loc.F, Record, Idx);
5684 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5685 return Context.getSubstTemplateTypeParmPackType(
5686 cast<TemplateTypeParmType>(Parm),
5687 ArgPack);
5688 }
5689
5690 case TYPE_INJECTED_CLASS_NAME: {
5691 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5692 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5693 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5694 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005695 const Type *T = nullptr;
5696 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5697 if (const Type *Existing = DI->getTypeForDecl()) {
5698 T = Existing;
5699 break;
5700 }
5701 }
5702 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005703 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005704 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5705 DI->setTypeForDecl(T);
5706 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005707 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 }
5709
5710 case TYPE_TEMPLATE_TYPE_PARM: {
5711 unsigned Idx = 0;
5712 unsigned Depth = Record[Idx++];
5713 unsigned Index = Record[Idx++];
5714 bool Pack = Record[Idx++];
5715 TemplateTypeParmDecl *D
5716 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5717 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5718 }
5719
5720 case TYPE_DEPENDENT_NAME: {
5721 unsigned Idx = 0;
5722 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5723 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005724 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 QualType Canon = readType(*Loc.F, Record, Idx);
5726 if (!Canon.isNull())
5727 Canon = Context.getCanonicalType(Canon);
5728 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5729 }
5730
5731 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5732 unsigned Idx = 0;
5733 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5734 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005735 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005736 unsigned NumArgs = Record[Idx++];
5737 SmallVector<TemplateArgument, 8> Args;
5738 Args.reserve(NumArgs);
5739 while (NumArgs--)
5740 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5741 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005742 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 }
5744
5745 case TYPE_DEPENDENT_SIZED_ARRAY: {
5746 unsigned Idx = 0;
5747
5748 // ArrayType
5749 QualType ElementType = readType(*Loc.F, Record, Idx);
5750 ArrayType::ArraySizeModifier ASM
5751 = (ArrayType::ArraySizeModifier)Record[Idx++];
5752 unsigned IndexTypeQuals = Record[Idx++];
5753
5754 // DependentSizedArrayType
5755 Expr *NumElts = ReadExpr(*Loc.F);
5756 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5757
5758 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5759 IndexTypeQuals, Brackets);
5760 }
5761
5762 case TYPE_TEMPLATE_SPECIALIZATION: {
5763 unsigned Idx = 0;
5764 bool IsDependent = Record[Idx++];
5765 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5766 SmallVector<TemplateArgument, 8> Args;
5767 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5768 QualType Underlying = readType(*Loc.F, Record, Idx);
5769 QualType T;
5770 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005771 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005772 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005773 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5775 return T;
5776 }
5777
5778 case TYPE_ATOMIC: {
5779 if (Record.size() != 1) {
5780 Error("Incorrect encoding of atomic type");
5781 return QualType();
5782 }
5783 QualType ValueType = readType(*Loc.F, Record, Idx);
5784 return Context.getAtomicType(ValueType);
5785 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005786
5787 case TYPE_PIPE: {
5788 if (Record.size() != 1) {
5789 Error("Incorrect encoding of pipe type");
5790 return QualType();
5791 }
5792
5793 // Reading the pipe element type.
5794 QualType ElementType = readType(*Loc.F, Record, Idx);
5795 return Context.getPipeType(ElementType);
5796 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 }
5798 llvm_unreachable("Invalid TypeCode!");
5799}
5800
Richard Smith564417a2014-03-20 21:47:22 +00005801void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5802 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005803 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005804 const RecordData &Record, unsigned &Idx) {
5805 ExceptionSpecificationType EST =
5806 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005807 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005808 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005809 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005810 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005811 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005812 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005813 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005814 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005815 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5816 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005817 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005818 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005819 }
5820}
5821
Guy Benyei11169dd2012-12-18 14:30:41 +00005822class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5823 ASTReader &Reader;
5824 ModuleFile &F;
5825 const ASTReader::RecordData &Record;
5826 unsigned &Idx;
5827
5828 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5829 unsigned &I) {
5830 return Reader.ReadSourceLocation(F, R, I);
5831 }
5832
5833 template<typename T>
5834 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5835 return Reader.ReadDeclAs<T>(F, Record, Idx);
5836 }
5837
5838public:
5839 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5840 const ASTReader::RecordData &Record, unsigned &Idx)
5841 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5842 { }
5843
5844 // We want compile-time assurance that we've enumerated all of
5845 // these, so unfortunately we have to declare them first, then
5846 // define them out-of-line.
5847#define ABSTRACT_TYPELOC(CLASS, PARENT)
5848#define TYPELOC(CLASS, PARENT) \
5849 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5850#include "clang/AST/TypeLocNodes.def"
5851
5852 void VisitFunctionTypeLoc(FunctionTypeLoc);
5853 void VisitArrayTypeLoc(ArrayTypeLoc);
5854};
5855
5856void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5857 // nothing to do
5858}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005859
Guy Benyei11169dd2012-12-18 14:30:41 +00005860void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5861 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5862 if (TL.needsExtraLocalData()) {
5863 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5864 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5865 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5866 TL.setModeAttr(Record[Idx++]);
5867 }
5868}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005869
Guy Benyei11169dd2012-12-18 14:30:41 +00005870void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5871 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5872}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005873
Guy Benyei11169dd2012-12-18 14:30:41 +00005874void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5875 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5876}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005877
Reid Kleckner8a365022013-06-24 17:51:48 +00005878void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5879 // nothing to do
5880}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005881
Reid Kleckner0503a872013-12-05 01:23:43 +00005882void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5883 // nothing to do
5884}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005885
Guy Benyei11169dd2012-12-18 14:30:41 +00005886void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5887 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5888}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005889
Guy Benyei11169dd2012-12-18 14:30:41 +00005890void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5891 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5892}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005893
Guy Benyei11169dd2012-12-18 14:30:41 +00005894void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5895 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5896}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005897
Guy Benyei11169dd2012-12-18 14:30:41 +00005898void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5899 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5900 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5901}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005902
Guy Benyei11169dd2012-12-18 14:30:41 +00005903void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5904 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5905 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5906 if (Record[Idx++])
5907 TL.setSizeExpr(Reader.ReadExpr(F));
5908 else
Craig Toppera13603a2014-05-22 05:54:18 +00005909 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005910}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005911
Guy Benyei11169dd2012-12-18 14:30:41 +00005912void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5913 VisitArrayTypeLoc(TL);
5914}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005915
Guy Benyei11169dd2012-12-18 14:30:41 +00005916void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5917 VisitArrayTypeLoc(TL);
5918}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005919
Guy Benyei11169dd2012-12-18 14:30:41 +00005920void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5921 VisitArrayTypeLoc(TL);
5922}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005923
Guy Benyei11169dd2012-12-18 14:30:41 +00005924void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5925 DependentSizedArrayTypeLoc TL) {
5926 VisitArrayTypeLoc(TL);
5927}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005928
Guy Benyei11169dd2012-12-18 14:30:41 +00005929void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5930 DependentSizedExtVectorTypeLoc TL) {
5931 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5932}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005933
Guy Benyei11169dd2012-12-18 14:30:41 +00005934void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5935 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5936}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005937
Guy Benyei11169dd2012-12-18 14:30:41 +00005938void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5939 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5940}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005941
Guy Benyei11169dd2012-12-18 14:30:41 +00005942void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5943 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5944 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5945 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5946 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005947 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5948 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 }
5950}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005951
Guy Benyei11169dd2012-12-18 14:30:41 +00005952void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5953 VisitFunctionTypeLoc(TL);
5954}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005955
Guy Benyei11169dd2012-12-18 14:30:41 +00005956void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5957 VisitFunctionTypeLoc(TL);
5958}
5959void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5960 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5961}
5962void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5963 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5964}
5965void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5966 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5967 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5968 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5969}
5970void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5971 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5972 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5973 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5974 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5975}
5976void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5977 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5978}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005979
Guy Benyei11169dd2012-12-18 14:30:41 +00005980void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5981 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5982 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5983 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5984 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5985}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005986
Guy Benyei11169dd2012-12-18 14:30:41 +00005987void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5988 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5989}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5992 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5993}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005994
Guy Benyei11169dd2012-12-18 14:30:41 +00005995void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5996 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5997}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005998
Guy Benyei11169dd2012-12-18 14:30:41 +00005999void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6000 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
6001 if (TL.hasAttrOperand()) {
6002 SourceRange range;
6003 range.setBegin(ReadSourceLocation(Record, Idx));
6004 range.setEnd(ReadSourceLocation(Record, Idx));
6005 TL.setAttrOperandParensRange(range);
6006 }
6007 if (TL.hasAttrExprOperand()) {
6008 if (Record[Idx++])
6009 TL.setAttrExprOperand(Reader.ReadExpr(F));
6010 else
Craig Toppera13603a2014-05-22 05:54:18 +00006011 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 } else if (TL.hasAttrEnumOperand())
6013 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
6014}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006015
Guy Benyei11169dd2012-12-18 14:30:41 +00006016void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6017 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6018}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006019
Guy Benyei11169dd2012-12-18 14:30:41 +00006020void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6021 SubstTemplateTypeParmTypeLoc TL) {
6022 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6023}
6024void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6025 SubstTemplateTypeParmPackTypeLoc TL) {
6026 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6027}
6028void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6029 TemplateSpecializationTypeLoc TL) {
6030 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6031 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6032 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6033 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6034 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6035 TL.setArgLocInfo(i,
6036 Reader.GetTemplateArgumentLocInfo(F,
6037 TL.getTypePtr()->getArg(i).getKind(),
6038 Record, Idx));
6039}
6040void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6041 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6042 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6043}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006044
Guy Benyei11169dd2012-12-18 14:30:41 +00006045void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6046 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6047 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6048}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6051 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6052}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006053
Guy Benyei11169dd2012-12-18 14:30:41 +00006054void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6055 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6056 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6057 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6058}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6061 DependentTemplateSpecializationTypeLoc TL) {
6062 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
6063 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
6064 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
6065 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
6066 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
6067 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
6068 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6069 TL.setArgLocInfo(I,
6070 Reader.GetTemplateArgumentLocInfo(F,
6071 TL.getTypePtr()->getArg(I).getKind(),
6072 Record, Idx));
6073}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006074
Guy Benyei11169dd2012-12-18 14:30:41 +00006075void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6076 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
6077}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006078
Guy Benyei11169dd2012-12-18 14:30:41 +00006079void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6080 TL.setNameLoc(ReadSourceLocation(Record, Idx));
6081}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006082
Manman Rene6be26c2016-09-13 17:25:08 +00006083void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6084 if (TL.getNumProtocols()) {
6085 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6086 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
6087 }
6088 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6089 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6090}
6091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6093 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006094 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
6095 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
6096 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6097 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
6098 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
6099 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6101 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
6102}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006103
Guy Benyei11169dd2012-12-18 14:30:41 +00006104void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6105 TL.setStarLoc(ReadSourceLocation(Record, Idx));
6106}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6109 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6110 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
6111 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
6112}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006113
Xiuli Pan9c14e282016-01-09 12:53:17 +00006114void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6115 TL.setKWLoc(ReadSourceLocation(Record, Idx));
6116}
Guy Benyei11169dd2012-12-18 14:30:41 +00006117
6118TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
6119 const RecordData &Record,
6120 unsigned &Idx) {
6121 QualType InfoTy = readType(F, Record, Idx);
6122 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006123 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006124
6125 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6126 TypeLocReader TLR(*this, F, Record, Idx);
6127 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6128 TLR.Visit(TL);
6129 return TInfo;
6130}
6131
6132QualType ASTReader::GetType(TypeID ID) {
6133 unsigned FastQuals = ID & Qualifiers::FastMask;
6134 unsigned Index = ID >> Qualifiers::FastWidth;
6135
6136 if (Index < NUM_PREDEF_TYPE_IDS) {
6137 QualType T;
6138 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006139 case PREDEF_TYPE_NULL_ID:
6140 return QualType();
6141 case PREDEF_TYPE_VOID_ID:
6142 T = Context.VoidTy;
6143 break;
6144 case PREDEF_TYPE_BOOL_ID:
6145 T = Context.BoolTy;
6146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006147
6148 case PREDEF_TYPE_CHAR_U_ID:
6149 case PREDEF_TYPE_CHAR_S_ID:
6150 // FIXME: Check that the signedness of CharTy is correct!
6151 T = Context.CharTy;
6152 break;
6153
Alexey Baderbdf7c842015-09-15 12:18:29 +00006154 case PREDEF_TYPE_UCHAR_ID:
6155 T = Context.UnsignedCharTy;
6156 break;
6157 case PREDEF_TYPE_USHORT_ID:
6158 T = Context.UnsignedShortTy;
6159 break;
6160 case PREDEF_TYPE_UINT_ID:
6161 T = Context.UnsignedIntTy;
6162 break;
6163 case PREDEF_TYPE_ULONG_ID:
6164 T = Context.UnsignedLongTy;
6165 break;
6166 case PREDEF_TYPE_ULONGLONG_ID:
6167 T = Context.UnsignedLongLongTy;
6168 break;
6169 case PREDEF_TYPE_UINT128_ID:
6170 T = Context.UnsignedInt128Ty;
6171 break;
6172 case PREDEF_TYPE_SCHAR_ID:
6173 T = Context.SignedCharTy;
6174 break;
6175 case PREDEF_TYPE_WCHAR_ID:
6176 T = Context.WCharTy;
6177 break;
6178 case PREDEF_TYPE_SHORT_ID:
6179 T = Context.ShortTy;
6180 break;
6181 case PREDEF_TYPE_INT_ID:
6182 T = Context.IntTy;
6183 break;
6184 case PREDEF_TYPE_LONG_ID:
6185 T = Context.LongTy;
6186 break;
6187 case PREDEF_TYPE_LONGLONG_ID:
6188 T = Context.LongLongTy;
6189 break;
6190 case PREDEF_TYPE_INT128_ID:
6191 T = Context.Int128Ty;
6192 break;
6193 case PREDEF_TYPE_HALF_ID:
6194 T = Context.HalfTy;
6195 break;
6196 case PREDEF_TYPE_FLOAT_ID:
6197 T = Context.FloatTy;
6198 break;
6199 case PREDEF_TYPE_DOUBLE_ID:
6200 T = Context.DoubleTy;
6201 break;
6202 case PREDEF_TYPE_LONGDOUBLE_ID:
6203 T = Context.LongDoubleTy;
6204 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006205 case PREDEF_TYPE_FLOAT128_ID:
6206 T = Context.Float128Ty;
6207 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006208 case PREDEF_TYPE_OVERLOAD_ID:
6209 T = Context.OverloadTy;
6210 break;
6211 case PREDEF_TYPE_BOUND_MEMBER:
6212 T = Context.BoundMemberTy;
6213 break;
6214 case PREDEF_TYPE_PSEUDO_OBJECT:
6215 T = Context.PseudoObjectTy;
6216 break;
6217 case PREDEF_TYPE_DEPENDENT_ID:
6218 T = Context.DependentTy;
6219 break;
6220 case PREDEF_TYPE_UNKNOWN_ANY:
6221 T = Context.UnknownAnyTy;
6222 break;
6223 case PREDEF_TYPE_NULLPTR_ID:
6224 T = Context.NullPtrTy;
6225 break;
6226 case PREDEF_TYPE_CHAR16_ID:
6227 T = Context.Char16Ty;
6228 break;
6229 case PREDEF_TYPE_CHAR32_ID:
6230 T = Context.Char32Ty;
6231 break;
6232 case PREDEF_TYPE_OBJC_ID:
6233 T = Context.ObjCBuiltinIdTy;
6234 break;
6235 case PREDEF_TYPE_OBJC_CLASS:
6236 T = Context.ObjCBuiltinClassTy;
6237 break;
6238 case PREDEF_TYPE_OBJC_SEL:
6239 T = Context.ObjCBuiltinSelTy;
6240 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006241#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6242 case PREDEF_TYPE_##Id##_ID: \
6243 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006244 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006245#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006246 case PREDEF_TYPE_SAMPLER_ID:
6247 T = Context.OCLSamplerTy;
6248 break;
6249 case PREDEF_TYPE_EVENT_ID:
6250 T = Context.OCLEventTy;
6251 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006252 case PREDEF_TYPE_CLK_EVENT_ID:
6253 T = Context.OCLClkEventTy;
6254 break;
6255 case PREDEF_TYPE_QUEUE_ID:
6256 T = Context.OCLQueueTy;
6257 break;
6258 case PREDEF_TYPE_NDRANGE_ID:
6259 T = Context.OCLNDRangeTy;
6260 break;
6261 case PREDEF_TYPE_RESERVE_ID_ID:
6262 T = Context.OCLReserveIDTy;
6263 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006264 case PREDEF_TYPE_AUTO_DEDUCT:
6265 T = Context.getAutoDeductType();
6266 break;
6267
6268 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6269 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006270 break;
6271
6272 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6273 T = Context.ARCUnbridgedCastTy;
6274 break;
6275
Guy Benyei11169dd2012-12-18 14:30:41 +00006276 case PREDEF_TYPE_BUILTIN_FN:
6277 T = Context.BuiltinFnTy;
6278 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006279
6280 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6281 T = Context.OMPArraySectionTy;
6282 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 }
6284
6285 assert(!T.isNull() && "Unknown predefined type");
6286 return T.withFastQualifiers(FastQuals);
6287 }
6288
6289 Index -= NUM_PREDEF_TYPE_IDS;
6290 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6291 if (TypesLoaded[Index].isNull()) {
6292 TypesLoaded[Index] = readTypeRecord(Index);
6293 if (TypesLoaded[Index].isNull())
6294 return QualType();
6295
6296 TypesLoaded[Index]->setFromAST();
6297 if (DeserializationListener)
6298 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6299 TypesLoaded[Index]);
6300 }
6301
6302 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6303}
6304
6305QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6306 return GetType(getGlobalTypeID(F, LocalID));
6307}
6308
6309serialization::TypeID
6310ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6311 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6312 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6313
6314 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6315 return LocalID;
6316
6317 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6318 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6319 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6320
6321 unsigned GlobalIndex = LocalIndex + I->second;
6322 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6323}
6324
6325TemplateArgumentLocInfo
6326ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6327 TemplateArgument::ArgKind Kind,
6328 const RecordData &Record,
6329 unsigned &Index) {
6330 switch (Kind) {
6331 case TemplateArgument::Expression:
6332 return ReadExpr(F);
6333 case TemplateArgument::Type:
6334 return GetTypeSourceInfo(F, Record, Index);
6335 case TemplateArgument::Template: {
6336 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6337 Index);
6338 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6339 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6340 SourceLocation());
6341 }
6342 case TemplateArgument::TemplateExpansion: {
6343 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6344 Index);
6345 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6346 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6347 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6348 EllipsisLoc);
6349 }
6350 case TemplateArgument::Null:
6351 case TemplateArgument::Integral:
6352 case TemplateArgument::Declaration:
6353 case TemplateArgument::NullPtr:
6354 case TemplateArgument::Pack:
6355 // FIXME: Is this right?
6356 return TemplateArgumentLocInfo();
6357 }
6358 llvm_unreachable("unexpected template argument loc");
6359}
6360
6361TemplateArgumentLoc
6362ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6363 const RecordData &Record, unsigned &Index) {
6364 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6365
6366 if (Arg.getKind() == TemplateArgument::Expression) {
6367 if (Record[Index++]) // bool InfoHasSameExpr.
6368 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6369 }
6370 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6371 Record, Index));
6372}
6373
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006374const ASTTemplateArgumentListInfo*
6375ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6376 const RecordData &Record,
6377 unsigned &Index) {
6378 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6379 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6380 unsigned NumArgsAsWritten = Record[Index++];
6381 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6382 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6383 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6384 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6385}
6386
Guy Benyei11169dd2012-12-18 14:30:41 +00006387Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6388 return GetDecl(ID);
6389}
6390
Richard Smith50895422015-01-31 03:04:55 +00006391template<typename TemplateSpecializationDecl>
6392static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6393 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6394 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6395}
6396
Richard Smith053f6c62014-05-16 23:01:30 +00006397void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006398 if (NumCurrentElementsDeserializing) {
6399 // We arrange to not care about the complete redeclaration chain while we're
6400 // deserializing. Just remember that the AST has marked this one as complete
6401 // but that it's not actually complete yet, so we know we still need to
6402 // complete it later.
6403 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6404 return;
6405 }
6406
Richard Smith053f6c62014-05-16 23:01:30 +00006407 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6408
Richard Smith053f6c62014-05-16 23:01:30 +00006409 // If this is a named declaration, complete it by looking it up
6410 // within its context.
6411 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006412 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006413 // all mergeable entities within it.
6414 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6415 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6416 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006417 if (!getContext().getLangOpts().CPlusPlus &&
6418 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006419 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006420 // the identifier instead. (For C++ modules, we don't store decls
6421 // in the serialized identifier table, so we do the lookup in the TU.)
6422 auto *II = Name.getAsIdentifierInfo();
6423 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006424 if (II->isOutOfDate())
6425 updateOutOfDateIdentifier(*II);
6426 } else
6427 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006428 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006429 // Find all declarations of this kind from the relevant context.
6430 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6431 auto *DC = cast<DeclContext>(DCDecl);
6432 SmallVector<Decl*, 8> Decls;
6433 FindExternalLexicalDecls(
6434 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6435 }
Richard Smith053f6c62014-05-16 23:01:30 +00006436 }
6437 }
Richard Smith50895422015-01-31 03:04:55 +00006438
6439 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6440 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6441 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6442 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6443 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6444 if (auto *Template = FD->getPrimaryTemplate())
6445 Template->LoadLazySpecializations();
6446 }
Richard Smith053f6c62014-05-16 23:01:30 +00006447}
6448
Richard Smithc2bb8182015-03-24 06:36:48 +00006449CXXCtorInitializer **
6450ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6451 RecordLocation Loc = getLocalBitOffset(Offset);
6452 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6453 SavedStreamPosition SavedPosition(Cursor);
6454 Cursor.JumpToBit(Loc.Offset);
6455 ReadingKindTracker ReadingKind(Read_Decl, *this);
6456
6457 RecordData Record;
6458 unsigned Code = Cursor.ReadCode();
6459 unsigned RecCode = Cursor.readRecord(Code, Record);
6460 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6461 Error("malformed AST file: missing C++ ctor initializers");
6462 return nullptr;
6463 }
6464
6465 unsigned Idx = 0;
6466 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6467}
6468
Guy Benyei11169dd2012-12-18 14:30:41 +00006469CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6470 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006471 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 SavedStreamPosition SavedPosition(Cursor);
6473 Cursor.JumpToBit(Loc.Offset);
6474 ReadingKindTracker ReadingKind(Read_Decl, *this);
6475 RecordData Record;
6476 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006477 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006479 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006480 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 }
6482
6483 unsigned Idx = 0;
6484 unsigned NumBases = Record[Idx++];
6485 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6486 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6487 for (unsigned I = 0; I != NumBases; ++I)
6488 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6489 return Bases;
6490}
6491
6492serialization::DeclID
6493ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6494 if (LocalID < NUM_PREDEF_DECL_IDS)
6495 return LocalID;
6496
6497 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6498 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6499 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6500
6501 return LocalID + I->second;
6502}
6503
6504bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6505 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006506 // Predefined decls aren't from any module.
6507 if (ID < NUM_PREDEF_DECL_IDS)
6508 return false;
6509
Richard Smithbcda1a92015-07-12 23:51:20 +00006510 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6511 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006512}
6513
Douglas Gregor9f782892013-01-21 15:25:38 +00006514ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006516 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6518 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6519 return I->second;
6520}
6521
6522SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6523 if (ID < NUM_PREDEF_DECL_IDS)
6524 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006525
Guy Benyei11169dd2012-12-18 14:30:41 +00006526 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6527
6528 if (Index > DeclsLoaded.size()) {
6529 Error("declaration ID out-of-range for AST file");
6530 return SourceLocation();
6531 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006532
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 if (Decl *D = DeclsLoaded[Index])
6534 return D->getLocation();
6535
Richard Smithcb34bd32016-03-27 07:28:06 +00006536 SourceLocation Loc;
6537 DeclCursorForID(ID, Loc);
6538 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006539}
6540
Richard Smithfe620d22015-03-05 23:24:12 +00006541static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6542 switch (ID) {
6543 case PREDEF_DECL_NULL_ID:
6544 return nullptr;
6545
6546 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6547 return Context.getTranslationUnitDecl();
6548
6549 case PREDEF_DECL_OBJC_ID_ID:
6550 return Context.getObjCIdDecl();
6551
6552 case PREDEF_DECL_OBJC_SEL_ID:
6553 return Context.getObjCSelDecl();
6554
6555 case PREDEF_DECL_OBJC_CLASS_ID:
6556 return Context.getObjCClassDecl();
6557
6558 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6559 return Context.getObjCProtocolDecl();
6560
6561 case PREDEF_DECL_INT_128_ID:
6562 return Context.getInt128Decl();
6563
6564 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6565 return Context.getUInt128Decl();
6566
6567 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6568 return Context.getObjCInstanceTypeDecl();
6569
6570 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6571 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006572
Richard Smith9b88a4c2015-07-27 05:40:23 +00006573 case PREDEF_DECL_VA_LIST_TAG:
6574 return Context.getVaListTagDecl();
6575
Charles Davisc7d5c942015-09-17 20:55:33 +00006576 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6577 return Context.getBuiltinMSVaListDecl();
6578
Richard Smithf19e1272015-03-07 00:04:49 +00006579 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6580 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006581
6582 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6583 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006584
6585 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6586 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006587
6588 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6589 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006590
6591 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6592 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006593 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006594 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006595}
6596
Richard Smithcd45dbc2014-04-19 03:48:30 +00006597Decl *ASTReader::GetExistingDecl(DeclID ID) {
6598 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006599 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6600 if (D) {
6601 // Track that we have merged the declaration with ID \p ID into the
6602 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006603 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006604 if (Merged.empty())
6605 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 }
Richard Smithfe620d22015-03-05 23:24:12 +00006607 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006609
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6611
6612 if (Index >= DeclsLoaded.size()) {
6613 assert(0 && "declaration ID out-of-range for AST file");
6614 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006615 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006616 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006617
6618 return DeclsLoaded[Index];
6619}
6620
6621Decl *ASTReader::GetDecl(DeclID ID) {
6622 if (ID < NUM_PREDEF_DECL_IDS)
6623 return GetExistingDecl(ID);
6624
6625 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6626
6627 if (Index >= DeclsLoaded.size()) {
6628 assert(0 && "declaration ID out-of-range for AST file");
6629 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006630 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006631 }
6632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 if (!DeclsLoaded[Index]) {
6634 ReadDeclRecord(ID);
6635 if (DeserializationListener)
6636 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6637 }
6638
6639 return DeclsLoaded[Index];
6640}
6641
6642DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6643 DeclID GlobalID) {
6644 if (GlobalID < NUM_PREDEF_DECL_IDS)
6645 return GlobalID;
6646
6647 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6648 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6649 ModuleFile *Owner = I->second;
6650
6651 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6652 = M.GlobalToLocalDeclIDs.find(Owner);
6653 if (Pos == M.GlobalToLocalDeclIDs.end())
6654 return 0;
6655
6656 return GlobalID - Owner->BaseDeclID + Pos->second;
6657}
6658
6659serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6660 const RecordData &Record,
6661 unsigned &Idx) {
6662 if (Idx >= Record.size()) {
6663 Error("Corrupted AST file");
6664 return 0;
6665 }
6666
6667 return getGlobalDeclID(F, Record[Idx++]);
6668}
6669
6670/// \brief Resolve the offset of a statement into a statement.
6671///
6672/// This operation will read a new statement from the external
6673/// source each time it is called, and is meant to be used via a
6674/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6675Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6676 // Switch case IDs are per Decl.
6677 ClearSwitchCaseIDs();
6678
6679 // Offset here is a global offset across the entire chain.
6680 RecordLocation Loc = getLocalBitOffset(Offset);
6681 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6682 return ReadStmtFromStream(*Loc.F);
6683}
6684
Richard Smith3cb15722015-08-05 22:41:45 +00006685void ASTReader::FindExternalLexicalDecls(
6686 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6687 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006688 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6689
Richard Smith9ccdd932015-08-06 22:14:12 +00006690 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006691 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6692 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6693 auto K = (Decl::Kind)+LexicalDecls[I];
6694 if (!IsKindWeWant(K))
6695 continue;
6696
6697 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6698
6699 // Don't add predefined declarations to the lexical context more
6700 // than once.
6701 if (ID < NUM_PREDEF_DECL_IDS) {
6702 if (PredefsVisited[ID])
6703 continue;
6704
6705 PredefsVisited[ID] = true;
6706 }
6707
6708 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006709 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006710 if (!DC->isDeclInLexicalTraversal(D))
6711 Decls.push_back(D);
6712 }
6713 }
6714 };
6715
6716 if (isa<TranslationUnitDecl>(DC)) {
6717 for (auto Lexical : TULexicalDecls)
6718 Visit(Lexical.first, Lexical.second);
6719 } else {
6720 auto I = LexicalDecls.find(DC);
6721 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006722 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006723 }
6724
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006726}
6727
6728namespace {
6729
6730class DeclIDComp {
6731 ASTReader &Reader;
6732 ModuleFile &Mod;
6733
6734public:
6735 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6736
6737 bool operator()(LocalDeclID L, LocalDeclID R) const {
6738 SourceLocation LHS = getLocation(L);
6739 SourceLocation RHS = getLocation(R);
6740 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6741 }
6742
6743 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6744 SourceLocation RHS = getLocation(R);
6745 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6746 }
6747
6748 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6749 SourceLocation LHS = getLocation(L);
6750 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6751 }
6752
6753 SourceLocation getLocation(LocalDeclID ID) const {
6754 return Reader.getSourceManager().getFileLoc(
6755 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6756 }
6757};
6758
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006759} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006760
6761void ASTReader::FindFileRegionDecls(FileID File,
6762 unsigned Offset, unsigned Length,
6763 SmallVectorImpl<Decl *> &Decls) {
6764 SourceManager &SM = getSourceManager();
6765
6766 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6767 if (I == FileDeclIDs.end())
6768 return;
6769
6770 FileDeclsInfo &DInfo = I->second;
6771 if (DInfo.Decls.empty())
6772 return;
6773
6774 SourceLocation
6775 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6776 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6777
6778 DeclIDComp DIDComp(*this, *DInfo.Mod);
6779 ArrayRef<serialization::LocalDeclID>::iterator
6780 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6781 BeginLoc, DIDComp);
6782 if (BeginIt != DInfo.Decls.begin())
6783 --BeginIt;
6784
6785 // If we are pointing at a top-level decl inside an objc container, we need
6786 // to backtrack until we find it otherwise we will fail to report that the
6787 // region overlaps with an objc container.
6788 while (BeginIt != DInfo.Decls.begin() &&
6789 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6790 ->isTopLevelDeclInObjCContainer())
6791 --BeginIt;
6792
6793 ArrayRef<serialization::LocalDeclID>::iterator
6794 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6795 EndLoc, DIDComp);
6796 if (EndIt != DInfo.Decls.end())
6797 ++EndIt;
6798
6799 for (ArrayRef<serialization::LocalDeclID>::iterator
6800 DIt = BeginIt; DIt != EndIt; ++DIt)
6801 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6802}
6803
Richard Smith9ce12e32013-02-07 03:30:24 +00006804bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006805ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6806 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006807 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 "DeclContext has no visible decls in storage");
6809 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006810 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006811
Richard Smithd88a7f12015-09-01 20:35:42 +00006812 auto It = Lookups.find(DC);
6813 if (It == Lookups.end())
6814 return false;
6815
Richard Smith8c913ec2014-08-14 02:21:01 +00006816 Deserializing LookupResults(this);
6817
Richard Smithd88a7f12015-09-01 20:35:42 +00006818 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006820 for (DeclID ID : It->second.Table.find(Name)) {
6821 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6822 if (ND->getDeclName() == Name)
6823 Decls.push_back(ND);
6824 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006825
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 ++NumVisibleDeclContextsRead;
6827 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006828 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006829}
6830
Guy Benyei11169dd2012-12-18 14:30:41 +00006831void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6832 if (!DC->hasExternalVisibleStorage())
6833 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006834
6835 auto It = Lookups.find(DC);
6836 assert(It != Lookups.end() &&
6837 "have external visible storage but no lookup tables");
6838
Craig Topper79be4cd2013-07-05 04:33:53 +00006839 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006840
Richard Smithd88a7f12015-09-01 20:35:42 +00006841 for (DeclID ID : It->second.Table.findAll()) {
6842 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6843 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 }
6845
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 ++NumVisibleDeclContextsRead;
6847
Craig Topper79be4cd2013-07-05 04:33:53 +00006848 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006849 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6850 }
6851 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6852}
6853
Richard Smithd88a7f12015-09-01 20:35:42 +00006854const serialization::reader::DeclContextLookupTable *
6855ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6856 auto I = Lookups.find(Primary);
6857 return I == Lookups.end() ? nullptr : &I->second;
6858}
6859
Guy Benyei11169dd2012-12-18 14:30:41 +00006860/// \brief Under non-PCH compilation the consumer receives the objc methods
6861/// before receiving the implementation, and codegen depends on this.
6862/// We simulate this by deserializing and passing to consumer the methods of the
6863/// implementation before passing the deserialized implementation decl.
6864static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6865 ASTConsumer *Consumer) {
6866 assert(ImplD && Consumer);
6867
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006868 for (auto *I : ImplD->methods())
6869 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006870
6871 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6872}
6873
6874void ASTReader::PassInterestingDeclsToConsumer() {
6875 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006876
6877 if (PassingDeclsToConsumer)
6878 return;
6879
6880 // Guard variable to avoid recursively redoing the process of passing
6881 // decls to consumer.
6882 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6883 true);
6884
Richard Smith9e2341d2015-03-23 03:25:59 +00006885 // Ensure that we've loaded all potentially-interesting declarations
6886 // that need to be eagerly loaded.
6887 for (auto ID : EagerlyDeserializedDecls)
6888 GetDecl(ID);
6889 EagerlyDeserializedDecls.clear();
6890
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 while (!InterestingDecls.empty()) {
6892 Decl *D = InterestingDecls.front();
6893 InterestingDecls.pop_front();
6894
6895 PassInterestingDeclToConsumer(D);
6896 }
6897}
6898
6899void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6900 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6901 PassObjCImplDeclToConsumer(ImplD, Consumer);
6902 else
6903 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6904}
6905
6906void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6907 this->Consumer = Consumer;
6908
Richard Smith9e2341d2015-03-23 03:25:59 +00006909 if (Consumer)
6910 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006911
6912 if (DeserializationListener)
6913 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006914}
6915
6916void ASTReader::PrintStats() {
6917 std::fprintf(stderr, "*** AST File Statistics:\n");
6918
6919 unsigned NumTypesLoaded
6920 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6921 QualType());
6922 unsigned NumDeclsLoaded
6923 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006924 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 unsigned NumIdentifiersLoaded
6926 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6927 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006928 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 unsigned NumMacrosLoaded
6930 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6931 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006932 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 unsigned NumSelectorsLoaded
6934 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6935 SelectorsLoaded.end(),
6936 Selector());
6937
6938 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6939 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6940 NumSLocEntriesRead, TotalNumSLocEntries,
6941 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6942 if (!TypesLoaded.empty())
6943 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6944 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6945 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6946 if (!DeclsLoaded.empty())
6947 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6948 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6949 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6950 if (!IdentifiersLoaded.empty())
6951 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6952 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6953 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6954 if (!MacrosLoaded.empty())
6955 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6956 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6957 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6958 if (!SelectorsLoaded.empty())
6959 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6960 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6961 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6962 if (TotalNumStatements)
6963 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6964 NumStatementsRead, TotalNumStatements,
6965 ((float)NumStatementsRead/TotalNumStatements * 100));
6966 if (TotalNumMacros)
6967 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6968 NumMacrosRead, TotalNumMacros,
6969 ((float)NumMacrosRead/TotalNumMacros * 100));
6970 if (TotalLexicalDeclContexts)
6971 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6972 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6973 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6974 * 100));
6975 if (TotalVisibleDeclContexts)
6976 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6977 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6978 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6979 * 100));
6980 if (TotalNumMethodPoolEntries) {
6981 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6982 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6983 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6984 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006986 if (NumMethodPoolLookups) {
6987 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6988 NumMethodPoolHits, NumMethodPoolLookups,
6989 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6990 }
6991 if (NumMethodPoolTableLookups) {
6992 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6993 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6994 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6995 * 100.0));
6996 }
6997
Douglas Gregor00a50f72013-01-25 00:38:33 +00006998 if (NumIdentifierLookupHits) {
6999 std::fprintf(stderr,
7000 " %u / %u identifier table lookups succeeded (%f%%)\n",
7001 NumIdentifierLookupHits, NumIdentifierLookups,
7002 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7003 }
7004
Douglas Gregore060e572013-01-25 01:03:03 +00007005 if (GlobalIndex) {
7006 std::fprintf(stderr, "\n");
7007 GlobalIndex->printStats();
7008 }
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 std::fprintf(stderr, "\n");
7011 dump();
7012 std::fprintf(stderr, "\n");
7013}
7014
7015template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7016static void
7017dumpModuleIDMap(StringRef Name,
7018 const ContinuousRangeMap<Key, ModuleFile *,
7019 InitialCapacity> &Map) {
7020 if (Map.begin() == Map.end())
7021 return;
7022
7023 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7024 llvm::errs() << Name << ":\n";
7025 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7026 I != IEnd; ++I) {
7027 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7028 << "\n";
7029 }
7030}
7031
Yaron Kerencdae9412016-01-29 19:38:18 +00007032LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007033 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7034 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7035 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7036 dumpModuleIDMap("Global type map", GlobalTypeMap);
7037 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7038 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7039 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7040 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7041 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7042 dumpModuleIDMap("Global preprocessed entity map",
7043 GlobalPreprocessedEntityMap);
7044
7045 llvm::errs() << "\n*** PCH/Modules Loaded:";
7046 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
7047 MEnd = ModuleMgr.end();
7048 M != MEnd; ++M)
7049 (*M)->dump();
7050}
7051
7052/// Return the amount of memory used by memory buffers, breaking down
7053/// by heap-backed versus mmap'ed memory.
7054void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7055 for (ModuleConstIterator I = ModuleMgr.begin(),
7056 E = ModuleMgr.end(); I != E; ++I) {
7057 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7058 size_t bytes = buf->getBufferSize();
7059 switch (buf->getBufferKind()) {
7060 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7061 sizes.malloc_bytes += bytes;
7062 break;
7063 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7064 sizes.mmap_bytes += bytes;
7065 break;
7066 }
7067 }
7068 }
7069}
7070
7071void ASTReader::InitializeSema(Sema &S) {
7072 SemaObj = &S;
7073 S.addExternalSource(this);
7074
7075 // Makes sure any declarations that were deserialized "too early"
7076 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007077 for (uint64_t ID : PreloadedDeclIDs) {
7078 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7079 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007081 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007082
Richard Smith3d8e97e2013-10-18 06:54:39 +00007083 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 if (!FPPragmaOptions.empty()) {
7085 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7086 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7087 }
7088
Richard Smith3d8e97e2013-10-18 06:54:39 +00007089 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007090 if (!OpenCLExtensions.empty()) {
7091 unsigned I = 0;
7092#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7093#include "clang/Basic/OpenCLExtensions.def"
7094
7095 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7096 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007097
7098 UpdateSema();
7099}
7100
7101void ASTReader::UpdateSema() {
7102 assert(SemaObj && "no Sema to update");
7103
7104 // Load the offsets of the declarations that Sema references.
7105 // They will be lazily deserialized when needed.
7106 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007107 assert(SemaDeclRefs.size() % 3 == 0);
7108 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007109 if (!SemaObj->StdNamespace)
7110 SemaObj->StdNamespace = SemaDeclRefs[I];
7111 if (!SemaObj->StdBadAlloc)
7112 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007113 if (!SemaObj->StdAlignValT)
7114 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007115 }
7116 SemaDeclRefs.clear();
7117 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007118
Nico Weber779355f2016-03-02 23:22:00 +00007119 // Update the state of pragmas. Use the same API as if we had encountered the
7120 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007121 if(OptimizeOffPragmaLocation.isValid())
7122 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007123 if (PragmaMSStructState != -1)
7124 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007125 if (PointersToMembersPragmaLocation.isValid()) {
7126 SemaObj->ActOnPragmaMSPointersToMembers(
7127 (LangOptions::PragmaMSPointersToMembersKind)
7128 PragmaMSPointersToMembersState,
7129 PointersToMembersPragmaLocation);
7130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007131}
7132
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007133IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 // Note that we are loading an identifier.
7135 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007136
Douglas Gregor7211ac12013-01-25 23:32:03 +00007137 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007138 NumIdentifierLookups,
7139 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007140
7141 // We don't need to do identifier table lookups in C++ modules (we preload
7142 // all interesting declarations, and don't need to use the scope for name
7143 // lookups). Perform the lookup in PCH files, though, since we don't build
7144 // a complete initial identifier table if we're carrying on from a PCH.
7145 if (Context.getLangOpts().CPlusPlus) {
7146 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007147 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007148 break;
7149 } else {
7150 // If there is a global index, look there first to determine which modules
7151 // provably do not have any results for this identifier.
7152 GlobalModuleIndex::HitSet Hits;
7153 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7154 if (!loadGlobalIndex()) {
7155 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7156 HitsPtr = &Hits;
7157 }
7158 }
7159
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007160 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007161 }
7162
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 IdentifierInfo *II = Visitor.getIdentifierInfo();
7164 markIdentifierUpToDate(II);
7165 return II;
7166}
7167
7168namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007169
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 /// \brief An identifier-lookup iterator that enumerates all of the
7171 /// identifiers stored within a set of AST files.
7172 class ASTIdentifierIterator : public IdentifierIterator {
7173 /// \brief The AST reader whose identifiers are being enumerated.
7174 const ASTReader &Reader;
7175
7176 /// \brief The current index into the chain of AST files stored in
7177 /// the AST reader.
7178 unsigned Index;
7179
7180 /// \brief The current position within the identifier lookup table
7181 /// of the current AST file.
7182 ASTIdentifierLookupTable::key_iterator Current;
7183
7184 /// \brief The end position within the identifier lookup table of
7185 /// the current AST file.
7186 ASTIdentifierLookupTable::key_iterator End;
7187
Ben Langmuir537c5b52016-05-04 00:53:13 +00007188 /// \brief Whether to skip any modules in the ASTReader.
7189 bool SkipModules;
7190
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007192 explicit ASTIdentifierIterator(const ASTReader &Reader,
7193 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007194
Craig Topper3e89dfe2014-03-13 02:13:41 +00007195 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007197
7198} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007199
Ben Langmuir537c5b52016-05-04 00:53:13 +00007200ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7201 bool SkipModules)
7202 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007203}
7204
7205StringRef ASTIdentifierIterator::Next() {
7206 while (Current == End) {
7207 // If we have exhausted all of our AST files, we're done.
7208 if (Index == 0)
7209 return StringRef();
7210
7211 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007212 ModuleFile &F = Reader.ModuleMgr[Index];
7213 if (SkipModules && F.isModule())
7214 continue;
7215
7216 ASTIdentifierLookupTable *IdTable =
7217 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 Current = IdTable->key_begin();
7219 End = IdTable->key_end();
7220 }
7221
7222 // We have any identifiers remaining in the current AST file; return
7223 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007224 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007225 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007226 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007227}
7228
Ben Langmuir537c5b52016-05-04 00:53:13 +00007229namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007230
Ben Langmuir537c5b52016-05-04 00:53:13 +00007231/// A utility for appending two IdentifierIterators.
7232class ChainedIdentifierIterator : public IdentifierIterator {
7233 std::unique_ptr<IdentifierIterator> Current;
7234 std::unique_ptr<IdentifierIterator> Queued;
7235
7236public:
7237 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7238 std::unique_ptr<IdentifierIterator> Second)
7239 : Current(std::move(First)), Queued(std::move(Second)) {}
7240
7241 StringRef Next() override {
7242 if (!Current)
7243 return StringRef();
7244
7245 StringRef result = Current->Next();
7246 if (!result.empty())
7247 return result;
7248
7249 // Try the queued iterator, which may itself be empty.
7250 Current.reset();
7251 std::swap(Current, Queued);
7252 return Next();
7253 }
7254};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007255
Ben Langmuir537c5b52016-05-04 00:53:13 +00007256} // end anonymous namespace.
7257
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007258IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007259 if (!loadGlobalIndex()) {
7260 std::unique_ptr<IdentifierIterator> ReaderIter(
7261 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7262 std::unique_ptr<IdentifierIterator> ModulesIter(
7263 GlobalIndex->createIdentifierIterator());
7264 return new ChainedIdentifierIterator(std::move(ReaderIter),
7265 std::move(ModulesIter));
7266 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 return new ASTIdentifierIterator(*this);
7269}
7270
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007271namespace clang {
7272namespace serialization {
7273
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 class ReadMethodPoolVisitor {
7275 ASTReader &Reader;
7276 Selector Sel;
7277 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007278 unsigned InstanceBits;
7279 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007280 bool InstanceHasMoreThanOneDecl;
7281 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007282 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7283 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007284
7285 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007286 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007287 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007288 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007289 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7290 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007291
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007292 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 if (!M.SelectorLookupTable)
7294 return false;
7295
7296 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007297 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007298 return true;
7299
Richard Smithbdf2d932015-07-30 03:37:16 +00007300 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 ASTSelectorLookupTable *PoolTable
7302 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007303 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 if (Pos == PoolTable->end())
7305 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007306
Richard Smithbdf2d932015-07-30 03:37:16 +00007307 ++Reader.NumMethodPoolTableHits;
7308 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 // FIXME: Not quite happy with the statistics here. We probably should
7310 // disable this tracking when called via LoadSelector.
7311 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007312 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007314 if (Reader.DeserializationListener)
7315 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007316
Richard Smithbdf2d932015-07-30 03:37:16 +00007317 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7318 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7319 InstanceBits = Data.InstanceBits;
7320 FactoryBits = Data.FactoryBits;
7321 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7322 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 return true;
7324 }
7325
7326 /// \brief Retrieve the instance methods found by this visitor.
7327 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7328 return InstanceMethods;
7329 }
7330
7331 /// \brief Retrieve the instance methods found by this visitor.
7332 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7333 return FactoryMethods;
7334 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007335
7336 unsigned getInstanceBits() const { return InstanceBits; }
7337 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007338 bool instanceHasMoreThanOneDecl() const {
7339 return InstanceHasMoreThanOneDecl;
7340 }
7341 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007342 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007343
7344} // end namespace serialization
7345} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007346
7347/// \brief Add the given set of methods to the method list.
7348static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7349 ObjCMethodList &List) {
7350 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7351 S.addMethodToGlobalList(&List, Methods[I]);
7352 }
7353}
7354
7355void ASTReader::ReadMethodPool(Selector Sel) {
7356 // Get the selector generation and update it to the current generation.
7357 unsigned &Generation = SelectorGeneration[Sel];
7358 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007359 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007360 SelectorOutOfDate[Sel] = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007361
7362 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007363 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007365 ModuleMgr.visit(Visitor);
7366
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007368 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007369 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007370
7371 ++NumMethodPoolHits;
7372
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 if (!getSema())
7374 return;
7375
7376 Sema &S = *getSema();
7377 Sema::GlobalMethodPool::iterator Pos
7378 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007379
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007380 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007381 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007382 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007383 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007384
7385 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7386 // when building a module we keep every method individually and may need to
7387 // update hasMoreThanOneDecl as we add the methods.
7388 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7389 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007390}
7391
Manman Rena0f31a02016-04-29 19:04:05 +00007392void ASTReader::updateOutOfDateSelector(Selector Sel) {
7393 if (SelectorOutOfDate[Sel])
7394 ReadMethodPool(Sel);
7395}
7396
Guy Benyei11169dd2012-12-18 14:30:41 +00007397void ASTReader::ReadKnownNamespaces(
7398 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7399 Namespaces.clear();
7400
7401 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7402 if (NamespaceDecl *Namespace
7403 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7404 Namespaces.push_back(Namespace);
7405 }
7406}
7407
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007408void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007409 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007410 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7411 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007412 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007413 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007414 Undefined.insert(std::make_pair(D, Loc));
7415 }
7416}
Nick Lewycky8334af82013-01-26 00:35:08 +00007417
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007418void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7419 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7420 Exprs) {
7421 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7422 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7423 uint64_t Count = DelayedDeleteExprs[Idx++];
7424 for (uint64_t C = 0; C < Count; ++C) {
7425 SourceLocation DeleteLoc =
7426 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7427 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7428 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7429 }
7430 }
7431}
7432
Guy Benyei11169dd2012-12-18 14:30:41 +00007433void ASTReader::ReadTentativeDefinitions(
7434 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7435 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7436 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7437 if (Var)
7438 TentativeDefs.push_back(Var);
7439 }
7440 TentativeDefinitions.clear();
7441}
7442
7443void ASTReader::ReadUnusedFileScopedDecls(
7444 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7445 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7446 DeclaratorDecl *D
7447 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7448 if (D)
7449 Decls.push_back(D);
7450 }
7451 UnusedFileScopedDecls.clear();
7452}
7453
7454void ASTReader::ReadDelegatingConstructors(
7455 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7456 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7457 CXXConstructorDecl *D
7458 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7459 if (D)
7460 Decls.push_back(D);
7461 }
7462 DelegatingCtorDecls.clear();
7463}
7464
7465void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7466 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7467 TypedefNameDecl *D
7468 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7469 if (D)
7470 Decls.push_back(D);
7471 }
7472 ExtVectorDecls.clear();
7473}
7474
Nico Weber72889432014-09-06 01:25:55 +00007475void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7476 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7477 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7478 ++I) {
7479 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7480 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7481 if (D)
7482 Decls.insert(D);
7483 }
7484 UnusedLocalTypedefNameCandidates.clear();
7485}
7486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487void ASTReader::ReadReferencedSelectors(
7488 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7489 if (ReferencedSelectorsData.empty())
7490 return;
7491
7492 // If there are @selector references added them to its pool. This is for
7493 // implementation of -Wselector.
7494 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7495 unsigned I = 0;
7496 while (I < DataSize) {
7497 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7498 SourceLocation SelLoc
7499 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7500 Sels.push_back(std::make_pair(Sel, SelLoc));
7501 }
7502 ReferencedSelectorsData.clear();
7503}
7504
7505void ASTReader::ReadWeakUndeclaredIdentifiers(
7506 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7507 if (WeakUndeclaredIdentifiers.empty())
7508 return;
7509
7510 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7511 IdentifierInfo *WeakId
7512 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7513 IdentifierInfo *AliasId
7514 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7515 SourceLocation Loc
7516 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7517 bool Used = WeakUndeclaredIdentifiers[I++];
7518 WeakInfo WI(AliasId, Loc);
7519 WI.setUsed(Used);
7520 WeakIDs.push_back(std::make_pair(WeakId, WI));
7521 }
7522 WeakUndeclaredIdentifiers.clear();
7523}
7524
7525void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7526 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7527 ExternalVTableUse VT;
7528 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7529 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7530 VT.DefinitionRequired = VTableUses[Idx++];
7531 VTables.push_back(VT);
7532 }
7533
7534 VTableUses.clear();
7535}
7536
7537void ASTReader::ReadPendingInstantiations(
7538 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7539 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7540 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7541 SourceLocation Loc
7542 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7543
7544 Pending.push_back(std::make_pair(D, Loc));
7545 }
7546 PendingInstantiations.clear();
7547}
7548
Richard Smithe40f2ba2013-08-07 21:41:30 +00007549void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007550 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007551 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7552 /* In loop */) {
7553 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7554
7555 LateParsedTemplate *LT = new LateParsedTemplate;
7556 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7557
7558 ModuleFile *F = getOwningModuleFile(LT->D);
7559 assert(F && "No module");
7560
7561 unsigned TokN = LateParsedTemplates[Idx++];
7562 LT->Toks.reserve(TokN);
7563 for (unsigned T = 0; T < TokN; ++T)
7564 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7565
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007566 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007567 }
7568
7569 LateParsedTemplates.clear();
7570}
7571
Guy Benyei11169dd2012-12-18 14:30:41 +00007572void ASTReader::LoadSelector(Selector Sel) {
7573 // It would be complicated to avoid reading the methods anyway. So don't.
7574 ReadMethodPool(Sel);
7575}
7576
7577void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7578 assert(ID && "Non-zero identifier ID required");
7579 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7580 IdentifiersLoaded[ID - 1] = II;
7581 if (DeserializationListener)
7582 DeserializationListener->IdentifierRead(ID, II);
7583}
7584
7585/// \brief Set the globally-visible declarations associated with the given
7586/// identifier.
7587///
7588/// If the AST reader is currently in a state where the given declaration IDs
7589/// cannot safely be resolved, they are queued until it is safe to resolve
7590/// them.
7591///
7592/// \param II an IdentifierInfo that refers to one or more globally-visible
7593/// declarations.
7594///
7595/// \param DeclIDs the set of declaration IDs with the name @p II that are
7596/// visible at global scope.
7597///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007598/// \param Decls if non-null, this vector will be populated with the set of
7599/// deserialized declarations. These declarations will not be pushed into
7600/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007601void
7602ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7603 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007604 SmallVectorImpl<Decl *> *Decls) {
7605 if (NumCurrentElementsDeserializing && !Decls) {
7606 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 return;
7608 }
7609
7610 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007611 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 // Queue this declaration so that it will be added to the
7613 // translation unit scope and identifier's declaration chain
7614 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007615 PreloadedDeclIDs.push_back(DeclIDs[I]);
7616 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007618
7619 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7620
7621 // If we're simply supposed to record the declarations, do so now.
7622 if (Decls) {
7623 Decls->push_back(D);
7624 continue;
7625 }
7626
7627 // Introduce this declaration into the translation-unit scope
7628 // and add it to the declaration chain for this identifier, so
7629 // that (unqualified) name lookup will find it.
7630 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007631 }
7632}
7633
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007634IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007636 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007637
7638 if (IdentifiersLoaded.empty()) {
7639 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007640 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 }
7642
7643 ID -= 1;
7644 if (!IdentifiersLoaded[ID]) {
7645 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7646 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7647 ModuleFile *M = I->second;
7648 unsigned Index = ID - M->BaseIdentifierID;
7649 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7650
7651 // All of the strings in the AST file are preceded by a 16-bit length.
7652 // Extract that 16-bit length to avoid having to execute strlen().
7653 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7654 // unsigned integers. This is important to avoid integer overflow when
7655 // we cast them to 'unsigned'.
7656 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7657 unsigned StrLen = (((unsigned) StrLenPtr[0])
7658 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007659 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7660 IdentifiersLoaded[ID] = &II;
7661 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007663 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 }
7665
7666 return IdentifiersLoaded[ID];
7667}
7668
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007669IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7670 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007671}
7672
7673IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7674 if (LocalID < NUM_PREDEF_IDENT_IDS)
7675 return LocalID;
7676
7677 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7678 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7679 assert(I != M.IdentifierRemap.end()
7680 && "Invalid index into identifier index remap");
7681
7682 return LocalID + I->second;
7683}
7684
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007685MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007686 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007687 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007688
7689 if (MacrosLoaded.empty()) {
7690 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007691 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 }
7693
7694 ID -= NUM_PREDEF_MACRO_IDS;
7695 if (!MacrosLoaded[ID]) {
7696 GlobalMacroMapType::iterator I
7697 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7698 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7699 ModuleFile *M = I->second;
7700 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007701 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7702
7703 if (DeserializationListener)
7704 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7705 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007706 }
7707
7708 return MacrosLoaded[ID];
7709}
7710
7711MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7712 if (LocalID < NUM_PREDEF_MACRO_IDS)
7713 return LocalID;
7714
7715 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7716 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7717 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7718
7719 return LocalID + I->second;
7720}
7721
7722serialization::SubmoduleID
7723ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7724 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7725 return LocalID;
7726
7727 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7728 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7729 assert(I != M.SubmoduleRemap.end()
7730 && "Invalid index into submodule index remap");
7731
7732 return LocalID + I->second;
7733}
7734
7735Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7736 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7737 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007738 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 }
7740
7741 if (GlobalID > SubmodulesLoaded.size()) {
7742 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007743 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007744 }
7745
7746 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7747}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007748
7749Module *ASTReader::getModule(unsigned ID) {
7750 return getSubmodule(ID);
7751}
7752
Richard Smithd88a7f12015-09-01 20:35:42 +00007753ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7754 if (ID & 1) {
7755 // It's a module, look it up by submodule ID.
7756 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7757 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7758 } else {
7759 // It's a prefix (preamble, PCH, ...). Look it up by index.
7760 unsigned IndexFromEnd = ID >> 1;
7761 assert(IndexFromEnd && "got reference to unknown module file");
7762 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7763 }
7764}
7765
7766unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7767 if (!F)
7768 return 1;
7769
7770 // For a file representing a module, use the submodule ID of the top-level
7771 // module as the file ID. For any other kind of file, the number of such
7772 // files loaded beforehand will be the same on reload.
7773 // FIXME: Is this true even if we have an explicit module file and a PCH?
7774 if (F->isModule())
7775 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7776
7777 auto PCHModules = getModuleManager().pch_modules();
7778 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7779 assert(I != PCHModules.end() && "emitting reference to unknown file");
7780 return (I - PCHModules.end()) << 1;
7781}
7782
Adrian Prantl15bcf702015-06-30 17:39:43 +00007783llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7784ASTReader::getSourceDescriptor(unsigned ID) {
7785 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007786 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007787
7788 // If there is only a single PCH, return it instead.
7789 // Chained PCH are not suported.
7790 if (ModuleMgr.size() == 1) {
7791 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007792 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007793 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7794 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7795 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007796 }
7797 return None;
7798}
7799
Guy Benyei11169dd2012-12-18 14:30:41 +00007800Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7801 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7802}
7803
7804Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7805 if (ID == 0)
7806 return Selector();
7807
7808 if (ID > SelectorsLoaded.size()) {
7809 Error("selector ID out of range in AST file");
7810 return Selector();
7811 }
7812
Craig Toppera13603a2014-05-22 05:54:18 +00007813 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 // Load this selector from the selector table.
7815 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7816 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7817 ModuleFile &M = *I->second;
7818 ASTSelectorLookupTrait Trait(*this, M);
7819 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7820 SelectorsLoaded[ID - 1] =
7821 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7822 if (DeserializationListener)
7823 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7824 }
7825
7826 return SelectorsLoaded[ID - 1];
7827}
7828
7829Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7830 return DecodeSelector(ID);
7831}
7832
7833uint32_t ASTReader::GetNumExternalSelectors() {
7834 // ID 0 (the null selector) is considered an external selector.
7835 return getTotalNumSelectors() + 1;
7836}
7837
7838serialization::SelectorID
7839ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7840 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7841 return LocalID;
7842
7843 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7844 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7845 assert(I != M.SelectorRemap.end()
7846 && "Invalid index into selector index remap");
7847
7848 return LocalID + I->second;
7849}
7850
7851DeclarationName
7852ASTReader::ReadDeclarationName(ModuleFile &F,
7853 const RecordData &Record, unsigned &Idx) {
7854 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7855 switch (Kind) {
7856 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007857 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007858
7859 case DeclarationName::ObjCZeroArgSelector:
7860 case DeclarationName::ObjCOneArgSelector:
7861 case DeclarationName::ObjCMultiArgSelector:
7862 return DeclarationName(ReadSelector(F, Record, Idx));
7863
7864 case DeclarationName::CXXConstructorName:
7865 return Context.DeclarationNames.getCXXConstructorName(
7866 Context.getCanonicalType(readType(F, Record, Idx)));
7867
7868 case DeclarationName::CXXDestructorName:
7869 return Context.DeclarationNames.getCXXDestructorName(
7870 Context.getCanonicalType(readType(F, Record, Idx)));
7871
7872 case DeclarationName::CXXConversionFunctionName:
7873 return Context.DeclarationNames.getCXXConversionFunctionName(
7874 Context.getCanonicalType(readType(F, Record, Idx)));
7875
7876 case DeclarationName::CXXOperatorName:
7877 return Context.DeclarationNames.getCXXOperatorName(
7878 (OverloadedOperatorKind)Record[Idx++]);
7879
7880 case DeclarationName::CXXLiteralOperatorName:
7881 return Context.DeclarationNames.getCXXLiteralOperatorName(
7882 GetIdentifierInfo(F, Record, Idx));
7883
7884 case DeclarationName::CXXUsingDirective:
7885 return DeclarationName::getUsingDirectiveName();
7886 }
7887
7888 llvm_unreachable("Invalid NameKind!");
7889}
7890
7891void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7892 DeclarationNameLoc &DNLoc,
7893 DeclarationName Name,
7894 const RecordData &Record, unsigned &Idx) {
7895 switch (Name.getNameKind()) {
7896 case DeclarationName::CXXConstructorName:
7897 case DeclarationName::CXXDestructorName:
7898 case DeclarationName::CXXConversionFunctionName:
7899 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7900 break;
7901
7902 case DeclarationName::CXXOperatorName:
7903 DNLoc.CXXOperatorName.BeginOpNameLoc
7904 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7905 DNLoc.CXXOperatorName.EndOpNameLoc
7906 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7907 break;
7908
7909 case DeclarationName::CXXLiteralOperatorName:
7910 DNLoc.CXXLiteralOperatorName.OpNameLoc
7911 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7912 break;
7913
7914 case DeclarationName::Identifier:
7915 case DeclarationName::ObjCZeroArgSelector:
7916 case DeclarationName::ObjCOneArgSelector:
7917 case DeclarationName::ObjCMultiArgSelector:
7918 case DeclarationName::CXXUsingDirective:
7919 break;
7920 }
7921}
7922
7923void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7924 DeclarationNameInfo &NameInfo,
7925 const RecordData &Record, unsigned &Idx) {
7926 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7927 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7928 DeclarationNameLoc DNLoc;
7929 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7930 NameInfo.setInfo(DNLoc);
7931}
7932
7933void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7934 const RecordData &Record, unsigned &Idx) {
7935 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7936 unsigned NumTPLists = Record[Idx++];
7937 Info.NumTemplParamLists = NumTPLists;
7938 if (NumTPLists) {
7939 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007940 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7942 }
7943}
7944
7945TemplateName
7946ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7947 unsigned &Idx) {
7948 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7949 switch (Kind) {
7950 case TemplateName::Template:
7951 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7952
7953 case TemplateName::OverloadedTemplate: {
7954 unsigned size = Record[Idx++];
7955 UnresolvedSet<8> Decls;
7956 while (size--)
7957 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7958
7959 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7960 }
7961
7962 case TemplateName::QualifiedTemplate: {
7963 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7964 bool hasTemplKeyword = Record[Idx++];
7965 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7966 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7967 }
7968
7969 case TemplateName::DependentTemplate: {
7970 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7971 if (Record[Idx++]) // isIdentifier
7972 return Context.getDependentTemplateName(NNS,
7973 GetIdentifierInfo(F, Record,
7974 Idx));
7975 return Context.getDependentTemplateName(NNS,
7976 (OverloadedOperatorKind)Record[Idx++]);
7977 }
7978
7979 case TemplateName::SubstTemplateTemplateParm: {
7980 TemplateTemplateParmDecl *param
7981 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7982 if (!param) return TemplateName();
7983 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7984 return Context.getSubstTemplateTemplateParm(param, replacement);
7985 }
7986
7987 case TemplateName::SubstTemplateTemplateParmPack: {
7988 TemplateTemplateParmDecl *Param
7989 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7990 if (!Param)
7991 return TemplateName();
7992
7993 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7994 if (ArgPack.getKind() != TemplateArgument::Pack)
7995 return TemplateName();
7996
7997 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7998 }
7999 }
8000
8001 llvm_unreachable("Unhandled template name kind!");
8002}
8003
Richard Smith2bb3c342015-08-09 01:05:31 +00008004TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8005 const RecordData &Record,
8006 unsigned &Idx,
8007 bool Canonicalize) {
8008 if (Canonicalize) {
8009 // The caller wants a canonical template argument. Sometimes the AST only
8010 // wants template arguments in canonical form (particularly as the template
8011 // argument lists of template specializations) so ensure we preserve that
8012 // canonical form across serialization.
8013 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8014 return Context.getCanonicalTemplateArgument(Arg);
8015 }
8016
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8018 switch (Kind) {
8019 case TemplateArgument::Null:
8020 return TemplateArgument();
8021 case TemplateArgument::Type:
8022 return TemplateArgument(readType(F, Record, Idx));
8023 case TemplateArgument::Declaration: {
8024 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008025 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 }
8027 case TemplateArgument::NullPtr:
8028 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8029 case TemplateArgument::Integral: {
8030 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8031 QualType T = readType(F, Record, Idx);
8032 return TemplateArgument(Context, Value, T);
8033 }
8034 case TemplateArgument::Template:
8035 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8036 case TemplateArgument::TemplateExpansion: {
8037 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008038 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 if (unsigned NumExpansions = Record[Idx++])
8040 NumTemplateExpansions = NumExpansions - 1;
8041 return TemplateArgument(Name, NumTemplateExpansions);
8042 }
8043 case TemplateArgument::Expression:
8044 return TemplateArgument(ReadExpr(F));
8045 case TemplateArgument::Pack: {
8046 unsigned NumArgs = Record[Idx++];
8047 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8048 for (unsigned I = 0; I != NumArgs; ++I)
8049 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008050 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 }
8052 }
8053
8054 llvm_unreachable("Unhandled template argument kind!");
8055}
8056
8057TemplateParameterList *
8058ASTReader::ReadTemplateParameterList(ModuleFile &F,
8059 const RecordData &Record, unsigned &Idx) {
8060 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8061 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8062 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8063
8064 unsigned NumParams = Record[Idx++];
8065 SmallVector<NamedDecl *, 16> Params;
8066 Params.reserve(NumParams);
8067 while (NumParams--)
8068 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8069
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008070 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 TemplateParameterList* TemplateParams =
8072 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008073 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 return TemplateParams;
8075}
8076
8077void
8078ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008079ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008081 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 unsigned NumTemplateArgs = Record[Idx++];
8083 TemplArgs.reserve(NumTemplateArgs);
8084 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008085 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008086}
8087
8088/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008089void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 const RecordData &Record, unsigned &Idx) {
8091 unsigned NumDecls = Record[Idx++];
8092 Set.reserve(Context, NumDecls);
8093 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008094 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008096 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 }
8098}
8099
8100CXXBaseSpecifier
8101ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8102 const RecordData &Record, unsigned &Idx) {
8103 bool isVirtual = static_cast<bool>(Record[Idx++]);
8104 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8105 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8106 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8107 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8108 SourceRange Range = ReadSourceRange(F, Record, Idx);
8109 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8110 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8111 EllipsisLoc);
8112 Result.setInheritConstructors(inheritConstructors);
8113 return Result;
8114}
8115
Richard Smithc2bb8182015-03-24 06:36:48 +00008116CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008117ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8118 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008120 assert(NumInitializers && "wrote ctor initializers but have no inits");
8121 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8122 for (unsigned i = 0; i != NumInitializers; ++i) {
8123 TypeSourceInfo *TInfo = nullptr;
8124 bool IsBaseVirtual = false;
8125 FieldDecl *Member = nullptr;
8126 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008127
Richard Smithc2bb8182015-03-24 06:36:48 +00008128 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8129 switch (Type) {
8130 case CTOR_INITIALIZER_BASE:
8131 TInfo = GetTypeSourceInfo(F, Record, Idx);
8132 IsBaseVirtual = Record[Idx++];
8133 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008134
Richard Smithc2bb8182015-03-24 06:36:48 +00008135 case CTOR_INITIALIZER_DELEGATING:
8136 TInfo = GetTypeSourceInfo(F, Record, Idx);
8137 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008138
Richard Smithc2bb8182015-03-24 06:36:48 +00008139 case CTOR_INITIALIZER_MEMBER:
8140 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8141 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008142
Richard Smithc2bb8182015-03-24 06:36:48 +00008143 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8144 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008147
8148 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8149 Expr *Init = ReadExpr(F);
8150 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8151 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8152 bool IsWritten = Record[Idx++];
8153 unsigned SourceOrderOrNumArrayIndices;
8154 SmallVector<VarDecl *, 8> Indices;
8155 if (IsWritten) {
8156 SourceOrderOrNumArrayIndices = Record[Idx++];
8157 } else {
8158 SourceOrderOrNumArrayIndices = Record[Idx++];
8159 Indices.reserve(SourceOrderOrNumArrayIndices);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008160 for (unsigned i = 0; i != SourceOrderOrNumArrayIndices; ++i)
Richard Smithc2bb8182015-03-24 06:36:48 +00008161 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8162 }
8163
8164 CXXCtorInitializer *BOMInit;
8165 if (Type == CTOR_INITIALIZER_BASE) {
8166 BOMInit = new (Context)
8167 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8168 RParenLoc, MemberOrEllipsisLoc);
8169 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8170 BOMInit = new (Context)
8171 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8172 } else if (IsWritten) {
8173 if (Member)
8174 BOMInit = new (Context) CXXCtorInitializer(
8175 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8176 else
8177 BOMInit = new (Context)
8178 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8179 LParenLoc, Init, RParenLoc);
8180 } else {
8181 if (IndirectMember) {
8182 assert(Indices.empty() && "Indirect field improperly initialized");
8183 BOMInit = new (Context)
8184 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8185 LParenLoc, Init, RParenLoc);
8186 } else {
8187 BOMInit = CXXCtorInitializer::Create(
8188 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8189 Indices.data(), Indices.size());
8190 }
8191 }
8192
8193 if (IsWritten)
8194 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8195 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 }
8197
Richard Smithc2bb8182015-03-24 06:36:48 +00008198 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008199}
8200
8201NestedNameSpecifier *
8202ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8203 const RecordData &Record, unsigned &Idx) {
8204 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008205 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008206 for (unsigned I = 0; I != N; ++I) {
8207 NestedNameSpecifier::SpecifierKind Kind
8208 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8209 switch (Kind) {
8210 case NestedNameSpecifier::Identifier: {
8211 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8212 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8213 break;
8214 }
8215
8216 case NestedNameSpecifier::Namespace: {
8217 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8218 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8219 break;
8220 }
8221
8222 case NestedNameSpecifier::NamespaceAlias: {
8223 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8224 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8225 break;
8226 }
8227
8228 case NestedNameSpecifier::TypeSpec:
8229 case NestedNameSpecifier::TypeSpecWithTemplate: {
8230 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8231 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008232 return nullptr;
8233
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 bool Template = Record[Idx++];
8235 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8236 break;
8237 }
8238
8239 case NestedNameSpecifier::Global: {
8240 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8241 // No associated value, and there can't be a prefix.
8242 break;
8243 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008244
8245 case NestedNameSpecifier::Super: {
8246 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8247 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8248 break;
8249 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 }
8251 Prev = NNS;
8252 }
8253 return NNS;
8254}
8255
8256NestedNameSpecifierLoc
8257ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8258 unsigned &Idx) {
8259 unsigned N = Record[Idx++];
8260 NestedNameSpecifierLocBuilder Builder;
8261 for (unsigned I = 0; I != N; ++I) {
8262 NestedNameSpecifier::SpecifierKind Kind
8263 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8264 switch (Kind) {
8265 case NestedNameSpecifier::Identifier: {
8266 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8267 SourceRange Range = ReadSourceRange(F, Record, Idx);
8268 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8269 break;
8270 }
8271
8272 case NestedNameSpecifier::Namespace: {
8273 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8274 SourceRange Range = ReadSourceRange(F, Record, Idx);
8275 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8276 break;
8277 }
8278
8279 case NestedNameSpecifier::NamespaceAlias: {
8280 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8281 SourceRange Range = ReadSourceRange(F, Record, Idx);
8282 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8283 break;
8284 }
8285
8286 case NestedNameSpecifier::TypeSpec:
8287 case NestedNameSpecifier::TypeSpecWithTemplate: {
8288 bool Template = Record[Idx++];
8289 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8290 if (!T)
8291 return NestedNameSpecifierLoc();
8292 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8293
8294 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8295 Builder.Extend(Context,
8296 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8297 T->getTypeLoc(), ColonColonLoc);
8298 break;
8299 }
8300
8301 case NestedNameSpecifier::Global: {
8302 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8303 Builder.MakeGlobal(Context, ColonColonLoc);
8304 break;
8305 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008306
8307 case NestedNameSpecifier::Super: {
8308 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8309 SourceRange Range = ReadSourceRange(F, Record, Idx);
8310 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8311 break;
8312 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008313 }
8314 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008315
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 return Builder.getWithLocInContext(Context);
8317}
8318
8319SourceRange
8320ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8321 unsigned &Idx) {
8322 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8323 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8324 return SourceRange(beg, end);
8325}
8326
8327/// \brief Read an integral value
8328llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8329 unsigned BitWidth = Record[Idx++];
8330 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8331 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8332 Idx += NumWords;
8333 return Result;
8334}
8335
8336/// \brief Read a signed integral value
8337llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8338 bool isUnsigned = Record[Idx++];
8339 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8340}
8341
8342/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008343llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8344 const llvm::fltSemantics &Sem,
8345 unsigned &Idx) {
8346 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008347}
8348
8349// \brief Read a string
8350std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8351 unsigned Len = Record[Idx++];
8352 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8353 Idx += Len;
8354 return Result;
8355}
8356
Richard Smith7ed1bc92014-12-05 22:42:13 +00008357std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8358 unsigned &Idx) {
8359 std::string Filename = ReadString(Record, Idx);
8360 ResolveImportedPath(F, Filename);
8361 return Filename;
8362}
8363
Guy Benyei11169dd2012-12-18 14:30:41 +00008364VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8365 unsigned &Idx) {
8366 unsigned Major = Record[Idx++];
8367 unsigned Minor = Record[Idx++];
8368 unsigned Subminor = Record[Idx++];
8369 if (Minor == 0)
8370 return VersionTuple(Major);
8371 if (Subminor == 0)
8372 return VersionTuple(Major, Minor - 1);
8373 return VersionTuple(Major, Minor - 1, Subminor - 1);
8374}
8375
8376CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8377 const RecordData &Record,
8378 unsigned &Idx) {
8379 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8380 return CXXTemporary::Create(Context, Decl);
8381}
8382
8383DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008384 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008385}
8386
8387DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8388 return Diags.Report(Loc, DiagID);
8389}
8390
8391/// \brief Retrieve the identifier table associated with the
8392/// preprocessor.
8393IdentifierTable &ASTReader::getIdentifierTable() {
8394 return PP.getIdentifierTable();
8395}
8396
8397/// \brief Record that the given ID maps to the given switch-case
8398/// statement.
8399void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008400 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 "Already have a SwitchCase with this ID");
8402 (*CurrSwitchCaseStmts)[ID] = SC;
8403}
8404
8405/// \brief Retrieve the switch-case statement with the given ID.
8406SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008407 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 return (*CurrSwitchCaseStmts)[ID];
8409}
8410
8411void ASTReader::ClearSwitchCaseIDs() {
8412 CurrSwitchCaseStmts->clear();
8413}
8414
8415void ASTReader::ReadComments() {
8416 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008417 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 serialization::ModuleFile *> >::iterator
8419 I = CommentsCursors.begin(),
8420 E = CommentsCursors.end();
8421 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008422 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008423 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008424 serialization::ModuleFile &F = *I->second;
8425 SavedStreamPosition SavedPosition(Cursor);
8426
8427 RecordData Record;
8428 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008429 llvm::BitstreamEntry Entry =
8430 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008431
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008432 switch (Entry.Kind) {
8433 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8434 case llvm::BitstreamEntry::Error:
8435 Error("malformed block record in AST file");
8436 return;
8437 case llvm::BitstreamEntry::EndBlock:
8438 goto NextCursor;
8439 case llvm::BitstreamEntry::Record:
8440 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008441 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008442 }
8443
8444 // Read a record.
8445 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008446 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008447 case COMMENTS_RAW_COMMENT: {
8448 unsigned Idx = 0;
8449 SourceRange SR = ReadSourceRange(F, Record, Idx);
8450 RawComment::CommentKind Kind =
8451 (RawComment::CommentKind) Record[Idx++];
8452 bool IsTrailingComment = Record[Idx++];
8453 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008454 Comments.push_back(new (Context) RawComment(
8455 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8456 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008457 break;
8458 }
8459 }
8460 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008461 NextCursor:
8462 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008464}
8465
Richard Smithcd45dbc2014-04-19 03:48:30 +00008466std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8467 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008468 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008469 return M->getFullModuleName();
8470
8471 // Otherwise, use the name of the top-level module the decl is within.
8472 if (ModuleFile *M = getOwningModuleFile(D))
8473 return M->ModuleName;
8474
8475 // Not from a module.
8476 return "";
8477}
8478
Guy Benyei11169dd2012-12-18 14:30:41 +00008479void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008480 while (!PendingIdentifierInfos.empty() ||
8481 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008482 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008483 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008484 // If any identifiers with corresponding top-level declarations have
8485 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008486 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8487 TopLevelDeclsMap;
8488 TopLevelDeclsMap TopLevelDecls;
8489
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008491 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008492 SmallVector<uint32_t, 4> DeclIDs =
8493 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008494 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008495
8496 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008498
Richard Smith851072e2014-05-19 20:59:20 +00008499 // For each decl chain that we wanted to complete while deserializing, mark
8500 // it as "still needs to be completed".
8501 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8502 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8503 }
8504 PendingIncompleteDeclChains.clear();
8505
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008507 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008508 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008509 PendingDeclChains.clear();
8510
Douglas Gregor6168bd22013-02-18 15:53:43 +00008511 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008512 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8513 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008514 IdentifierInfo *II = TLD->first;
8515 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008516 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008517 }
8518 }
8519
Guy Benyei11169dd2012-12-18 14:30:41 +00008520 // Load any pending macro definitions.
8521 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008522 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8523 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8524 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8525 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008526 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008527 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008528 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008529 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008530 resolvePendingMacro(II, Info);
8531 }
8532 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008533 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008534 ++IDIdx) {
8535 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008536 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008537 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008538 }
8539 }
8540 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008541
8542 // Wire up the DeclContexts for Decls that we delayed setting until
8543 // recursive loading is completed.
8544 while (!PendingDeclContextInfos.empty()) {
8545 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8546 PendingDeclContextInfos.pop_front();
8547 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8548 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8549 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8550 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008551
Richard Smithd1c46742014-04-30 02:24:17 +00008552 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008553 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008554 auto Update = PendingUpdateRecords.pop_back_val();
8555 ReadingKindTracker ReadingKind(Read_Decl, *this);
8556 loadDeclUpdateRecords(Update.first, Update.second);
8557 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 }
Richard Smith8a639892015-01-24 01:07:20 +00008559
8560 // At this point, all update records for loaded decls are in place, so any
8561 // fake class definitions should have become real.
8562 assert(PendingFakeDefinitionData.empty() &&
8563 "faked up a class definition but never saw the real one");
8564
Guy Benyei11169dd2012-12-18 14:30:41 +00008565 // If we deserialized any C++ or Objective-C class definitions, any
8566 // Objective-C protocol definitions, or any redeclarable templates, make sure
8567 // that all redeclarations point to the definitions. Note that this can only
8568 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008569 for (Decl *D : PendingDefinitions) {
8570 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008571 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008572 // Make sure that the TagType points at the definition.
8573 const_cast<TagType*>(TagT)->decl = TD;
8574 }
Richard Smith8ce51082015-03-11 01:44:51 +00008575
Craig Topperc6914d02014-08-25 04:15:02 +00008576 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008577 for (auto *R = getMostRecentExistingDecl(RD); R;
8578 R = R->getPreviousDecl()) {
8579 assert((R == D) ==
8580 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008581 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008582 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008584 }
8585
8586 continue;
8587 }
Richard Smith8ce51082015-03-11 01:44:51 +00008588
Craig Topperc6914d02014-08-25 04:15:02 +00008589 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008590 // Make sure that the ObjCInterfaceType points at the definition.
8591 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8592 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008593
8594 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8595 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8596
Guy Benyei11169dd2012-12-18 14:30:41 +00008597 continue;
8598 }
Richard Smith8ce51082015-03-11 01:44:51 +00008599
Craig Topperc6914d02014-08-25 04:15:02 +00008600 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008601 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8602 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8603
Guy Benyei11169dd2012-12-18 14:30:41 +00008604 continue;
8605 }
Richard Smith8ce51082015-03-11 01:44:51 +00008606
Craig Topperc6914d02014-08-25 04:15:02 +00008607 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008608 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8609 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 }
8611 PendingDefinitions.clear();
8612
8613 // Load the bodies of any functions or methods we've encountered. We do
8614 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008615 // have been fully wired up (hasBody relies on this).
8616 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008617 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8618 PBEnd = PendingBodies.end();
8619 PB != PBEnd; ++PB) {
8620 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8621 // FIXME: Check for =delete/=default?
8622 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008623 const FunctionDecl *Defn = nullptr;
8624 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008625 FD->setLazyBody(PB->second);
Eric Liu762b4882016-09-14 10:05:10 +00008626 else
Richard Smith6561f922016-09-12 21:06:40 +00008627 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008628 continue;
8629 }
8630
8631 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8632 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8633 MD->setLazyBody(PB->second);
8634 }
8635 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008636
8637 // Do some cleanup.
8638 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8639 getContext().deduplicateMergedDefinitonsFor(ND);
8640 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008641}
8642
8643void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008644 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8645 return;
8646
Richard Smitha0ce9c42014-07-29 23:23:27 +00008647 // Trigger the import of the full definition of each class that had any
8648 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008649 // These updates may in turn find and diagnose some ODR failures, so take
8650 // ownership of the set first.
8651 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8652 PendingOdrMergeFailures.clear();
8653 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008654 Merge.first->buildLookup();
8655 Merge.first->decls_begin();
8656 Merge.first->bases_begin();
8657 Merge.first->vbases_begin();
8658 for (auto *RD : Merge.second) {
8659 RD->decls_begin();
8660 RD->bases_begin();
8661 RD->vbases_begin();
8662 }
8663 }
8664
8665 // For each declaration from a merged context, check that the canonical
8666 // definition of that context also contains a declaration of the same
8667 // entity.
8668 //
8669 // Caution: this loop does things that might invalidate iterators into
8670 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8671 while (!PendingOdrMergeChecks.empty()) {
8672 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8673
8674 // FIXME: Skip over implicit declarations for now. This matters for things
8675 // like implicitly-declared special member functions. This isn't entirely
8676 // correct; we can end up with multiple unmerged declarations of the same
8677 // implicit entity.
8678 if (D->isImplicit())
8679 continue;
8680
8681 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008682
8683 bool Found = false;
8684 const Decl *DCanon = D->getCanonicalDecl();
8685
Richard Smith01bdb7a2014-08-28 05:44:07 +00008686 for (auto RI : D->redecls()) {
8687 if (RI->getLexicalDeclContext() == CanonDef) {
8688 Found = true;
8689 break;
8690 }
8691 }
8692 if (Found)
8693 continue;
8694
Richard Smith0f4e2c42015-08-06 04:23:48 +00008695 // Quick check failed, time to do the slow thing. Note, we can't just
8696 // look up the name of D in CanonDef here, because the member that is
8697 // in CanonDef might not be found by name lookup (it might have been
8698 // replaced by a more recent declaration in the lookup table), and we
8699 // can't necessarily find it in the redeclaration chain because it might
8700 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008701 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008702 for (auto *CanonMember : CanonDef->decls()) {
8703 if (CanonMember->getCanonicalDecl() == DCanon) {
8704 // This can happen if the declaration is merely mergeable and not
8705 // actually redeclarable (we looked for redeclarations earlier).
8706 //
8707 // FIXME: We should be able to detect this more efficiently, without
8708 // pulling in all of the members of CanonDef.
8709 Found = true;
8710 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008711 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008712 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8713 if (ND->getDeclName() == D->getDeclName())
8714 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008715 }
8716
8717 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008718 // The AST doesn't like TagDecls becoming invalid after they've been
8719 // completed. We only really need to mark FieldDecls as invalid here.
8720 if (!isa<TagDecl>(D))
8721 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008722
8723 // Ensure we don't accidentally recursively enter deserialization while
8724 // we're producing our diagnostic.
8725 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008726
8727 std::string CanonDefModule =
8728 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8729 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8730 << D << getOwningModuleNameForDiagnostic(D)
8731 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8732
8733 if (Candidates.empty())
8734 Diag(cast<Decl>(CanonDef)->getLocation(),
8735 diag::note_module_odr_violation_no_possible_decls) << D;
8736 else {
8737 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8738 Diag(Candidates[I]->getLocation(),
8739 diag::note_module_odr_violation_possible_decl)
8740 << Candidates[I];
8741 }
8742
8743 DiagnosedOdrMergeFailures.insert(CanonDef);
8744 }
8745 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008746
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008747 if (OdrMergeFailures.empty())
8748 return;
8749
8750 // Ensure we don't accidentally recursively enter deserialization while
8751 // we're producing our diagnostics.
8752 Deserializing RecursionGuard(this);
8753
Richard Smithcd45dbc2014-04-19 03:48:30 +00008754 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008755 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008756 // If we've already pointed out a specific problem with this class, don't
8757 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008758 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008759 continue;
8760
8761 bool Diagnosed = false;
8762 for (auto *RD : Merge.second) {
8763 // Multiple different declarations got merged together; tell the user
8764 // where they came from.
8765 if (Merge.first != RD) {
8766 // FIXME: Walk the definition, figure out what's different,
8767 // and diagnose that.
8768 if (!Diagnosed) {
8769 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8770 Diag(Merge.first->getLocation(),
8771 diag::err_module_odr_violation_different_definitions)
8772 << Merge.first << Module.empty() << Module;
8773 Diagnosed = true;
8774 }
8775
8776 Diag(RD->getLocation(),
8777 diag::note_module_odr_violation_different_definitions)
8778 << getOwningModuleNameForDiagnostic(RD);
8779 }
8780 }
8781
8782 if (!Diagnosed) {
8783 // All definitions are updates to the same declaration. This happens if a
8784 // module instantiates the declaration of a class template specialization
8785 // and two or more other modules instantiate its definition.
8786 //
8787 // FIXME: Indicate which modules had instantiations of this definition.
8788 // FIXME: How can this even happen?
8789 Diag(Merge.first->getLocation(),
8790 diag::err_module_odr_violation_different_instantiations)
8791 << Merge.first;
8792 }
8793 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008794}
8795
Richard Smithce18a182015-07-14 00:26:00 +00008796void ASTReader::StartedDeserializing() {
8797 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8798 ReadTimer->startTimer();
8799}
8800
Guy Benyei11169dd2012-12-18 14:30:41 +00008801void ASTReader::FinishedDeserializing() {
8802 assert(NumCurrentElementsDeserializing &&
8803 "FinishedDeserializing not paired with StartedDeserializing");
8804 if (NumCurrentElementsDeserializing == 1) {
8805 // We decrease NumCurrentElementsDeserializing only after pending actions
8806 // are finished, to avoid recursively re-calling finishPendingActions().
8807 finishPendingActions();
8808 }
8809 --NumCurrentElementsDeserializing;
8810
Richard Smitha0ce9c42014-07-29 23:23:27 +00008811 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008812 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008813 while (!PendingExceptionSpecUpdates.empty()) {
8814 auto Updates = std::move(PendingExceptionSpecUpdates);
8815 PendingExceptionSpecUpdates.clear();
8816 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008817 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008818 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008819 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008820 if (auto *Listener = Context.getASTMutationListener())
8821 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008822 for (auto *Redecl : Update.second->redecls())
8823 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008824 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008825 }
8826
Richard Smithce18a182015-07-14 00:26:00 +00008827 if (ReadTimer)
8828 ReadTimer->stopTimer();
8829
Richard Smith0f4e2c42015-08-06 04:23:48 +00008830 diagnoseOdrViolations();
8831
Richard Smith04d05b52014-03-23 00:27:18 +00008832 // We are not in recursive loading, so it's safe to pass the "interesting"
8833 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008834 if (Consumer)
8835 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008836 }
8837}
8838
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008839void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008840 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8841 // Remove any fake results before adding any real ones.
8842 auto It = PendingFakeLookupResults.find(II);
8843 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008844 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008845 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008846 // FIXME: this works around module+PCH performance issue.
8847 // Rather than erase the result from the map, which is O(n), just clear
8848 // the vector of NamedDecls.
8849 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008850 }
8851 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008852
8853 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8854 SemaObj->TUScope->AddDecl(D);
8855 } else if (SemaObj->TUScope) {
8856 // Adding the decl to IdResolver may have failed because it was already in
8857 // (even though it was not added in scope). If it is already in, make sure
8858 // it gets in the scope as well.
8859 if (std::find(SemaObj->IdResolver.begin(Name),
8860 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8861 SemaObj->TUScope->AddDecl(D);
8862 }
8863}
8864
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008865ASTReader::ASTReader(
8866 Preprocessor &PP, ASTContext &Context,
8867 const PCHContainerReader &PCHContainerRdr,
8868 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8869 StringRef isysroot, bool DisableValidation,
8870 bool AllowASTWithCompilerErrors,
8871 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8872 bool UseGlobalIndex,
8873 std::unique_ptr<llvm::Timer> ReadTimer)
Yaxun Liu43712e02016-09-07 18:40:20 +00008874 : Listener(DisableValidation ?
8875 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8876 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8877 DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008878 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008879 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008880 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008881 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smith10379092016-05-06 23:14:07 +00008882 DummyIdResolver(PP),
Richard Smithce18a182015-07-14 00:26:00 +00008883 ReadTimer(std::move(ReadTimer)),
Nico Weber779355f2016-03-02 23:22:00 +00008884 PragmaMSStructState(-1),
Nico Weber42932312016-03-03 00:17:35 +00008885 PragmaMSPointersToMembersState(-1),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008886 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008887 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8888 AllowConfigurationMismatch(AllowConfigurationMismatch),
8889 ValidateSystemInputs(ValidateSystemInputs),
8890 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008891 ProcessingUpdateRecords(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008892 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8893 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8894 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8895 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008896 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8897 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8898 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8899 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8900 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8901 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008902 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008904
8905 for (const auto &Ext : Extensions) {
8906 auto BlockName = Ext->getExtensionMetadata().BlockName;
8907 auto Known = ModuleFileExtensions.find(BlockName);
8908 if (Known != ModuleFileExtensions.end()) {
8909 Diags.Report(diag::warn_duplicate_module_file_extension)
8910 << BlockName;
8911 continue;
8912 }
8913
8914 ModuleFileExtensions.insert({BlockName, Ext});
8915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008916}
8917
8918ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008919 if (OwnsDeserializationListener)
8920 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008921}
Richard Smith10379092016-05-06 23:14:07 +00008922
8923IdentifierResolver &ASTReader::getIdResolver() {
8924 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8925}