blob: 61b5a822c55200d9fad5ee0b81c835c8ce47eedd [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000029#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/Type.h"
32#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/UnresolvedSet.h"
34#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000035#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "clang/Basic/FileSystemOptions.h"
39#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000040#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "clang/Basic/ObjCRuntime.h"
42#include "clang/Basic/OperatorKinds.h"
43#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "clang/Basic/TargetInfo.h"
48#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "clang/Basic/Version.h"
51#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "clang/Lex/HeaderSearch.h"
54#include "clang/Lex/HeaderSearchOptions.h"
55#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include "clang/Lex/PreprocessingRecord.h"
58#include "clang/Lex/Preprocessor.h"
59#include "clang/Lex/PreprocessorOptions.h"
60#include "clang/Sema/Scope.h"
61#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000064#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000065#include "clang/Serialization/ModuleManager.h"
66#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000067#include "llvm/ADT/APFloat.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000070#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000074#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000075#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000076#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000077#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000078#include "llvm/Support/ErrorHandling.h"
79#include "llvm/Support/FileSystem.h"
80#include "llvm/Support/MemoryBuffer.h"
81#include "llvm/Support/Path.h"
82#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000083#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000085#include <cassert>
86#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000087#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include <cstring>
89#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000090#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000091#include <limits>
92#include <map>
93#include <memory>
94#include <new>
95#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000096#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include <tuple>
98#include <utility>
99#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000100
101using namespace clang;
102using namespace clang::serialization;
103using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000104using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000105
Ben Langmuircb69b572014-03-07 06:40:32 +0000106//===----------------------------------------------------------------------===//
107// ChainedASTReaderListener implementation
108//===----------------------------------------------------------------------===//
109
110bool
111ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112 return First->ReadFullVersionInformation(FullVersion) ||
113 Second->ReadFullVersionInformation(FullVersion);
114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000115
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000116void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117 First->ReadModuleName(ModuleName);
118 Second->ReadModuleName(ModuleName);
119}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000121void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122 First->ReadModuleMapFile(ModuleMapPath);
123 Second->ReadModuleMapFile(ModuleMapPath);
124}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000125
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000126bool
127ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
128 bool Complain,
129 bool AllowCompatibleDifferences) {
130 return First->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences) ||
132 Second->ReadLanguageOptions(LangOpts, Complain,
133 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000134}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000135
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000136bool ChainedASTReaderListener::ReadTargetOptions(
137 const TargetOptions &TargetOpts, bool Complain,
138 bool AllowCompatibleDifferences) {
139 return First->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences) ||
141 Second->ReadTargetOptions(TargetOpts, Complain,
142 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000143}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000144
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000147 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148 Second->ReadDiagnosticOptions(DiagOpts, Complain);
149}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000150
Ben Langmuircb69b572014-03-07 06:40:32 +0000151bool
152ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
153 bool Complain) {
154 return First->ReadFileSystemOptions(FSOpts, Complain) ||
155 Second->ReadFileSystemOptions(FSOpts, Complain);
156}
157
158bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
160 bool Complain) {
161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162 Complain) ||
163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
164 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000165}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000166
Ben Langmuircb69b572014-03-07 06:40:32 +0000167bool ChainedASTReaderListener::ReadPreprocessorOptions(
168 const PreprocessorOptions &PPOpts, bool Complain,
169 std::string &SuggestedPredefines) {
170 return First->ReadPreprocessorOptions(PPOpts, Complain,
171 SuggestedPredefines) ||
172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
173}
174void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
175 unsigned Value) {
176 First->ReadCounter(M, Value);
177 Second->ReadCounter(M, Value);
178}
179bool ChainedASTReaderListener::needsInputFileVisitation() {
180 return First->needsInputFileVisitation() ||
181 Second->needsInputFileVisitation();
182}
183bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184 return First->needsSystemInputFileVisitation() ||
185 Second->needsSystemInputFileVisitation();
186}
Richard Smith216a3bd2015-08-13 17:57:10 +0000187void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
188 ModuleKind Kind) {
189 First->visitModuleFile(Filename, Kind);
190 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000191}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000192
Ben Langmuircb69b572014-03-07 06:40:32 +0000193bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000194 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000195 bool isOverridden,
196 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000197 bool Continue = false;
198 if (First->needsInputFileVisitation() &&
199 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
201 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000202 if (Second->needsInputFileVisitation() &&
203 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
205 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000206 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000207}
208
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000209void ChainedASTReaderListener::readModuleFileExtension(
210 const ModuleFileExtensionMetadata &Metadata) {
211 First->readModuleFileExtension(Metadata);
212 Second->readModuleFileExtension(Metadata);
213}
214
Guy Benyei11169dd2012-12-18 14:30:41 +0000215//===----------------------------------------------------------------------===//
216// PCH validator implementation
217//===----------------------------------------------------------------------===//
218
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000219ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000220
221/// \brief Compare the given set of language options against an existing set of
222/// language options.
223///
224/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000225/// \param AllowCompatibleDifferences If true, differences between compatible
226/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000227///
228/// \returns true if the languagae options mis-match, false otherwise.
229static bool checkLanguageOptions(const LangOptions &LangOpts,
230 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000231 DiagnosticsEngine *Diags,
232 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000233#define LANGOPT(Name, Bits, Default, Description) \
234 if (ExistingLangOpts.Name != LangOpts.Name) { \
235 if (Diags) \
236 Diags->Report(diag::err_pch_langopt_mismatch) \
237 << Description << LangOpts.Name << ExistingLangOpts.Name; \
238 return true; \
239 }
240
241#define VALUE_LANGOPT(Name, Bits, Default, Description) \
242 if (ExistingLangOpts.Name != LangOpts.Name) { \
243 if (Diags) \
244 Diags->Report(diag::err_pch_langopt_value_mismatch) \
245 << Description; \
246 return true; \
247 }
248
249#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
251 if (Diags) \
252 Diags->Report(diag::err_pch_langopt_value_mismatch) \
253 << Description; \
254 return true; \
255 }
256
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000257#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
258 if (!AllowCompatibleDifferences) \
259 LANGOPT(Name, Bits, Default, Description)
260
261#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
262 if (!AllowCompatibleDifferences) \
263 ENUM_LANGOPT(Name, Bits, Default, Description)
264
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000265#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266 if (!AllowCompatibleDifferences) \
267 VALUE_LANGOPT(Name, Bits, Default, Description)
268
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#define BENIGN_LANGOPT(Name, Bits, Default, Description)
270#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000271#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000272#include "clang/Basic/LangOptions.def"
273
Ben Langmuircd98cb72015-06-23 18:20:18 +0000274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
275 if (Diags)
276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
277 return true;
278 }
279
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
281 if (Diags)
282 Diags->Report(diag::err_pch_langopt_value_mismatch)
283 << "target Objective-C runtime";
284 return true;
285 }
286
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000287 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
288 LangOpts.CommentOpts.BlockCommandNames) {
289 if (Diags)
290 Diags->Report(diag::err_pch_langopt_value_mismatch)
291 << "block command names";
292 return true;
293 }
294
Guy Benyei11169dd2012-12-18 14:30:41 +0000295 return false;
296}
297
298/// \brief Compare the given set of target options against an existing set of
299/// target options.
300///
301/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
302///
303/// \returns true if the target options mis-match, false otherwise.
304static bool checkTargetOptions(const TargetOptions &TargetOpts,
305 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 DiagnosticsEngine *Diags,
307 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308#define CHECK_TARGET_OPT(Field, Name) \
309 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
310 if (Diags) \
311 Diags->Report(diag::err_pch_targetopt_mismatch) \
312 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
313 return true; \
314 }
315
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000319
320 // We can tolerate different CPUs in many cases, notably when one CPU
321 // supports a strict superset of another. When allowing compatible
322 // differences skip this check.
323 if (!AllowCompatibleDifferences)
324 CHECK_TARGET_OPT(CPU, "target CPU");
325
Guy Benyei11169dd2012-12-18 14:30:41 +0000326#undef CHECK_TARGET_OPT
327
328 // Compare feature sets.
329 SmallVector<StringRef, 4> ExistingFeatures(
330 ExistingTargetOpts.FeaturesAsWritten.begin(),
331 ExistingTargetOpts.FeaturesAsWritten.end());
332 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
333 TargetOpts.FeaturesAsWritten.end());
334 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
335 std::sort(ReadFeatures.begin(), ReadFeatures.end());
336
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000337 // We compute the set difference in both directions explicitly so that we can
338 // diagnose the differences differently.
339 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
340 std::set_difference(
341 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
342 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
343 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
344 ExistingFeatures.begin(), ExistingFeatures.end(),
345 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000346
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000347 // If we are allowing compatible differences and the read feature set is
348 // a strict subset of the existing feature set, there is nothing to diagnose.
349 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
350 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000351
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000352 if (Diags) {
353 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000355 << /* is-existing-feature */ false << Feature;
356 for (StringRef Feature : UnmatchedExistingFeatures)
357 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
358 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000359 }
360
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000361 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000362}
363
364bool
365PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000366 bool Complain,
367 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 const LangOptions &ExistingLangOpts = PP.getLangOpts();
369 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000370 Complain ? &Reader.Diags : nullptr,
371 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000372}
373
374bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000375 bool Complain,
376 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000377 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
378 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000379 Complain ? &Reader.Diags : nullptr,
380 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000381}
382
383namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000384
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
386 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000387 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
388 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000389
390} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000391
Ben Langmuirb92de022014-04-29 16:25:26 +0000392static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
393 DiagnosticsEngine &Diags,
394 bool Complain) {
395 typedef DiagnosticsEngine::Level Level;
396
397 // Check current mappings for new -Werror mappings, and the stored mappings
398 // for cases that were explicitly mapped to *not* be errors that are now
399 // errors because of options like -Werror.
400 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
401
402 for (DiagnosticsEngine *MappingSource : MappingSources) {
403 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
404 diag::kind DiagID = DiagIDMappingPair.first;
405 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
406 if (CurLevel < DiagnosticsEngine::Error)
407 continue; // not significant
408 Level StoredLevel =
409 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
410 if (StoredLevel < DiagnosticsEngine::Error) {
411 if (Complain)
412 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
413 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
414 return true;
415 }
416 }
417 }
418
419 return false;
420}
421
Alp Tokerac4e8e52014-06-22 21:58:33 +0000422static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
423 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
424 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
425 return true;
426 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000427}
428
429static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
430 DiagnosticsEngine &Diags,
431 bool IsSystem, bool Complain) {
432 // Top-level options
433 if (IsSystem) {
434 if (Diags.getSuppressSystemWarnings())
435 return false;
436 // If -Wsystem-headers was not enabled before, be conservative
437 if (StoredDiags.getSuppressSystemWarnings()) {
438 if (Complain)
439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
440 return true;
441 }
442 }
443
444 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
445 if (Complain)
446 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
447 return true;
448 }
449
450 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
451 !StoredDiags.getEnableAllWarnings()) {
452 if (Complain)
453 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
454 return true;
455 }
456
457 if (isExtHandlingFromDiagsError(Diags) &&
458 !isExtHandlingFromDiagsError(StoredDiags)) {
459 if (Complain)
460 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
461 return true;
462 }
463
464 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
465}
466
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000467/// Return the top import module if it is implicit, nullptr otherwise.
468static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
469 Preprocessor &PP) {
470 // If the original import came from a file explicitly generated by the user,
471 // don't check the diagnostic mappings.
472 // FIXME: currently this is approximated by checking whether this is not a
473 // module import of an implicitly-loaded module file.
474 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
475 // the transitive closure of its imports, since unrelated modules cannot be
476 // imported until after this module finishes validation.
477 ModuleFile *TopImport = &*ModuleMgr.rbegin();
478 while (!TopImport->ImportedBy.empty())
479 TopImport = TopImport->ImportedBy[0];
480 if (TopImport->Kind != MK_ImplicitModule)
481 return nullptr;
482
483 StringRef ModuleName = TopImport->ModuleName;
484 assert(!ModuleName.empty() && "diagnostic options read before module name");
485
486 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
487 assert(M && "missing module");
488 return M;
489}
490
Ben Langmuirb92de022014-04-29 16:25:26 +0000491bool PCHValidator::ReadDiagnosticOptions(
492 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
493 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
494 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
495 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000496 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000497 // This should never fail, because we would have processed these options
498 // before writing them to an ASTFile.
499 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
500
501 ModuleManager &ModuleMgr = Reader.getModuleManager();
502 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
503
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000504 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
505 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000506 return false;
507
Ben Langmuirb92de022014-04-29 16:25:26 +0000508 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
509 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000510 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
511 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000512}
513
Guy Benyei11169dd2012-12-18 14:30:41 +0000514/// \brief Collect the macro definitions provided by the given preprocessor
515/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000516static void
517collectMacroDefinitions(const PreprocessorOptions &PPOpts,
518 MacroDefinitionsMap &Macros,
519 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000520 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
521 StringRef Macro = PPOpts.Macros[I].first;
522 bool IsUndef = PPOpts.Macros[I].second;
523
524 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
525 StringRef MacroName = MacroPair.first;
526 StringRef MacroBody = MacroPair.second;
527
528 // For an #undef'd macro, we only care about the name.
529 if (IsUndef) {
530 if (MacroNames && !Macros.count(MacroName))
531 MacroNames->push_back(MacroName);
532
533 Macros[MacroName] = std::make_pair("", true);
534 continue;
535 }
536
537 // For a #define'd macro, figure out the actual definition.
538 if (MacroName.size() == Macro.size())
539 MacroBody = "1";
540 else {
541 // Note: GCC drops anything following an end-of-line character.
542 StringRef::size_type End = MacroBody.find_first_of("\n\r");
543 MacroBody = MacroBody.substr(0, End);
544 }
545
546 if (MacroNames && !Macros.count(MacroName))
547 MacroNames->push_back(MacroName);
548 Macros[MacroName] = std::make_pair(MacroBody, false);
549 }
550}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552/// \brief Check the preprocessor options deserialized from the control block
553/// against the preprocessor options in an existing preprocessor.
554///
555/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000556/// \param Validate If true, validate preprocessor options. If false, allow
557/// macros defined by \p ExistingPPOpts to override those defined by
558/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000559static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
560 const PreprocessorOptions &ExistingPPOpts,
561 DiagnosticsEngine *Diags,
562 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000563 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000564 const LangOptions &LangOpts,
565 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Check macro definitions.
567 MacroDefinitionsMap ASTFileMacros;
568 collectMacroDefinitions(PPOpts, ASTFileMacros);
569 MacroDefinitionsMap ExistingMacros;
570 SmallVector<StringRef, 4> ExistingMacroNames;
571 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
572
573 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
574 // Dig out the macro definition in the existing preprocessor options.
575 StringRef MacroName = ExistingMacroNames[I];
576 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
577
578 // Check whether we know anything about this macro name or not.
579 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
580 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000581 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // FIXME: Check whether this identifier was referenced anywhere in the
583 // AST file. If so, we should reject the AST file. Unfortunately, this
584 // information isn't in the control block. What shall we do about it?
585
586 if (Existing.second) {
587 SuggestedPredefines += "#undef ";
588 SuggestedPredefines += MacroName.str();
589 SuggestedPredefines += '\n';
590 } else {
591 SuggestedPredefines += "#define ";
592 SuggestedPredefines += MacroName.str();
593 SuggestedPredefines += ' ';
594 SuggestedPredefines += Existing.first.str();
595 SuggestedPredefines += '\n';
596 }
597 continue;
598 }
599
600 // If the macro was defined in one but undef'd in the other, we have a
601 // conflict.
602 if (Existing.second != Known->second.second) {
603 if (Diags) {
604 Diags->Report(diag::err_pch_macro_def_undef)
605 << MacroName << Known->second.second;
606 }
607 return true;
608 }
609
610 // If the macro was #undef'd in both, or if the macro bodies are identical,
611 // it's fine.
612 if (Existing.second || Existing.first == Known->second.first)
613 continue;
614
615 // The macro bodies differ; complain.
616 if (Diags) {
617 Diags->Report(diag::err_pch_macro_def_conflict)
618 << MacroName << Known->second.first << Existing.first;
619 }
620 return true;
621 }
622
623 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000624 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000625 if (Diags) {
626 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
627 }
628 return true;
629 }
630
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000631 // Detailed record is important since it is used for the module cache hash.
632 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000633 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000634 if (Diags) {
635 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
636 }
637 return true;
638 }
639
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 // Compute the #include and #include_macros lines we need.
641 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
642 StringRef File = ExistingPPOpts.Includes[I];
643 if (File == ExistingPPOpts.ImplicitPCHInclude)
644 continue;
645
646 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
647 != PPOpts.Includes.end())
648 continue;
649
650 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 SuggestedPredefines += "\"\n";
653 }
654
655 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
656 StringRef File = ExistingPPOpts.MacroIncludes[I];
657 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
658 File)
659 != PPOpts.MacroIncludes.end())
660 continue;
661
662 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000663 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 SuggestedPredefines += "\"\n##\n";
665 }
666
667 return false;
668}
669
670bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
671 bool Complain,
672 std::string &SuggestedPredefines) {
673 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
674
675 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000676 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000678 SuggestedPredefines,
679 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
Yaxun Liu43712e02016-09-07 18:40:20 +0000682bool SimpleASTReaderListener::ReadPreprocessorOptions(
683 const PreprocessorOptions &PPOpts,
684 bool Complain,
685 std::string &SuggestedPredefines) {
686 return checkPreprocessorOptions(PPOpts,
687 PP.getPreprocessorOpts(),
688 nullptr,
689 PP.getFileManager(),
690 SuggestedPredefines,
691 PP.getLangOpts(),
692 false);
693}
694
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000695/// Check the header search options deserialized from the control block
696/// against the header search options in an existing preprocessor.
697///
698/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
699static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
700 StringRef SpecificModuleCachePath,
701 StringRef ExistingModuleCachePath,
702 DiagnosticsEngine *Diags,
703 const LangOptions &LangOpts) {
704 if (LangOpts.Modules) {
705 if (SpecificModuleCachePath != ExistingModuleCachePath) {
706 if (Diags)
707 Diags->Report(diag::err_pch_modulecache_mismatch)
708 << SpecificModuleCachePath << ExistingModuleCachePath;
709 return true;
710 }
711 }
712
713 return false;
714}
715
716bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
717 StringRef SpecificModuleCachePath,
718 bool Complain) {
719 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
720 PP.getHeaderSearchInfo().getModuleCachePath(),
721 Complain ? &Reader.Diags : nullptr,
722 PP.getLangOpts());
723}
724
Guy Benyei11169dd2012-12-18 14:30:41 +0000725void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
726 PP.setCounterValue(Value);
727}
728
729//===----------------------------------------------------------------------===//
730// AST reader implementation
731//===----------------------------------------------------------------------===//
732
Nico Weber824285e2014-05-08 04:26:47 +0000733void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
734 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000736 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000737}
738
Guy Benyei11169dd2012-12-18 14:30:41 +0000739unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
740 return serialization::ComputeHash(Sel);
741}
742
Guy Benyei11169dd2012-12-18 14:30:41 +0000743std::pair<unsigned, unsigned>
744ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000745 using namespace llvm::support;
746 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
747 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 return std::make_pair(KeyLen, DataLen);
749}
750
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000751ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000752ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000753 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000755 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
756 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
757 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 if (N == 0)
759 return SelTable.getNullarySelector(FirstII);
760 else if (N == 1)
761 return SelTable.getUnarySelector(FirstII);
762
763 SmallVector<IdentifierInfo *, 16> Args;
764 Args.push_back(FirstII);
765 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 Args.push_back(Reader.getLocalIdentifier(
767 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000768
769 return SelTable.getSelector(N, Args.data());
770}
771
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000772ASTSelectorLookupTrait::data_type
773ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000775 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000776
777 data_type Result;
778
Justin Bogner57ba0b22014-03-28 22:03:24 +0000779 Result.ID = Reader.getGlobalSelectorID(
780 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000781 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
782 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
783 Result.InstanceBits = FullInstanceBits & 0x3;
784 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
785 Result.FactoryBits = FullFactoryBits & 0x3;
786 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
787 unsigned NumInstanceMethods = FullInstanceBits >> 3;
788 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000789
790 // Load instance methods
791 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000792 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
793 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000794 Result.Instance.push_back(Method);
795 }
796
797 // Load factory methods
798 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000799 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
800 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 Result.Factory.push_back(Method);
802 }
803
804 return Result;
805}
806
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000807unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
808 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000809}
810
811std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000812ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000813 using namespace llvm::support;
814 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
815 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 return std::make_pair(KeyLen, DataLen);
817}
818
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000819ASTIdentifierLookupTraitBase::internal_key_type
820ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000822 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823}
824
Douglas Gregordcf25082013-02-11 18:16:18 +0000825/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000826static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
827 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000828 return II.hadMacroDefinition() ||
829 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000830 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000831 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000832 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
833 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000834}
835
Richard Smith76c2f2c2015-07-17 20:09:43 +0000836static bool readBit(unsigned &Bits) {
837 bool Value = Bits & 0x1;
838 Bits >>= 1;
839 return Value;
840}
841
Richard Smith79bf9202015-08-24 03:33:22 +0000842IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
843 using namespace llvm::support;
844 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
845 return Reader.getGlobalIdentifierID(F, RawID >> 1);
846}
847
Richard Smitheb4b58f62016-02-05 01:40:54 +0000848static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
849 if (!II.isFromAST()) {
850 II.setIsFromAST();
851 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
852 if (isInterestingIdentifier(Reader, II, IsModule))
853 II.setChangedSinceDeserialization();
854 }
855}
856
Guy Benyei11169dd2012-12-18 14:30:41 +0000857IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
858 const unsigned char* d,
859 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000860 using namespace llvm::support;
861 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 bool IsInteresting = RawID & 0x01;
863
864 // Wipe out the "is interesting" bit.
865 RawID = RawID >> 1;
866
Richard Smith76c2f2c2015-07-17 20:09:43 +0000867 // Build the IdentifierInfo and link the identifier ID with it.
868 IdentifierInfo *II = KnownII;
869 if (!II) {
870 II = &Reader.getIdentifierTable().getOwn(k);
871 KnownII = II;
872 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000873 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000874 Reader.markIdentifierUpToDate(II);
875
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
877 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000878 // For uninteresting identifiers, there's nothing else to do. Just notify
879 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000880 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 return II;
882 }
883
Justin Bogner57ba0b22014-03-28 22:03:24 +0000884 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
885 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000886 bool CPlusPlusOperatorKeyword = readBit(Bits);
887 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000888 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000889 bool Poisoned = readBit(Bits);
890 bool ExtensionToken = readBit(Bits);
891 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892
893 assert(Bits == 0 && "Extra bits in the identifier?");
894 DataLen -= 8;
895
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 // Set or check the various bits in the IdentifierInfo structure.
897 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000898 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000899 II->revertTokenIDToIdentifier();
900 if (!F.isModule())
901 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
902 else if (HasRevertedBuiltin && II->getBuiltinID()) {
903 II->revertBuiltin();
904 assert((II->hasRevertedBuiltin() ||
905 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
906 "Incorrect ObjC keyword or builtin ID");
907 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 assert(II->isExtensionToken() == ExtensionToken &&
909 "Incorrect extension token flag");
910 (void)ExtensionToken;
911 if (Poisoned)
912 II->setIsPoisoned(true);
913 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
914 "Incorrect C++ operator keyword flag");
915 (void)CPlusPlusOperatorKeyword;
916
917 // If this identifier is a macro, deserialize the macro
918 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000919 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000920 uint32_t MacroDirectivesOffset =
921 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000922 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000923
Richard Smithd7329392015-04-21 21:46:32 +0000924 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 }
926
927 Reader.SetIdentifierInfo(ID, II);
928
929 // Read all of the declarations visible at global scope with this
930 // name.
931 if (DataLen > 0) {
932 SmallVector<uint32_t, 4> DeclIDs;
933 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000934 DeclIDs.push_back(Reader.getGlobalDeclID(
935 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 Reader.SetGloballyVisibleDecls(II, DeclIDs);
937 }
938
939 return II;
940}
941
Richard Smitha06c7e62015-08-26 23:55:49 +0000942DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
943 : Kind(Name.getNameKind()) {
944 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000946 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::ObjCZeroArgSelector:
949 case DeclarationName::ObjCOneArgSelector:
950 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000951 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 break;
953 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000954 Data = Name.getCXXOverloadedOperator();
955 break;
956 case DeclarationName::CXXLiteralOperatorName:
957 Data = (uint64_t)Name.getCXXLiteralIdentifier();
958 break;
Richard Smith35845152017-02-07 01:37:30 +0000959 case DeclarationName::CXXDeductionGuideName:
960 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
961 ->getDeclName().getAsIdentifierInfo();
962 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000963 case DeclarationName::CXXConstructorName:
964 case DeclarationName::CXXDestructorName:
965 case DeclarationName::CXXConversionFunctionName:
966 case DeclarationName::CXXUsingDirective:
967 Data = 0;
968 break;
969 }
970}
971
972unsigned DeclarationNameKey::getHash() const {
973 llvm::FoldingSetNodeID ID;
974 ID.AddInteger(Kind);
975
976 switch (Kind) {
977 case DeclarationName::Identifier:
978 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000979 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000980 ID.AddString(((IdentifierInfo*)Data)->getName());
981 break;
982 case DeclarationName::ObjCZeroArgSelector:
983 case DeclarationName::ObjCOneArgSelector:
984 case DeclarationName::ObjCMultiArgSelector:
985 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
986 break;
987 case DeclarationName::CXXOperatorName:
988 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 break;
990 case DeclarationName::CXXConstructorName:
991 case DeclarationName::CXXDestructorName:
992 case DeclarationName::CXXConversionFunctionName:
993 case DeclarationName::CXXUsingDirective:
994 break;
995 }
996
997 return ID.ComputeHash();
998}
999
Richard Smithd88a7f12015-09-01 20:35:42 +00001000ModuleFile *
1001ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1002 using namespace llvm::support;
1003 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1004 return Reader.getLocalModuleFile(F, ModuleFileID);
1005}
1006
Guy Benyei11169dd2012-12-18 14:30:41 +00001007std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001008ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001009 using namespace llvm::support;
1010 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1011 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 return std::make_pair(KeyLen, DataLen);
1013}
1014
Richard Smitha06c7e62015-08-26 23:55:49 +00001015ASTDeclContextNameLookupTrait::internal_key_type
1016ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001017 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001018
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 auto Kind = (DeclarationName::NameKind)*d++;
1020 uint64_t Data;
1021 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001023 case DeclarationName::CXXLiteralOperatorName:
1024 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001026 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001032 (uint64_t)Reader.getLocalSelector(
1033 F, endian::readNext<uint32_t, little, unaligned>(
1034 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 break;
1036 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001037 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 case DeclarationName::CXXConstructorName:
1040 case DeclarationName::CXXDestructorName:
1041 case DeclarationName::CXXConversionFunctionName:
1042 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001043 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 break;
1045 }
1046
Richard Smitha06c7e62015-08-26 23:55:49 +00001047 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
Richard Smithd88a7f12015-09-01 20:35:42 +00001050void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1051 const unsigned char *d,
1052 unsigned DataLen,
1053 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001054 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001055 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1056 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1057 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001059}
1060
Richard Smith0f4e2c42015-08-06 04:23:48 +00001061bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1062 BitstreamCursor &Cursor,
1063 uint64_t Offset,
1064 DeclContext *DC) {
1065 assert(Offset != 0);
1066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001068 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069
Richard Smith0f4e2c42015-08-06 04:23:48 +00001070 RecordData Record;
1071 StringRef Blob;
1072 unsigned Code = Cursor.ReadCode();
1073 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1074 if (RecCode != DECL_CONTEXT_LEXICAL) {
1075 Error("Expected lexical block");
1076 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001077 }
1078
Richard Smith82f8fcd2015-08-06 22:07:25 +00001079 assert(!isa<TranslationUnitDecl>(DC) &&
1080 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001081 // If we are handling a C++ class template instantiation, we can see multiple
1082 // lexical updates for the same record. It's important that we select only one
1083 // of them, so that field numbering works properly. Just pick the first one we
1084 // see.
1085 auto &Lex = LexicalDecls[DC];
1086 if (!Lex.first) {
1087 Lex = std::make_pair(
1088 &M, llvm::makeArrayRef(
1089 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1090 Blob.data()),
1091 Blob.size() / 4));
1092 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001093 DC->setHasExternalLexicalStorage(true);
1094 return false;
1095}
Guy Benyei11169dd2012-12-18 14:30:41 +00001096
Richard Smith0f4e2c42015-08-06 04:23:48 +00001097bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1098 BitstreamCursor &Cursor,
1099 uint64_t Offset,
1100 DeclID ID) {
1101 assert(Offset != 0);
1102
1103 SavedStreamPosition SavedPosition(Cursor);
1104 Cursor.JumpToBit(Offset);
1105
1106 RecordData Record;
1107 StringRef Blob;
1108 unsigned Code = Cursor.ReadCode();
1109 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1110 if (RecCode != DECL_CONTEXT_VISIBLE) {
1111 Error("Expected visible lookup table block");
1112 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 }
1114
Richard Smith0f4e2c42015-08-06 04:23:48 +00001115 // We can't safely determine the primary context yet, so delay attaching the
1116 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001117 auto *Data = (const unsigned char*)Blob.data();
1118 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 return false;
1120}
1121
Richard Smith37a93df2017-02-18 00:32:02 +00001122void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001124 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1125 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001126 Diag(diag::note_module_cache_path)
1127 << PP.getHeaderSearchInfo().getModuleCachePath();
1128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001129}
1130
1131void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001132 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 if (Diags.isDiagnosticInFlight())
1134 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1135 else
1136 Diag(DiagID) << Arg1 << Arg2;
1137}
1138
1139//===----------------------------------------------------------------------===//
1140// Source Manager Deserialization
1141//===----------------------------------------------------------------------===//
1142
1143/// \brief Read the line table in the source manager block.
1144/// \returns true if there was an error.
1145bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001146 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 unsigned Idx = 0;
1148 LineTableInfo &LineTable = SourceMgr.getLineTable();
1149
1150 // Parse the file names
1151 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001152 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001154 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1156 }
Richard Smith63078492015-09-01 07:41:55 +00001157 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001158
1159 // Parse the line entries
1160 std::vector<LineEntry> Entries;
1161 while (Idx < Record.size()) {
1162 int FID = Record[Idx++];
1163 assert(FID >= 0 && "Serialized line entries for non-local file.");
1164 // Remap FileID from 1-based old view.
1165 FID += F.SLocEntryBaseID - 1;
1166
1167 // Extract the line entries
1168 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001169 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Entries.clear();
1171 Entries.reserve(NumEntries);
1172 for (unsigned I = 0; I != NumEntries; ++I) {
1173 unsigned FileOffset = Record[Idx++];
1174 unsigned LineNo = Record[Idx++];
1175 int FilenameID = FileIDs[Record[Idx++]];
1176 SrcMgr::CharacteristicKind FileKind
1177 = (SrcMgr::CharacteristicKind)Record[Idx++];
1178 unsigned IncludeOffset = Record[Idx++];
1179 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1180 FileKind, IncludeOffset));
1181 }
1182 LineTable.AddEntry(FileID::get(FID), Entries);
1183 }
1184
1185 return false;
1186}
1187
1188/// \brief Read a source manager block
1189bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1190 using namespace SrcMgr;
1191
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001192 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
1194 // Set the source-location entry cursor to the current position in
1195 // the stream. This cursor will be used to read the contents of the
1196 // source manager block initially, and then lazily read
1197 // source-location entries as needed.
1198 SLocEntryCursor = F.Stream;
1199
1200 // The stream itself is going to skip over the source manager block.
1201 if (F.Stream.SkipBlock()) {
1202 Error("malformed block record in AST file");
1203 return true;
1204 }
1205
1206 // Enter the source manager block.
1207 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1208 Error("malformed source manager block record in AST file");
1209 return true;
1210 }
1211
1212 RecordData Record;
1213 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001214 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001215
Chris Lattnere7b154b2013-01-19 21:39:22 +00001216 switch (E.Kind) {
1217 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1218 case llvm::BitstreamEntry::Error:
1219 Error("malformed block record in AST file");
1220 return true;
1221 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001223 case llvm::BitstreamEntry::Record:
1224 // The interesting case.
1225 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001227
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001230 StringRef Blob;
1231 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 default: // Default behavior: ignore.
1233 break;
1234
1235 case SM_SLOC_FILE_ENTRY:
1236 case SM_SLOC_BUFFER_ENTRY:
1237 case SM_SLOC_EXPANSION_ENTRY:
1238 // Once we hit one of the source location entries, we're done.
1239 return false;
1240 }
1241 }
1242}
1243
1244/// \brief If a header file is not found at the path that we expect it to be
1245/// and the PCH file was moved from its original location, try to resolve the
1246/// file by assuming that header+PCH were moved together and the header is in
1247/// the same place relative to the PCH.
1248static std::string
1249resolveFileRelativeToOriginalDir(const std::string &Filename,
1250 const std::string &OriginalDir,
1251 const std::string &CurrDir) {
1252 assert(OriginalDir != CurrDir &&
1253 "No point trying to resolve the file if the PCH dir didn't change");
1254 using namespace llvm::sys;
1255 SmallString<128> filePath(Filename);
1256 fs::make_absolute(filePath);
1257 assert(path::is_absolute(OriginalDir));
1258 SmallString<128> currPCHPath(CurrDir);
1259
1260 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1261 fileDirE = path::end(path::parent_path(filePath));
1262 path::const_iterator origDirI = path::begin(OriginalDir),
1263 origDirE = path::end(OriginalDir);
1264 // Skip the common path components from filePath and OriginalDir.
1265 while (fileDirI != fileDirE && origDirI != origDirE &&
1266 *fileDirI == *origDirI) {
1267 ++fileDirI;
1268 ++origDirI;
1269 }
1270 for (; origDirI != origDirE; ++origDirI)
1271 path::append(currPCHPath, "..");
1272 path::append(currPCHPath, fileDirI, fileDirE);
1273 path::append(currPCHPath, path::filename(Filename));
1274 return currPCHPath.str();
1275}
1276
1277bool ASTReader::ReadSLocEntry(int ID) {
1278 if (ID == 0)
1279 return false;
1280
1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282 Error("source location entry ID out-of-range for AST file");
1283 return true;
1284 }
1285
Richard Smithaada85c2016-02-06 02:06:43 +00001286 // Local helper to read the (possibly-compressed) buffer data following the
1287 // entry record.
1288 auto ReadBuffer = [this](
1289 BitstreamCursor &SLocEntryCursor,
1290 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1291 RecordData Record;
1292 StringRef Blob;
1293 unsigned Code = SLocEntryCursor.ReadCode();
1294 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1295
1296 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001297 if (!llvm::zlib::isAvailable()) {
1298 Error("zlib is not available");
1299 return nullptr;
1300 }
Richard Smithaada85c2016-02-06 02:06:43 +00001301 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001302 if (llvm::Error E =
1303 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1304 Error("could not decompress embedded file contents: " +
1305 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001306 return nullptr;
1307 }
1308 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1309 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1310 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1311 } else {
1312 Error("AST record has invalid code");
1313 return nullptr;
1314 }
1315 };
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1318 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 unsigned BaseOffset = F->SLocEntryBaseOffset;
1321
1322 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001323 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1324 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 Error("incorrectly-formatted source location entry in AST file");
1326 return true;
1327 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001328
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001330 StringRef Blob;
1331 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 default:
1333 Error("incorrectly-formatted source location entry in AST file");
1334 return true;
1335
1336 case SM_SLOC_FILE_ENTRY: {
1337 // We will detect whether a file changed and return 'Failure' for it, but
1338 // we will also try to fail gracefully by setting up the SLocEntry.
1339 unsigned InputID = Record[4];
1340 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001341 const FileEntry *File = IF.getFile();
1342 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001343
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001344 // Note that we only check if a File was returned. If it was out-of-date
1345 // we have complained but we will continue creating a FileID to recover
1346 // gracefully.
1347 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 return true;
1349
1350 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1351 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1352 // This is the module's main file.
1353 IncludeLoc = getImportLocation(F);
1354 }
1355 SrcMgr::CharacteristicKind
1356 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1357 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1358 ID, BaseOffset + Record[0]);
1359 SrcMgr::FileInfo &FileInfo =
1360 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1361 FileInfo.NumCreatedFIDs = Record[5];
1362 if (Record[3])
1363 FileInfo.setHasLineDirectives();
1364
1365 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1366 unsigned NumFileDecls = Record[7];
1367 if (NumFileDecls) {
1368 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1369 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1370 NumFileDecls));
1371 }
Richard Smithaada85c2016-02-06 02:06:43 +00001372
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 const SrcMgr::ContentCache *ContentCache
1374 = SourceMgr.getOrCreateContentCache(File,
1375 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1376 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001377 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1378 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001379 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1380 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001382 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 }
1384
1385 break;
1386 }
1387
1388 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001389 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 unsigned Offset = Record[0];
1391 SrcMgr::CharacteristicKind
1392 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1393 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001394 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 IncludeLoc = getImportLocation(F);
1396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Richard Smithaada85c2016-02-06 02:06:43 +00001398 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1399 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001401 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001402 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 break;
1404 }
1405
1406 case SM_SLOC_EXPANSION_ENTRY: {
1407 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1408 SourceMgr.createExpansionLoc(SpellingLoc,
1409 ReadSourceLocation(*F, Record[2]),
1410 ReadSourceLocation(*F, Record[3]),
1411 Record[4],
1412 ID,
1413 BaseOffset + Record[0]);
1414 break;
1415 }
1416 }
1417
1418 return false;
1419}
1420
1421std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1422 if (ID == 0)
1423 return std::make_pair(SourceLocation(), "");
1424
1425 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1426 Error("source location entry ID out-of-range for AST file");
1427 return std::make_pair(SourceLocation(), "");
1428 }
1429
1430 // Find which module file this entry lands in.
1431 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001432 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 return std::make_pair(SourceLocation(), "");
1434
1435 // FIXME: Can we map this down to a particular submodule? That would be
1436 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001437 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001438}
1439
1440/// \brief Find the location where the module F is imported.
1441SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1442 if (F->ImportLoc.isValid())
1443 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001444
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 // Otherwise we have a PCH. It's considered to be "imported" at the first
1446 // location of its includer.
1447 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001448 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001449 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001450 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001452 return F->ImportedBy[0]->FirstLoc;
1453}
1454
1455/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1456/// specified cursor. Read the abbreviations that are at the top of the block
1457/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001458bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001459 if (Cursor.EnterSubBlock(BlockID))
1460 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001461
1462 while (true) {
1463 uint64_t Offset = Cursor.GetCurrentBitNo();
1464 unsigned Code = Cursor.ReadCode();
1465
1466 // We expect all abbrevs to be at the start of the block.
1467 if (Code != llvm::bitc::DEFINE_ABBREV) {
1468 Cursor.JumpToBit(Offset);
1469 return false;
1470 }
1471 Cursor.ReadAbbrevRecord();
1472 }
1473}
1474
Richard Smithe40f2ba2013-08-07 21:41:30 +00001475Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001476 unsigned &Idx) {
1477 Token Tok;
1478 Tok.startToken();
1479 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1480 Tok.setLength(Record[Idx++]);
1481 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1482 Tok.setIdentifierInfo(II);
1483 Tok.setKind((tok::TokenKind)Record[Idx++]);
1484 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1485 return Tok;
1486}
1487
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001488MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001489 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001490
1491 // Keep track of where we are in the stream, then jump back there
1492 // after reading this macro.
1493 SavedStreamPosition SavedPosition(Stream);
1494
1495 Stream.JumpToBit(Offset);
1496 RecordData Record;
1497 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001498 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001499
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001501 // Advance to the next record, but if we get to the end of the block, don't
1502 // pop it (removing all the abbreviations from the cursor) since we want to
1503 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001504 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001505 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001506
Chris Lattnerefa77172013-01-20 00:00:22 +00001507 switch (Entry.Kind) {
1508 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1509 case llvm::BitstreamEntry::Error:
1510 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001511 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001512 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001514 case llvm::BitstreamEntry::Record:
1515 // The interesting case.
1516 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 }
1518
1519 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 Record.clear();
1521 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001522 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001524 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001525 case PP_MACRO_DIRECTIVE_HISTORY:
1526 return Macro;
1527
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 case PP_MACRO_OBJECT_LIKE:
1529 case PP_MACRO_FUNCTION_LIKE: {
1530 // If we already have a macro, that means that we've hit the end
1531 // of the definition of the macro we were looking for. We're
1532 // done.
1533 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001534 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001535
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001536 unsigned NextIndex = 1; // Skip identifier ID.
1537 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001539 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001540 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001542 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1545 // Decode function-like macro info.
1546 bool isC99VarArgs = Record[NextIndex++];
1547 bool isGNUVarArgs = Record[NextIndex++];
1548 bool hasCommaPasting = Record[NextIndex++];
1549 MacroArgs.clear();
1550 unsigned NumArgs = Record[NextIndex++];
1551 for (unsigned i = 0; i != NumArgs; ++i)
1552 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1553
1554 // Install function-like macro info.
1555 MI->setIsFunctionLike();
1556 if (isC99VarArgs) MI->setIsC99Varargs();
1557 if (isGNUVarArgs) MI->setIsGNUVarargs();
1558 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001559 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 }
1561
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 // Remember that we saw this macro last so that we add the tokens that
1563 // form its body to it.
1564 Macro = MI;
1565
1566 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1567 Record[NextIndex]) {
1568 // We have a macro definition. Register the association
1569 PreprocessedEntityID
1570 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1571 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001572 PreprocessingRecord::PPEntityID PPID =
1573 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1574 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1575 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001576 if (PPDef)
1577 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 }
1579
1580 ++NumMacrosRead;
1581 break;
1582 }
1583
1584 case PP_TOKEN: {
1585 // If we see a TOKEN before a PP_MACRO_*, then the file is
1586 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001587 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001588
John McCallf413f5e2013-05-03 00:10:13 +00001589 unsigned Idx = 0;
1590 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 Macro->AddTokenToBody(Tok);
1592 break;
1593 }
1594 }
1595 }
1596}
1597
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001598PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001599ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1600 unsigned LocalID) const {
1601 if (!M.ModuleOffsetMap.empty())
1602 ReadModuleOffsetMap(M);
1603
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001606 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 return LocalID + I->second;
1610}
1611
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001612unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1613 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001614}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001615
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001616HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001617HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001618 internal_key_type ikey = {FE->getSize(),
1619 M.HasTimestamps ? FE->getModificationTime() : 0,
1620 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001621 return ikey;
1622}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001623
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001624bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001625 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 return false;
1627
Mehdi Amini004b9c72016-10-10 22:52:47 +00001628 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001629 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001632 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001633 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1634 if (!Key.Imported)
1635 return FileMgr.getFile(Key.Filename);
1636
1637 std::string Resolved = Key.Filename;
1638 Reader.ResolveImportedPath(M, Resolved);
1639 return FileMgr.getFile(Resolved);
1640 };
1641
1642 const FileEntry *FEA = GetFile(a);
1643 const FileEntry *FEB = GetFile(b);
1644 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001645}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001646
Guy Benyei11169dd2012-12-18 14:30:41 +00001647std::pair<unsigned, unsigned>
1648HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001649 using namespace llvm::support;
1650 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001652 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001653}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001654
1655HeaderFileInfoTrait::internal_key_type
1656HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001657 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001658 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001659 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1660 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001661 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001662 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001663 return ikey;
1664}
1665
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001666HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001667HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 unsigned DataLen) {
1669 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001670 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 HeaderFileInfo HFI;
1672 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001673 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1674 HFI.isImport |= (Flags >> 4) & 0x01;
1675 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1676 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001678 // FIXME: Find a better way to handle this. Maybe just store a
1679 // "has been included" flag?
1680 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1681 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001682 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1683 M, endian::readNext<uint32_t, little, unaligned>(d));
1684 if (unsigned FrameworkOffset =
1685 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001686 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 // since 0 is used as an indicator for "no framework name".
1688 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1689 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1690 }
Richard Smith386bb072015-08-18 23:42:23 +00001691
1692 assert((End - d) % 4 == 0 &&
1693 "Wrong data length in HeaderFileInfo deserialization");
1694 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001695 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001696 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1697 LocalSMID >>= 2;
1698
1699 // This header is part of a module. Associate it with the module to enable
1700 // implicit module import.
1701 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1702 Module *Mod = Reader.getSubmodule(GlobalSMID);
1703 FileManager &FileMgr = Reader.getFileManager();
1704 ModuleMap &ModMap =
1705 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1706
1707 std::string Filename = key.Filename;
1708 if (key.Imported)
1709 Reader.ResolveImportedPath(M, Filename);
1710 // FIXME: This is not always the right filename-as-written, but we're not
1711 // going to use this information to rebuild the module, so it doesn't make
1712 // a lot of difference.
1713 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001714 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1715 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001716 }
1717
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 // This HeaderFileInfo was externally loaded.
1719 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001720 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 return HFI;
1722}
1723
Richard Smithd7329392015-04-21 21:46:32 +00001724void ASTReader::addPendingMacro(IdentifierInfo *II,
1725 ModuleFile *M,
1726 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1728 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001729}
1730
1731void ASTReader::ReadDefinedMacros() {
1732 // Note that we are loading defined macros.
1733 Deserializing Macros(this);
1734
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001735 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1736 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737
1738 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001739 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 continue;
1741
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001742 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001743 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001744
1745 RecordData Record;
1746 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001748
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 switch (E.Kind) {
1750 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1751 case llvm::BitstreamEntry::Error:
1752 Error("malformed block record in AST file");
1753 return;
1754 case llvm::BitstreamEntry::EndBlock:
1755 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001756
Chris Lattnere7b154b2013-01-19 21:39:22 +00001757 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001758 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001759 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001760 default: // Default behavior: ignore.
1761 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001762
Chris Lattnere7b154b2013-01-19 21:39:22 +00001763 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001764 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001765 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001766 if (II->isOutOfDate())
1767 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001768 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001769 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001770
Chris Lattnere7b154b2013-01-19 21:39:22 +00001771 case PP_TOKEN:
1772 // Ignore tokens.
1773 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 break;
1776 }
1777 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001778 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 }
1780}
1781
1782namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001783
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 /// \brief Visitor class used to look up identifirs in an AST file.
1785 class IdentifierLookupVisitor {
1786 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001787 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001788 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001789 unsigned &NumIdentifierLookups;
1790 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001792
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001794 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1795 unsigned &NumIdentifierLookups,
1796 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001797 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1798 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001799 NumIdentifierLookups(NumIdentifierLookups),
1800 NumIdentifierLookupHits(NumIdentifierLookupHits),
1801 Found()
1802 {
1803 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001804
1805 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001807 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001809
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 ASTIdentifierLookupTable *IdTable
1811 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1812 if (!IdTable)
1813 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001814
1815 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001816 Found);
1817 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001818 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001819 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 if (Pos == IdTable->end())
1821 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001822
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 // Dereferencing the iterator has the effect of building the
1824 // IdentifierInfo node and populating it with the various
1825 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001826 ++NumIdentifierLookupHits;
1827 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 return true;
1829 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001830
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 // \brief Retrieve the identifier info found within the module
1832 // files.
1833 IdentifierInfo *getIdentifierInfo() const { return Found; }
1834 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001835
1836} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001837
1838void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1839 // Note that we are loading an identifier.
1840 Deserializing AnIdentifier(this);
1841
1842 unsigned PriorGeneration = 0;
1843 if (getContext().getLangOpts().Modules)
1844 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001845
1846 // If there is a global index, look there first to determine which modules
1847 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001848 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001849 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001850 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001851 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1852 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001853 }
1854 }
1855
Douglas Gregor7211ac12013-01-25 23:32:03 +00001856 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001857 NumIdentifierLookups,
1858 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001859 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 markIdentifierUpToDate(&II);
1861}
1862
1863void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1864 if (!II)
1865 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001866
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 II->setOutOfDate(false);
1868
1869 // Update the generation for this identifier.
1870 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001871 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001872}
1873
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001874void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1875 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001876 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
1878 BitstreamCursor &Cursor = M.MacroCursor;
1879 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001880 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001881
Richard Smith713369b2015-04-23 20:40:50 +00001882 struct ModuleMacroRecord {
1883 SubmoduleID SubModID;
1884 MacroInfo *MI;
1885 SmallVector<SubmoduleID, 8> Overrides;
1886 };
1887 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001888
Richard Smithd7329392015-04-21 21:46:32 +00001889 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1890 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1891 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001892 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001893 while (true) {
1894 llvm::BitstreamEntry Entry =
1895 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1896 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1897 Error("malformed block record in AST file");
1898 return;
1899 }
1900
1901 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001902 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001903 case PP_MACRO_DIRECTIVE_HISTORY:
1904 break;
1905
1906 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001907 ModuleMacros.push_back(ModuleMacroRecord());
1908 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001909 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1910 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001911 for (int I = 2, N = Record.size(); I != N; ++I)
1912 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001913 continue;
1914 }
1915
1916 default:
1917 Error("malformed block record in AST file");
1918 return;
1919 }
1920
1921 // We found the macro directive history; that's the last record
1922 // for this macro.
1923 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001924 }
1925
Richard Smithd7329392015-04-21 21:46:32 +00001926 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001927 {
1928 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001929 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001930 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001931 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001932 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001933 Module *Mod = getSubmodule(ModID);
1934 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001935 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001936 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001937 }
1938
1939 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001940 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001941 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001942 }
1943 }
1944
1945 // Don't read the directive history for a module; we don't have anywhere
1946 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001947 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001948 return;
1949
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001950 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001951 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001952 unsigned Idx = 0, N = Record.size();
1953 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001954 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001955 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001956 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1957 switch (K) {
1958 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001959 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001960 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001961 break;
1962 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001963 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001964 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001965 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001966 }
1967 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001968 bool isPublic = Record[Idx++];
1969 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1970 break;
1971 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001972
1973 if (!Latest)
1974 Latest = MD;
1975 if (Earliest)
1976 Earliest->setPrevious(MD);
1977 Earliest = MD;
1978 }
1979
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001980 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001981 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001982}
1983
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001984ASTReader::InputFileInfo
1985ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001986 // Go find this input file.
1987 BitstreamCursor &Cursor = F.InputFilesCursor;
1988 SavedStreamPosition SavedPosition(Cursor);
1989 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1990
1991 unsigned Code = Cursor.ReadCode();
1992 RecordData Record;
1993 StringRef Blob;
1994
1995 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1996 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1997 "invalid record type for input file");
1998 (void)Result;
1999
2000 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002001 InputFileInfo R;
2002 R.StoredSize = static_cast<off_t>(Record[1]);
2003 R.StoredTime = static_cast<time_t>(Record[2]);
2004 R.Overridden = static_cast<bool>(Record[3]);
2005 R.Transient = static_cast<bool>(Record[4]);
2006 R.Filename = Blob;
2007 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002008 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002009}
2010
Manman Renc8c94152016-10-21 23:35:03 +00002011static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002012InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 // If this ID is bogus, just return an empty input file.
2014 if (ID == 0 || ID > F.InputFilesLoaded.size())
2015 return InputFile();
2016
2017 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002018 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 return F.InputFilesLoaded[ID-1];
2020
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002021 if (F.InputFilesLoaded[ID-1].isNotFound())
2022 return InputFile();
2023
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002025 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 SavedStreamPosition SavedPosition(Cursor);
2027 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002028
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002029 InputFileInfo FI = readInputFileInfo(F, ID);
2030 off_t StoredSize = FI.StoredSize;
2031 time_t StoredTime = FI.StoredTime;
2032 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002033 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002034 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002035
Richard Smitha8cfffa2015-11-26 02:04:16 +00002036 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002037
2038 // If we didn't find the file, resolve it relative to the
2039 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002040 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 F.OriginalDir != CurrentDir) {
2042 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2043 F.OriginalDir,
2044 CurrentDir);
2045 if (!Resolved.empty())
2046 File = FileMgr.getFile(Resolved);
2047 }
2048
2049 // For an overridden file, create a virtual file with the stored
2050 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002051 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002053
Craig Toppera13603a2014-05-22 05:54:18 +00002054 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002055 if (Complain) {
2056 std::string ErrorStr = "could not find file '";
2057 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002058 ErrorStr += "' referenced by AST file '";
2059 ErrorStr += F.FileName;
2060 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002061 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002063 // Record that we didn't find the file.
2064 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2065 return InputFile();
2066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002067
Ben Langmuir198c1682014-03-07 07:27:49 +00002068 // Check if there was a request to override the contents of the file
2069 // that was part of the precompiled header. Overridding such a file
2070 // can lead to problems when lexing using the source locations from the
2071 // PCH.
2072 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002073 // FIXME: Reject if the overrides are different.
2074 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002075 if (Complain)
2076 Error(diag::err_fe_pch_file_overridden, Filename);
2077 // After emitting the diagnostic, recover by disabling the override so
2078 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002079 //
2080 // FIXME: This recovery is just as broken as the original state; there may
2081 // be another precompiled module that's using the overridden contents, or
2082 // we might be half way through parsing it. Instead, we should treat the
2083 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002084 SM.disableFileContentsOverride(File);
2085 // The FileEntry is a virtual file entry with the size of the contents
2086 // that would override the original contents. Set it to the original's
2087 // size/time.
2088 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2089 StoredSize, StoredTime);
2090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002091
Ben Langmuir198c1682014-03-07 07:27:49 +00002092 bool IsOutOfDate = false;
2093
2094 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002095 if (!Overridden && //
2096 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002097 (StoredTime && StoredTime != File->getModificationTime() &&
2098 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002099 )) {
2100 if (Complain) {
2101 // Build a list of the PCH imports that got us here (in reverse).
2102 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2103 while (ImportStack.back()->ImportedBy.size() > 0)
2104 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002105
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 // The top-level PCH is stale.
2107 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002108 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2109 if (DiagnosticKind == 0)
2110 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2111 else if (DiagnosticKind == 1)
2112 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2113 else
2114 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002115
Ben Langmuir198c1682014-03-07 07:27:49 +00002116 // Print the import stack.
2117 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2118 Diag(diag::note_pch_required_by)
2119 << Filename << ImportStack[0]->FileName;
2120 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002121 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002123 }
2124
Ben Langmuir198c1682014-03-07 07:27:49 +00002125 if (!Diags.isDiagnosticInFlight())
2126 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 }
2128
Ben Langmuir198c1682014-03-07 07:27:49 +00002129 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002131 // FIXME: If the file is overridden and we've already opened it,
2132 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002133
Richard Smitha8cfffa2015-11-26 02:04:16 +00002134 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002135
2136 // Note that we've loaded this input file.
2137 F.InputFilesLoaded[ID-1] = IF;
2138 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002139}
2140
Richard Smith7ed1bc92014-12-05 22:42:13 +00002141/// \brief If we are loading a relocatable PCH or module file, and the filename
2142/// is not an absolute path, add the system or module root to the beginning of
2143/// the file name.
2144void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2145 // Resolve relative to the base directory, if we have one.
2146 if (!M.BaseDirectory.empty())
2147 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002148}
2149
Richard Smith7ed1bc92014-12-05 22:42:13 +00002150void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2152 return;
2153
Richard Smith7ed1bc92014-12-05 22:42:13 +00002154 SmallString<128> Buffer;
2155 llvm::sys::path::append(Buffer, Prefix, Filename);
2156 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002157}
2158
Richard Smith0f99d6a2015-08-09 08:48:41 +00002159static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2160 switch (ARR) {
2161 case ASTReader::Failure: return true;
2162 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2163 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2164 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2165 case ASTReader::ConfigurationMismatch:
2166 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2167 case ASTReader::HadErrors: return true;
2168 case ASTReader::Success: return false;
2169 }
2170
2171 llvm_unreachable("unknown ASTReadResult");
2172}
2173
Richard Smith0516b182015-09-08 19:40:14 +00002174ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2175 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2176 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002177 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002178 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2179 return Failure;
2180
2181 // Read all of the records in the options block.
2182 RecordData Record;
2183 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002184 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002185 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002186
Richard Smith0516b182015-09-08 19:40:14 +00002187 switch (Entry.Kind) {
2188 case llvm::BitstreamEntry::Error:
2189 case llvm::BitstreamEntry::SubBlock:
2190 return Failure;
2191
2192 case llvm::BitstreamEntry::EndBlock:
2193 return Result;
2194
2195 case llvm::BitstreamEntry::Record:
2196 // The interesting case.
2197 break;
2198 }
2199
2200 // Read and process a record.
2201 Record.clear();
2202 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2203 case LANGUAGE_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2205 if (ParseLanguageOptions(Record, Complain, Listener,
2206 AllowCompatibleConfigurationMismatch))
2207 Result = ConfigurationMismatch;
2208 break;
2209 }
2210
2211 case TARGET_OPTIONS: {
2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2213 if (ParseTargetOptions(Record, Complain, Listener,
2214 AllowCompatibleConfigurationMismatch))
2215 Result = ConfigurationMismatch;
2216 break;
2217 }
2218
Richard Smith0516b182015-09-08 19:40:14 +00002219 case FILE_SYSTEM_OPTIONS: {
2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2221 if (!AllowCompatibleConfigurationMismatch &&
2222 ParseFileSystemOptions(Record, Complain, Listener))
2223 Result = ConfigurationMismatch;
2224 break;
2225 }
2226
2227 case HEADER_SEARCH_OPTIONS: {
2228 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2229 if (!AllowCompatibleConfigurationMismatch &&
2230 ParseHeaderSearchOptions(Record, Complain, Listener))
2231 Result = ConfigurationMismatch;
2232 break;
2233 }
2234
2235 case PREPROCESSOR_OPTIONS:
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2237 if (!AllowCompatibleConfigurationMismatch &&
2238 ParsePreprocessorOptions(Record, Complain, Listener,
2239 SuggestedPredefines))
2240 Result = ConfigurationMismatch;
2241 break;
2242 }
2243 }
2244}
2245
Guy Benyei11169dd2012-12-18 14:30:41 +00002246ASTReader::ASTReadResult
2247ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002248 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002249 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002251 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002252 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002253
2254 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2255 Error("malformed block record in AST file");
2256 return Failure;
2257 }
2258
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002259 // Lambda to read the unhashed control block the first time it's called.
2260 //
2261 // For PCM files, the unhashed control block cannot be read until after the
2262 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2263 // need to look ahead before reading the IMPORTS record. For consistency,
2264 // this block is always read somehow (see BitstreamEntry::EndBlock).
2265 bool HasReadUnhashedControlBlock = false;
2266 auto readUnhashedControlBlockOnce = [&]() {
2267 if (!HasReadUnhashedControlBlock) {
2268 HasReadUnhashedControlBlock = true;
2269 if (ASTReadResult Result =
2270 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2271 return Result;
2272 }
2273 return Success;
2274 };
2275
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 // Read all of the records and blocks in the control block.
2277 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002278 unsigned NumInputs = 0;
2279 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002280 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002281 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002282
Chris Lattnere7b154b2013-01-19 21:39:22 +00002283 switch (Entry.Kind) {
2284 case llvm::BitstreamEntry::Error:
2285 Error("malformed block record in AST file");
2286 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002287 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002288 // Validate the module before returning. This call catches an AST with
2289 // no module name and no imports.
2290 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2291 return Result;
2292
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002293 // Validate input files.
2294 const HeaderSearchOptions &HSOpts =
2295 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002296
Richard Smitha1825302014-10-23 22:18:29 +00002297 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002298 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2299 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002300 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2301 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002303
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002304 // If we are reading a module, we will create a verification timestamp,
2305 // so we verify all input files. Otherwise, verify only user input
2306 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002307
2308 unsigned N = NumUserInputs;
2309 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002310 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002311 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002312 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002313 N = NumInputs;
2314
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002315 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002316 InputFile IF = getInputFile(F, I+1, Complain);
2317 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002319 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002321
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002322 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002323 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002324
Ben Langmuircb69b572014-03-07 06:40:32 +00002325 if (Listener && Listener->needsInputFileVisitation()) {
2326 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2327 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002328 for (unsigned I = 0; I < N; ++I) {
2329 bool IsSystem = I >= NumUserInputs;
2330 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002331 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002332 F.Kind == MK_ExplicitModule ||
2333 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002334 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002335 }
2336
Richard Smith8a308ec2015-11-05 00:54:55 +00002337 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002338 }
2339
Chris Lattnere7b154b2013-01-19 21:39:22 +00002340 case llvm::BitstreamEntry::SubBlock:
2341 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 case INPUT_FILES_BLOCK_ID:
2343 F.InputFilesCursor = Stream;
2344 if (Stream.SkipBlock() || // Skip with the main cursor
2345 // Read the abbreviations
2346 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2347 Error("malformed block record in AST file");
2348 return Failure;
2349 }
2350 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002351
2352 case OPTIONS_BLOCK_ID:
2353 // If we're reading the first module for this group, check its options
2354 // are compatible with ours. For modules it imports, no further checking
2355 // is required, because we checked them when we built it.
2356 if (Listener && !ImportedBy) {
2357 // Should we allow the configuration of the module file to differ from
2358 // the configuration of the current translation unit in a compatible
2359 // way?
2360 //
2361 // FIXME: Allow this for files explicitly specified with -include-pch.
2362 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002363 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002364
Richard Smith8a308ec2015-11-05 00:54:55 +00002365 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2366 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002367 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002368 if (Result == Failure) {
2369 Error("malformed block record in AST file");
2370 return Result;
2371 }
2372
Richard Smith8a308ec2015-11-05 00:54:55 +00002373 if (DisableValidation ||
2374 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2375 Result = Success;
2376
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002377 // If we can't load the module, exit early since we likely
2378 // will rebuild the module anyway. The stream may be in the
2379 // middle of a block.
2380 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002381 return Result;
2382 } else if (Stream.SkipBlock()) {
2383 Error("malformed block record in AST file");
2384 return Failure;
2385 }
2386 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002387
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 if (Stream.SkipBlock()) {
2390 Error("malformed block record in AST file");
2391 return Failure;
2392 }
2393 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002395
Chris Lattnere7b154b2013-01-19 21:39:22 +00002396 case llvm::BitstreamEntry::Record:
2397 // The interesting case.
2398 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 }
2400
2401 // Read and process a record.
2402 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002403 StringRef Blob;
2404 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case METADATA: {
2406 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2407 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002408 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2409 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return VersionMismatch;
2411 }
2412
Richard Smithe75ee0f2015-08-17 07:13:32 +00002413 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2415 Diag(diag::err_pch_with_compiler_errors);
2416 return HadErrors;
2417 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002418 if (hasErrors) {
2419 Diags.ErrorOccurred = true;
2420 Diags.UncompilableErrorOccurred = true;
2421 Diags.UnrecoverableErrorOccurred = true;
2422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002423
2424 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002425 // Relative paths in a relocatable PCH are relative to our sysroot.
2426 if (F.RelocatablePCH)
2427 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428
Richard Smithe75ee0f2015-08-17 07:13:32 +00002429 F.HasTimestamps = Record[5];
2430
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2434 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002435 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return VersionMismatch;
2437 }
2438 break;
2439 }
2440
2441 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002442 // Validate the AST before processing any imports (otherwise, untangling
2443 // them can be error-prone and expensive). A module will have a name and
2444 // will already have been validated, but this catches the PCH case.
2445 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2446 return Result;
2447
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002448 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 unsigned Idx = 0, N = Record.size();
2450 while (Idx < N) {
2451 // Read information about the AST file.
2452 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2453 // The import location will be the local one for now; we will adjust
2454 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002455 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002457 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002458 off_t StoredSize = (off_t)Record[Idx++];
2459 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002460 ASTFileSignature StoredSignature = {
2461 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2462 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2463 (uint32_t)Record[Idx++]}}};
Richard Smith7ed1bc92014-12-05 22:42:13 +00002464 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002465
Richard Smith0f99d6a2015-08-09 08:48:41 +00002466 // If our client can't cope with us being out of date, we can't cope with
2467 // our dependency being missing.
2468 unsigned Capabilities = ClientLoadCapabilities;
2469 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2470 Capabilities &= ~ARR_Missing;
2471
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002473 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2474 Loaded, StoredSize, StoredModTime,
2475 StoredSignature, Capabilities);
2476
2477 // If we diagnosed a problem, produce a backtrace.
2478 if (isDiagnosedResult(Result, Capabilities))
2479 Diag(diag::note_module_file_imported_by)
2480 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2481
2482 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 case Failure: return Failure;
2484 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002485 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 case OutOfDate: return OutOfDate;
2487 case VersionMismatch: return VersionMismatch;
2488 case ConfigurationMismatch: return ConfigurationMismatch;
2489 case HadErrors: return HadErrors;
2490 case Success: break;
2491 }
2492 }
2493 break;
2494 }
2495
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 case ORIGINAL_FILE:
2497 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002498 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002500 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 break;
2502
2503 case ORIGINAL_FILE_ID:
2504 F.OriginalSourceFileID = FileID::get(Record[0]);
2505 break;
2506
2507 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002508 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 break;
2510
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002511 case MODULE_NAME:
2512 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002513 if (Listener)
2514 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002515
2516 // Validate the AST as soon as we have a name so we can exit early on
2517 // failure.
2518 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2519 return Result;
2520
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002521 break;
2522
Richard Smith223d3f22014-12-06 03:21:08 +00002523 case MODULE_DIRECTORY: {
2524 assert(!F.ModuleName.empty() &&
2525 "MODULE_DIRECTORY found before MODULE_NAME");
2526 // If we've already loaded a module map file covering this module, we may
2527 // have a better path for it (relative to the current build).
2528 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2529 if (M && M->Directory) {
2530 // If we're implicitly loading a module, the base directory can't
2531 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002532 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002533 const DirectoryEntry *BuildDir =
2534 PP.getFileManager().getDirectory(Blob);
2535 if (!BuildDir || BuildDir != M->Directory) {
2536 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2537 Diag(diag::err_imported_module_relocated)
2538 << F.ModuleName << Blob << M->Directory->getName();
2539 return OutOfDate;
2540 }
2541 }
2542 F.BaseDirectory = M->Directory->getName();
2543 } else {
2544 F.BaseDirectory = Blob;
2545 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002546 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002547 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002548
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002549 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002550 if (ASTReadResult Result =
2551 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2552 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002553 break;
2554
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002555 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002556 NumInputs = Record[0];
2557 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002558 F.InputFileOffsets =
2559 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002560 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002561 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 break;
2563 }
2564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002565}
2566
Ben Langmuir2c9af442014-04-10 17:57:43 +00002567ASTReader::ASTReadResult
2568ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002569 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570
2571 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2572 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
2575
2576 // Read all of the records and blocks for the AST file.
2577 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002578 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002579 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002580
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581 switch (Entry.Kind) {
2582 case llvm::BitstreamEntry::Error:
2583 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002586 // Outside of C++, we do not store a lookup map for the translation unit.
2587 // Instead, mark it as needing a lookup map to be built if this module
2588 // contains any declarations lexically within it (which it always does!).
2589 // This usually has no cost, since we very rarely need the lookup map for
2590 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002592 if (DC->hasExternalLexicalStorage() &&
2593 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002595
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 case llvm::BitstreamEntry::SubBlock:
2599 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 case DECLTYPES_BLOCK_ID:
2601 // We lazily load the decls block, but we want to set up the
2602 // DeclsCursor cursor to point into it. Clone our current bitcode
2603 // cursor to it, enter the block and read the abbrevs in that block.
2604 // With the main cursor, we just skip over it.
2605 F.DeclsCursor = Stream;
2606 if (Stream.SkipBlock() || // Skip with the main cursor.
2607 // Read the abbrevs.
2608 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2609 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002613
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 case PREPROCESSOR_BLOCK_ID:
2615 F.MacroCursor = Stream;
2616 if (!PP.getExternalSource())
2617 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 if (Stream.SkipBlock() ||
2620 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2621 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
2624 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2625 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002626
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 case PREPROCESSOR_DETAIL_BLOCK_ID:
2628 F.PreprocessorDetailCursor = Stream;
2629 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002630 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002632 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002636 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 if (!PP.getPreprocessingRecord())
2639 PP.createPreprocessingRecord();
2640 if (!PP.getPreprocessingRecord()->getExternalSource())
2641 PP.getPreprocessingRecord()->SetExternalSource(*this);
2642 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 case SOURCE_MANAGER_BLOCK_ID:
2645 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002646 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002648
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002650 if (ASTReadResult Result =
2651 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002654
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002656 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 if (Stream.SkipBlock() ||
2658 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2659 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002660 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 }
2662 CommentsCursors.push_back(std::make_pair(C, &F));
2663 break;
2664 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002665
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002667 if (Stream.SkipBlock()) {
2668 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002669 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002670 }
2671 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 }
2673 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002674
Chris Lattnere7b154b2013-01-19 21:39:22 +00002675 case llvm::BitstreamEntry::Record:
2676 // The interesting case.
2677 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 }
2679
2680 // Read and process a record.
2681 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002682 StringRef Blob;
2683 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 default: // Default behavior: ignore.
2685 break;
2686
2687 case TYPE_OFFSET: {
2688 if (F.LocalNumTypes != 0) {
2689 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002690 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 F.LocalNumTypes = Record[0];
2694 unsigned LocalBaseTypeIndex = Record[1];
2695 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002696
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 if (F.LocalNumTypes > 0) {
2698 // Introduce the global -> local mapping for types within this module.
2699 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 // Introduce the local -> global mapping for types within this module.
2702 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002703 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002705
2706 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 }
2708 break;
2709 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 case DECL_OFFSET: {
2712 if (F.LocalNumDecls != 0) {
2713 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002714 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002716 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 F.LocalNumDecls = Record[0];
2718 unsigned LocalBaseDeclID = Record[1];
2719 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002720
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002722 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 // module.
2724 GlobalDeclMap.insert(
2725 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002726
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 // Introduce the local -> global mapping for declarations within this
2728 // module.
2729 F.DeclRemap.insertOrReplace(
2730 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 // Introduce the global -> local mapping for declarations within this
2733 // module.
2734 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002735
Ben Langmuir52ca6782014-10-20 16:27:32 +00002736 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2737 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 break;
2739 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 case TU_UPDATE_LEXICAL: {
2742 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002743 LexicalContents Contents(
2744 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2745 Blob.data()),
2746 static_cast<unsigned int>(Blob.size() / 4));
2747 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 TU->setHasExternalLexicalStorage(true);
2749 break;
2750 }
2751
2752 case UPDATE_VISIBLE: {
2753 unsigned Idx = 0;
2754 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002755 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002756 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002757 // If we've already loaded the decl, perform the updates when we finish
2758 // loading this block.
2759 if (Decl *D = GetExistingDecl(ID))
2760 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
2762 }
2763
2764 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002765 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002767 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2768 (const unsigned char *)F.IdentifierTableData + Record[0],
2769 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2770 (const unsigned char *)F.IdentifierTableData,
2771 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002772
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2774 }
2775 break;
2776
2777 case IDENTIFIER_OFFSET: {
2778 if (F.LocalNumIdentifiers != 0) {
2779 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002780 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002782 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 F.LocalNumIdentifiers = Record[0];
2784 unsigned LocalBaseIdentifierID = Record[1];
2785 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002786
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 if (F.LocalNumIdentifiers > 0) {
2788 // Introduce the global -> local mapping for identifiers within this
2789 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002790 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002792
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 // Introduce the local -> global mapping for identifiers within this
2794 // module.
2795 F.IdentifierRemap.insertOrReplace(
2796 std::make_pair(LocalBaseIdentifierID,
2797 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002798
Ben Langmuir52ca6782014-10-20 16:27:32 +00002799 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2800 + F.LocalNumIdentifiers);
2801 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 break;
2803 }
2804
Richard Smith33e0f7e2015-07-22 02:08:40 +00002805 case INTERESTING_IDENTIFIERS:
2806 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2807 break;
2808
Ben Langmuir332aafe2014-01-31 01:06:56 +00002809 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002810 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2811 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002813 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 break;
2815
David Blaikie9ffe5a32017-01-30 05:00:26 +00002816 case MODULAR_CODEGEN_DECLS:
2817 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2818 // them (ie: if we're not codegenerating this module).
2819 if (F.Kind == MK_MainFile)
2820 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2822 break;
2823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002825 if (SpecialTypes.empty()) {
2826 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2828 break;
2829 }
2830
2831 if (SpecialTypes.size() != Record.size()) {
2832 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002833 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002834 }
2835
2836 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2837 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2838 if (!SpecialTypes[I])
2839 SpecialTypes[I] = ID;
2840 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2841 // merge step?
2842 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 break;
2844
2845 case STATISTICS:
2846 TotalNumStatements += Record[0];
2847 TotalNumMacros += Record[1];
2848 TotalLexicalDeclContexts += Record[2];
2849 TotalVisibleDeclContexts += Record[3];
2850 break;
2851
2852 case UNUSED_FILESCOPED_DECLS:
2853 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2855 break;
2856
2857 case DELEGATING_CTORS:
2858 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2859 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2860 break;
2861
2862 case WEAK_UNDECLARED_IDENTIFIERS:
2863 if (Record.size() % 4 != 0) {
2864 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002865 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002867
2868 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 // files. This isn't the way to do it :)
2870 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 // Translate the weak, undeclared identifiers into global IDs.
2873 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2874 WeakUndeclaredIdentifiers.push_back(
2875 getGlobalIdentifierID(F, Record[I++]));
2876 WeakUndeclaredIdentifiers.push_back(
2877 getGlobalIdentifierID(F, Record[I++]));
2878 WeakUndeclaredIdentifiers.push_back(
2879 ReadSourceLocation(F, Record, I).getRawEncoding());
2880 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2881 }
2882 break;
2883
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002885 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 F.LocalNumSelectors = Record[0];
2887 unsigned LocalBaseSelectorID = Record[1];
2888 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002889
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002891 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 // module.
2893 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002894
2895 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 // module.
2897 F.SelectorRemap.insertOrReplace(
2898 std::make_pair(LocalBaseSelectorID,
2899 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002900
2901 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 }
2903 break;
2904 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002905
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002907 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 if (Record[0])
2909 F.SelectorLookupTable
2910 = ASTSelectorLookupTable::Create(
2911 F.SelectorLookupTableData + Record[0],
2912 F.SelectorLookupTableData,
2913 ASTSelectorLookupTrait(*this, F));
2914 TotalNumMethodPoolEntries += Record[1];
2915 break;
2916
2917 case REFERENCED_SELECTOR_POOL:
2918 if (!Record.empty()) {
2919 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002920 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 Record[Idx++]));
2922 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2923 getRawEncoding());
2924 }
2925 }
2926 break;
2927
2928 case PP_COUNTER_VALUE:
2929 if (!Record.empty() && Listener)
2930 Listener->ReadCounter(F, Record[0]);
2931 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002932
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 F.NumFileSortedDecls = Record[0];
2936 break;
2937
2938 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002939 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 F.LocalNumSLocEntries = Record[0];
2941 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002942 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002943 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002945 if (!F.SLocEntryBaseID) {
2946 Error("ran out of source locations");
2947 break;
2948 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Make our entry in the range map. BaseID is negative and growing, so
2950 // we invert it. Because we invert it, though, we need the other end of
2951 // the range.
2952 unsigned RangeStart =
2953 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2954 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2955 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2956
2957 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2958 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2959 GlobalSLocOffsetMap.insert(
2960 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2961 - SLocSpaceSize,&F));
2962
2963 // Initialize the remapping table.
2964 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002965 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002967 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002969
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 TotalNumSLocEntries += F.LocalNumSLocEntries;
2971 break;
2972 }
2973
Richard Smith37a93df2017-02-18 00:32:02 +00002974 case MODULE_OFFSET_MAP:
2975 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002977
2978 case SOURCE_MANAGER_LINE_TABLE:
2979 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 break;
2982
2983 case SOURCE_LOCATION_PRELOADS: {
2984 // Need to transform from the local view (1-based IDs) to the global view,
2985 // which is based off F.SLocEntryBaseID.
2986 if (!F.PreloadSLocEntries.empty()) {
2987 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002988 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002990
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 F.PreloadSLocEntries.swap(Record);
2992 break;
2993 }
2994
2995 case EXT_VECTOR_DECLS:
2996 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2997 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2998 break;
2999
3000 case VTABLE_USES:
3001 if (Record.size() % 3 != 0) {
3002 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003003 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003005
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 // Later tables overwrite earlier ones.
3007 // FIXME: Modules will have some trouble with this. This is clearly not
3008 // the right way to do this.
3009 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003010
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3012 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3013 VTableUses.push_back(
3014 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3015 VTableUses.push_back(Record[Idx++]);
3016 }
3017 break;
3018
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 case PENDING_IMPLICIT_INSTANTIATIONS:
3020 if (PendingInstantiations.size() % 2 != 0) {
3021 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 }
3024
3025 if (Record.size() % 2 != 0) {
3026 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029
3030 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3031 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3032 PendingInstantiations.push_back(
3033 ReadSourceLocation(F, Record, I).getRawEncoding());
3034 }
3035 break;
3036
3037 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003038 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003039 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003040 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3043 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3044 break;
3045
3046 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003047 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3048 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3049 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003050
3051 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 unsigned StartingID;
3054 if (!PP.getPreprocessingRecord())
3055 PP.createPreprocessingRecord();
3056 if (!PP.getPreprocessingRecord()->getExternalSource())
3057 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003058 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003060 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 F.BasePreprocessedEntityID = StartingID;
3062
3063 if (F.NumPreprocessedEntities > 0) {
3064 // Introduce the global -> local mapping for preprocessed entities in
3065 // this module.
3066 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003067
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 // Introduce the local -> global mapping for preprocessed entities in
3069 // this module.
3070 F.PreprocessedEntityRemap.insertOrReplace(
3071 std::make_pair(LocalBasePreprocessedEntityID,
3072 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3073 }
3074
3075 break;
3076 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003077
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 case DECL_UPDATE_OFFSETS: {
3079 if (Record.size() % 2 != 0) {
3080 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003081 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003083 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3084 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3085 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3086
3087 // If we've already loaded the decl, perform the updates when we finish
3088 // loading this block.
3089 if (Decl *D = GetExistingDecl(ID))
3090 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 break;
3093 }
3094
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 case OBJC_CATEGORIES_MAP: {
3096 if (F.LocalNumObjCCategoriesInMap != 0) {
3097 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003098 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003102 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 break;
3104 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 case OBJC_CATEGORIES:
3107 F.ObjCCategories.swap(Record);
3108 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 case CUDA_SPECIAL_DECL_REFS:
3111 // Later tables overwrite earlier ones.
3112 // FIXME: Modules will have trouble with this.
3113 CUDASpecialDeclRefs.clear();
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3116 break;
3117
3118 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003119 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 if (Record[0]) {
3122 F.HeaderFileInfoTable
3123 = HeaderFileInfoLookupTable::Create(
3124 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3125 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003126 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003128 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003129
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 PP.getHeaderSearchInfo().SetExternalSource(this);
3131 if (!PP.getHeaderSearchInfo().getExternalLookup())
3132 PP.getHeaderSearchInfo().SetExternalLookup(this);
3133 }
3134 break;
3135 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 case FP_PRAGMA_OPTIONS:
3138 // Later tables overwrite earlier ones.
3139 FPPragmaOptions.swap(Record);
3140 break;
3141
3142 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003143 for (unsigned I = 0, E = Record.size(); I != E; ) {
3144 auto Name = ReadString(Record, I);
3145 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003146 Opt.Supported = Record[I++] != 0;
3147 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003148 Opt.Avail = Record[I++];
3149 Opt.Core = Record[I++];
3150 }
3151 break;
3152
3153 case OPENCL_EXTENSION_TYPES:
3154 for (unsigned I = 0, E = Record.size(); I != E;) {
3155 auto TypeID = static_cast<::TypeID>(Record[I++]);
3156 auto *Type = GetType(TypeID).getTypePtr();
3157 auto NumExt = static_cast<unsigned>(Record[I++]);
3158 for (unsigned II = 0; II != NumExt; ++II) {
3159 auto Ext = ReadString(Record, I);
3160 OpenCLTypeExtMap[Type].insert(Ext);
3161 }
3162 }
3163 break;
3164
3165 case OPENCL_EXTENSION_DECLS:
3166 for (unsigned I = 0, E = Record.size(); I != E;) {
3167 auto DeclID = static_cast<::DeclID>(Record[I++]);
3168 auto *Decl = GetDecl(DeclID);
3169 auto NumExt = static_cast<unsigned>(Record[I++]);
3170 for (unsigned II = 0; II != NumExt; ++II) {
3171 auto Ext = ReadString(Record, I);
3172 OpenCLDeclExtMap[Decl].insert(Ext);
3173 }
3174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 break;
3176
3177 case TENTATIVE_DEFINITIONS:
3178 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3179 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3180 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 case KNOWN_NAMESPACES:
3183 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3184 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3185 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003186
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003187 case UNDEFINED_BUT_USED:
3188 if (UndefinedButUsed.size() % 2 != 0) {
3189 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003190 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003191 }
3192
3193 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003194 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003195 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003196 }
3197 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003198 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3199 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003200 ReadSourceLocation(F, Record, I).getRawEncoding());
3201 }
3202 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003203 case DELETE_EXPRS_TO_ANALYZE:
3204 for (unsigned I = 0, N = Record.size(); I != N;) {
3205 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3206 const uint64_t Count = Record[I++];
3207 DelayedDeleteExprs.push_back(Count);
3208 for (uint64_t C = 0; C < Count; ++C) {
3209 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3210 bool IsArrayForm = Record[I++] == 1;
3211 DelayedDeleteExprs.push_back(IsArrayForm);
3212 }
3213 }
3214 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003215
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003217 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 // If we aren't loading a module (which has its own exports), make
3219 // all of the imported modules visible.
3220 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003221 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3222 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3223 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003224 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003225 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003226 if (DeserializationListener)
3227 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3228 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 }
3230 }
3231 break;
3232 }
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 case MACRO_OFFSET: {
3235 if (F.LocalNumMacros != 0) {
3236 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003237 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003239 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 F.LocalNumMacros = Record[0];
3241 unsigned LocalBaseMacroID = Record[1];
3242 F.BaseMacroID = getTotalNumMacros();
3243
3244 if (F.LocalNumMacros > 0) {
3245 // Introduce the global -> local mapping for macros within this module.
3246 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3247
3248 // Introduce the local -> global mapping for macros within this module.
3249 F.MacroRemap.insertOrReplace(
3250 std::make_pair(LocalBaseMacroID,
3251 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003252
3253 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 }
3255 break;
3256 }
3257
Richard Smithe40f2ba2013-08-07 21:41:30 +00003258 case LATE_PARSED_TEMPLATE: {
3259 LateParsedTemplates.append(Record.begin(), Record.end());
3260 break;
3261 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003262
3263 case OPTIMIZE_PRAGMA_OPTIONS:
3264 if (Record.size() != 1) {
3265 Error("invalid pragma optimize record");
3266 return Failure;
3267 }
3268 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3269 break;
Nico Weber72889432014-09-06 01:25:55 +00003270
Nico Weber779355f2016-03-02 23:22:00 +00003271 case MSSTRUCT_PRAGMA_OPTIONS:
3272 if (Record.size() != 1) {
3273 Error("invalid pragma ms_struct record");
3274 return Failure;
3275 }
3276 PragmaMSStructState = Record[0];
3277 break;
3278
Nico Weber42932312016-03-03 00:17:35 +00003279 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3280 if (Record.size() != 2) {
3281 Error("invalid pragma ms_struct record");
3282 return Failure;
3283 }
3284 PragmaMSPointersToMembersState = Record[0];
3285 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3286 break;
3287
Nico Weber72889432014-09-06 01:25:55 +00003288 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3289 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3290 UnusedLocalTypedefNameCandidates.push_back(
3291 getGlobalDeclID(F, Record[I]));
3292 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003293
3294 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3295 if (Record.size() != 1) {
3296 Error("invalid cuda pragma options record");
3297 return Failure;
3298 }
3299 ForceCUDAHostDeviceDepth = Record[0];
3300 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003301
3302 case PACK_PRAGMA_OPTIONS: {
3303 if (Record.size() < 3) {
3304 Error("invalid pragma pack record");
3305 return Failure;
3306 }
3307 PragmaPackCurrentValue = Record[0];
3308 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3309 unsigned NumStackEntries = Record[2];
3310 unsigned Idx = 3;
3311 // Reset the stack when importing a new module.
3312 PragmaPackStack.clear();
3313 for (unsigned I = 0; I < NumStackEntries; ++I) {
3314 PragmaPackStackEntry Entry;
3315 Entry.Value = Record[Idx++];
3316 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3317 PragmaPackStrings.push_back(ReadString(Record, Idx));
3318 Entry.SlotLabel = PragmaPackStrings.back();
3319 PragmaPackStack.push_back(Entry);
3320 }
3321 break;
3322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003323 }
3324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003325}
3326
Richard Smith37a93df2017-02-18 00:32:02 +00003327void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3328 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3329
3330 // Additional remapping information.
3331 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3332 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3333 F.ModuleOffsetMap = StringRef();
3334
3335 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3336 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3337 F.SLocRemap.insert(std::make_pair(0U, 0));
3338 F.SLocRemap.insert(std::make_pair(2U, 1));
3339 }
3340
3341 // Continuous range maps we may be updating in our module.
3342 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3343 RemapBuilder;
3344 RemapBuilder SLocRemap(F.SLocRemap);
3345 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3346 RemapBuilder MacroRemap(F.MacroRemap);
3347 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3348 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3349 RemapBuilder SelectorRemap(F.SelectorRemap);
3350 RemapBuilder DeclRemap(F.DeclRemap);
3351 RemapBuilder TypeRemap(F.TypeRemap);
3352
3353 while (Data < DataEnd) {
3354 // FIXME: Looking up dependency modules by filename is horrible.
3355 using namespace llvm::support;
3356 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3357 StringRef Name = StringRef((const char*)Data, Len);
3358 Data += Len;
3359 ModuleFile *OM = ModuleMgr.lookup(Name);
3360 if (!OM) {
3361 std::string Msg =
3362 "SourceLocation remap refers to unknown module, cannot find ";
3363 Msg.append(Name);
3364 Error(Msg);
3365 return;
3366 }
3367
3368 uint32_t SLocOffset =
3369 endian::readNext<uint32_t, little, unaligned>(Data);
3370 uint32_t IdentifierIDOffset =
3371 endian::readNext<uint32_t, little, unaligned>(Data);
3372 uint32_t MacroIDOffset =
3373 endian::readNext<uint32_t, little, unaligned>(Data);
3374 uint32_t PreprocessedEntityIDOffset =
3375 endian::readNext<uint32_t, little, unaligned>(Data);
3376 uint32_t SubmoduleIDOffset =
3377 endian::readNext<uint32_t, little, unaligned>(Data);
3378 uint32_t SelectorIDOffset =
3379 endian::readNext<uint32_t, little, unaligned>(Data);
3380 uint32_t DeclIDOffset =
3381 endian::readNext<uint32_t, little, unaligned>(Data);
3382 uint32_t TypeIndexOffset =
3383 endian::readNext<uint32_t, little, unaligned>(Data);
3384
3385 uint32_t None = std::numeric_limits<uint32_t>::max();
3386
3387 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3388 RemapBuilder &Remap) {
3389 if (Offset != None)
3390 Remap.insert(std::make_pair(Offset,
3391 static_cast<int>(BaseOffset - Offset)));
3392 };
3393 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3394 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3395 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3396 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3397 PreprocessedEntityRemap);
3398 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3399 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3400 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3401 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3402
3403 // Global -> local mappings.
3404 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3405 }
3406}
3407
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408ASTReader::ASTReadResult
3409ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3410 const ModuleFile *ImportedBy,
3411 unsigned ClientLoadCapabilities) {
3412 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003413 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003414
Manman Ren11f2a472016-08-18 17:42:15 +00003415 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003416 // For an explicitly-loaded module, we don't care whether the original
3417 // module map file exists or matches.
3418 return Success;
3419 }
3420
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 // Try to resolve ModuleName in the current header search context and
3422 // verify that it is found in the same module map file as we saved. If the
3423 // top-level AST file is a main file, skip this check because there is no
3424 // usable header search context.
3425 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003426 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003427 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003428 // An implicitly-loaded module file should have its module listed in some
3429 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003430 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003431 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3432 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3433 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003434 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003435 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3436 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3437 // This module was defined by an imported (explicit) module.
3438 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3439 << ASTFE->getName();
3440 else
3441 // This module was built with a different module map.
3442 Diag(diag::err_imported_module_not_found)
3443 << F.ModuleName << F.FileName << ImportedBy->FileName
3444 << F.ModuleMapPath;
3445 }
3446 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003447 }
3448
Richard Smithe842a472014-10-22 02:05:46 +00003449 assert(M->Name == F.ModuleName && "found module with different name");
3450
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003451 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003452 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003453 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3454 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003455 assert(ImportedBy && "top-level import should be verified");
3456 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3457 Diag(diag::err_imported_module_modmap_changed)
3458 << F.ModuleName << ImportedBy->FileName
3459 << ModMap->getName() << F.ModuleMapPath;
3460 return OutOfDate;
3461 }
3462
3463 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3464 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3465 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003466 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003467 const FileEntry *F =
3468 FileMgr.getFile(Filename, false, false);
3469 if (F == nullptr) {
3470 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3471 Error("could not find file '" + Filename +"' referenced by AST file");
3472 return OutOfDate;
3473 }
3474 AdditionalStoredMaps.insert(F);
3475 }
3476
3477 // Check any additional module map files (e.g. module.private.modulemap)
3478 // that are not in the pcm.
3479 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3480 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3481 // Remove files that match
3482 // Note: SmallPtrSet::erase is really remove
3483 if (!AdditionalStoredMaps.erase(ModMap)) {
3484 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3485 Diag(diag::err_module_different_modmap)
3486 << F.ModuleName << /*new*/0 << ModMap->getName();
3487 return OutOfDate;
3488 }
3489 }
3490 }
3491
3492 // Check any additional module map files that are in the pcm, but not
3493 // found in header search. Cases that match are already removed.
3494 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3495 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3496 Diag(diag::err_module_different_modmap)
3497 << F.ModuleName << /*not new*/1 << ModMap->getName();
3498 return OutOfDate;
3499 }
3500 }
3501
3502 if (Listener)
3503 Listener->ReadModuleMapFile(F.ModuleMapPath);
3504 return Success;
3505}
3506
3507
Douglas Gregorc1489562013-02-12 23:36:21 +00003508/// \brief Move the given method to the back of the global list of methods.
3509static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3510 // Find the entry for this selector in the method pool.
3511 Sema::GlobalMethodPool::iterator Known
3512 = S.MethodPool.find(Method->getSelector());
3513 if (Known == S.MethodPool.end())
3514 return;
3515
3516 // Retrieve the appropriate method list.
3517 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3518 : Known->second.second;
3519 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003520 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003521 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003522 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003523 Found = true;
3524 } else {
3525 // Keep searching.
3526 continue;
3527 }
3528 }
3529
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003530 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003531 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003532 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003533 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003534 }
3535}
3536
Richard Smithde711422015-04-23 21:20:19 +00003537void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003538 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003539 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003540 bool wasHidden = D->Hidden;
3541 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003542
Richard Smith49f906a2014-03-01 00:08:04 +00003543 if (wasHidden && SemaObj) {
3544 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3545 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003546 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 }
3548 }
3549}
3550
Richard Smith49f906a2014-03-01 00:08:04 +00003551void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003552 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003553 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003555 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003556 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003558 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003559
3560 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003561 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 // there is nothing more to do.
3563 continue;
3564 }
Richard Smith49f906a2014-03-01 00:08:04 +00003565
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 if (!Mod->isAvailable()) {
3567 // Modules that aren't available cannot be made visible.
3568 continue;
3569 }
3570
3571 // Update the module's name visibility.
3572 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003573
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 // If we've already deserialized any names from this module,
3575 // mark them as visible.
3576 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3577 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003578 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003580 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003581 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3582 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003584
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003586 SmallVector<Module *, 16> Exports;
3587 Mod->getExportedModules(Exports);
3588 for (SmallVectorImpl<Module *>::iterator
3589 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3590 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003591 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003592 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 }
3594 }
3595}
3596
Richard Smith6561f922016-09-12 21:06:40 +00003597/// We've merged the definition \p MergedDef into the existing definition
3598/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3599/// visible.
3600void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3601 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003602 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3603 // in modules other than its owning module. We should instead give the
3604 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003605 if (Def->isHidden()) {
3606 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003607 if (!MergedDef->isHidden())
3608 Def->Hidden = false;
3609 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3610 getContext().mergeDefinitionIntoModule(
3611 Def, MergedDef->getImportedOwningModule(),
3612 /*NotifyListeners*/ false);
3613 PendingMergedDefinitionsToDeduplicate.insert(Def);
3614 } else {
3615 auto SubmoduleID = MergedDef->getOwningModuleID();
3616 assert(SubmoduleID && "hidden definition in no module");
3617 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3618 }
Richard Smith6561f922016-09-12 21:06:40 +00003619 }
3620}
3621
Douglas Gregore060e572013-01-25 01:03:03 +00003622bool ASTReader::loadGlobalIndex() {
3623 if (GlobalIndex)
3624 return false;
3625
3626 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3627 !Context.getLangOpts().Modules)
3628 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003629
Douglas Gregore060e572013-01-25 01:03:03 +00003630 // Try to load the global index.
3631 TriedLoadingGlobalIndex = true;
3632 StringRef ModuleCachePath
3633 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3634 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003635 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003636 if (!Result.first)
3637 return true;
3638
3639 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003640 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003641 return false;
3642}
3643
3644bool ASTReader::isGlobalIndexUnavailable() const {
3645 return Context.getLangOpts().Modules && UseGlobalIndex &&
3646 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3647}
3648
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003649static void updateModuleTimestamp(ModuleFile &MF) {
3650 // Overwrite the timestamp file contents so that file's mtime changes.
3651 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003652 std::error_code EC;
3653 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3654 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003655 return;
3656 OS << "Timestamp file\n";
3657}
3658
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003659/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3660/// cursor into the start of the given block ID, returning false on success and
3661/// true on failure.
3662static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003663 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003664 llvm::BitstreamEntry Entry = Cursor.advance();
3665 switch (Entry.Kind) {
3666 case llvm::BitstreamEntry::Error:
3667 case llvm::BitstreamEntry::EndBlock:
3668 return true;
3669
3670 case llvm::BitstreamEntry::Record:
3671 // Ignore top-level records.
3672 Cursor.skipRecord(Entry.ID);
3673 break;
3674
3675 case llvm::BitstreamEntry::SubBlock:
3676 if (Entry.ID == BlockID) {
3677 if (Cursor.EnterSubBlock(BlockID))
3678 return true;
3679 // Found it!
3680 return false;
3681 }
3682
3683 if (Cursor.SkipBlock())
3684 return true;
3685 }
3686 }
3687}
3688
Benjamin Kramer0772c422016-02-13 13:42:54 +00003689ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 ModuleKind Type,
3691 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003692 unsigned ClientLoadCapabilities,
3693 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003694 llvm::SaveAndRestore<SourceLocation>
3695 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3696
Richard Smithd1c46742014-04-30 02:24:17 +00003697 // Defer any pending actions until we get to the end of reading the AST file.
3698 Deserializing AnASTFile(this);
3699
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003701 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003702
3703 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003704 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003705 switch (ASTReadResult ReadResult =
3706 ReadASTCore(FileName, Type, ImportLoc,
3707 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3708 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003710 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 case OutOfDate:
3712 case VersionMismatch:
3713 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003714 case HadErrors: {
3715 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3716 for (const ImportedModule &IM : Loaded)
3717 LoadedSet.insert(IM.Mod);
3718
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003719 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003720 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003721 ? &PP.getHeaderSearchInfo().getModuleMap()
3722 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003723
3724 // If we find that any modules are unusable, the global index is going
3725 // to be out-of-date. Just remove it.
3726 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003727 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003728 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003729 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 case Success:
3731 break;
3732 }
3733
3734 // Here comes stuff that we only do once the entire chain is loaded.
3735
3736 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003737 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3738 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003739 M != MEnd; ++M) {
3740 ModuleFile &F = *M->Mod;
3741
3742 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003743 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3744 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003745
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003746 // Read the extension blocks.
3747 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3748 if (ASTReadResult Result = ReadExtensionBlock(F))
3749 return Result;
3750 }
3751
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003752 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 // bits of all files we've seen.
3754 F.GlobalBitOffset = TotalModulesSizeInBits;
3755 TotalModulesSizeInBits += F.SizeInBits;
3756 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003757
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 // Preload SLocEntries.
3759 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3760 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3761 // Load it through the SourceManager and don't call ReadSLocEntry()
3762 // directly because the entry may have already been loaded in which case
3763 // calling ReadSLocEntry() directly would trigger an assertion in
3764 // SourceManager.
3765 SourceMgr.getLoadedSLocEntryByID(Index);
3766 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003767
Richard Smithea741482017-05-01 22:10:47 +00003768 // Map the original source file ID into the ID space of the current
3769 // compilation.
3770 if (F.OriginalSourceFileID.isValid()) {
3771 F.OriginalSourceFileID = FileID::get(
3772 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3773 }
3774
Richard Smith33e0f7e2015-07-22 02:08:40 +00003775 // Preload all the pending interesting identifiers by marking them out of
3776 // date.
3777 for (auto Offset : F.PreloadIdentifierOffsets) {
3778 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3779 F.IdentifierTableData + Offset);
3780
3781 ASTIdentifierLookupTrait Trait(*this, F);
3782 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3783 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003784 auto &II = PP.getIdentifierTable().getOwn(Key);
3785 II.setOutOfDate(true);
3786
3787 // Mark this identifier as being from an AST file so that we can track
3788 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003789 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003790
3791 // Associate the ID with the identifier so that the writer can reuse it.
3792 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3793 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003794 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 }
3796
Douglas Gregor603cd862013-03-22 18:50:14 +00003797 // Setup the import locations and notify the module manager that we've
3798 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003799 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3800 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 M != MEnd; ++M) {
3802 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003803
3804 ModuleMgr.moduleFileAccepted(&F);
3805
3806 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003807 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003808 // FIXME: We assume that locations from PCH / preamble do not need
3809 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003810 if (!M->ImportedBy)
3811 F.ImportLoc = M->ImportLoc;
3812 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003813 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 }
3815
Richard Smith33e0f7e2015-07-22 02:08:40 +00003816 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003817 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3818 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003819 // Mark all of the identifiers in the identifier table as being out of date,
3820 // so that various accessors know to check the loaded modules when the
3821 // identifier is used.
3822 //
3823 // For C++ modules, we don't need information on many identifiers (just
3824 // those that provide macros or are poisoned), so we mark all of
3825 // the interesting ones via PreloadIdentifierOffsets.
3826 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3827 IdEnd = PP.getIdentifierTable().end();
3828 Id != IdEnd; ++Id)
3829 Id->second->setOutOfDate(true);
3830 }
Manman Rena0f31a02016-04-29 19:04:05 +00003831 // Mark selectors as out of date.
3832 for (auto Sel : SelectorGeneration)
3833 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003834
Guy Benyei11169dd2012-12-18 14:30:41 +00003835 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003836 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3837 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003838 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3839 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003840
3841 switch (Unresolved.Kind) {
3842 case UnresolvedModuleRef::Conflict:
3843 if (ResolvedMod) {
3844 Module::Conflict Conflict;
3845 Conflict.Other = ResolvedMod;
3846 Conflict.Message = Unresolved.String.str();
3847 Unresolved.Mod->Conflicts.push_back(Conflict);
3848 }
3849 continue;
3850
3851 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003852 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003853 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003855
Douglas Gregorfb912652013-03-20 21:10:35 +00003856 case UnresolvedModuleRef::Export:
3857 if (ResolvedMod || Unresolved.IsWildcard)
3858 Unresolved.Mod->Exports.push_back(
3859 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3860 continue;
3861 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003862 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003863 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003864
Graydon Hoaree7196af2016-12-09 21:45:49 +00003865 if (Imported)
3866 Imported->append(ImportedModules.begin(),
3867 ImportedModules.end());
3868
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003869 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3870 // Might be unnecessary as use declarations are only used to build the
3871 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003872
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 InitializeContext();
3874
Richard Smith3d8e97e2013-10-18 06:54:39 +00003875 if (SemaObj)
3876 UpdateSema();
3877
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 if (DeserializationListener)
3879 DeserializationListener->ReaderInitialized(this);
3880
3881 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003882 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003883 // If this AST file is a precompiled preamble, then set the
3884 // preamble file ID of the source manager to the file source file
3885 // from which the preamble was built.
3886 if (Type == MK_Preamble) {
3887 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3888 } else if (Type == MK_MainFile) {
3889 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3890 }
3891 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003892
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 // For any Objective-C class definitions we have already loaded, make sure
3894 // that we load any additional categories.
3895 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003896 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 ObjCClassesLoaded[I],
3898 PreviousGeneration);
3899 }
Douglas Gregore060e572013-01-25 01:03:03 +00003900
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003901 if (PP.getHeaderSearchInfo()
3902 .getHeaderSearchOpts()
3903 .ModulesValidateOncePerBuildSession) {
3904 // Now we are certain that the module and all modules it depends on are
3905 // up to date. Create or update timestamp files for modules that are
3906 // located in the module cache (not for PCH files that could be anywhere
3907 // in the filesystem).
3908 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3909 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003910 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003911 updateModuleTimestamp(*M.Mod);
3912 }
3913 }
3914 }
3915
Guy Benyei11169dd2012-12-18 14:30:41 +00003916 return Success;
3917}
3918
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003919static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003920
Ben Langmuir70a1b812015-03-24 04:43:52 +00003921/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3922static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003923 return Stream.canSkipToPos(4) &&
3924 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003925 Stream.Read(8) == 'P' &&
3926 Stream.Read(8) == 'C' &&
3927 Stream.Read(8) == 'H';
3928}
3929
Richard Smith0f99d6a2015-08-09 08:48:41 +00003930static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3931 switch (Kind) {
3932 case MK_PCH:
3933 return 0; // PCH
3934 case MK_ImplicitModule:
3935 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003936 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003937 return 1; // module
3938 case MK_MainFile:
3939 case MK_Preamble:
3940 return 2; // main source file
3941 }
3942 llvm_unreachable("unknown module kind");
3943}
3944
Guy Benyei11169dd2012-12-18 14:30:41 +00003945ASTReader::ASTReadResult
3946ASTReader::ReadASTCore(StringRef FileName,
3947 ModuleKind Type,
3948 SourceLocation ImportLoc,
3949 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003950 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003951 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003952 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 unsigned ClientLoadCapabilities) {
3954 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003956 ModuleManager::AddModuleResult AddResult
3957 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003958 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003959 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003960 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003961
Douglas Gregor7029ce12013-03-19 00:28:20 +00003962 switch (AddResult) {
3963 case ModuleManager::AlreadyLoaded:
3964 return Success;
3965
3966 case ModuleManager::NewlyLoaded:
3967 // Load module file below.
3968 break;
3969
3970 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003971 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003972 // it.
3973 if (ClientLoadCapabilities & ARR_Missing)
3974 return Missing;
3975
3976 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003977 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003978 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003979 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003980 return Failure;
3981
3982 case ModuleManager::OutOfDate:
3983 // We couldn't load the module file because it is out-of-date. If the
3984 // client can handle out-of-date, return it.
3985 if (ClientLoadCapabilities & ARR_OutOfDate)
3986 return OutOfDate;
3987
3988 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003989 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003990 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003991 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 return Failure;
3993 }
3994
Douglas Gregor7029ce12013-03-19 00:28:20 +00003995 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003996
3997 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3998 // module?
3999 if (FileName != "-") {
4000 CurrentDir = llvm::sys::path::parent_path(FileName);
4001 if (CurrentDir.empty()) CurrentDir = ".";
4002 }
4003
4004 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004005 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004006 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004007 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004008
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004010 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004011 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4012 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 return Failure;
4014 }
4015
4016 // This is used for compatibility with older PCH formats.
4017 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004018 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004019 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004020
Chris Lattnerefa77172013-01-20 00:00:22 +00004021 switch (Entry.Kind) {
4022 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004023 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004024 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 Error("invalid record at top-level of AST file");
4026 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004027
Chris Lattnerefa77172013-01-20 00:00:22 +00004028 case llvm::BitstreamEntry::SubBlock:
4029 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 }
4031
Chris Lattnerefa77172013-01-20 00:00:22 +00004032 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 case CONTROL_BLOCK_ID:
4034 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004035 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004037 // Check that we didn't try to load a non-module AST file as a module.
4038 //
4039 // FIXME: Should we also perform the converse check? Loading a module as
4040 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004041 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4042 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004043 F.ModuleName.empty()) {
4044 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4045 if (Result != OutOfDate ||
4046 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4047 Diag(diag::err_module_file_not_module) << FileName;
4048 return Result;
4049 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 break;
4051
4052 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004053 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 case OutOfDate: return OutOfDate;
4055 case VersionMismatch: return VersionMismatch;
4056 case ConfigurationMismatch: return ConfigurationMismatch;
4057 case HadErrors: return HadErrors;
4058 }
4059 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004060
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 case AST_BLOCK_ID:
4062 if (!HaveReadControlBlock) {
4063 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004064 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 return VersionMismatch;
4066 }
4067
4068 // Record that we've loaded this module.
4069 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4070 return Success;
4071
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004072 case UNHASHED_CONTROL_BLOCK_ID:
4073 // This block is handled using look-ahead during ReadControlBlock. We
4074 // shouldn't get here!
4075 Error("malformed block record in AST file");
4076 return Failure;
4077
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 default:
4079 if (Stream.SkipBlock()) {
4080 Error("malformed block record in AST file");
4081 return Failure;
4082 }
4083 break;
4084 }
4085 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004086
4087 return Success;
4088}
4089
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004090ASTReader::ASTReadResult
4091ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4092 unsigned ClientLoadCapabilities) {
4093 const HeaderSearchOptions &HSOpts =
4094 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4095 bool AllowCompatibleConfigurationMismatch =
4096 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4097
4098 ASTReadResult Result = readUnhashedControlBlockImpl(
4099 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4100 Listener.get(),
4101 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4102
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004103 // If F was directly imported by another module, it's implicitly validated by
4104 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004105 if (DisableValidation || WasImportedBy ||
4106 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4107 return Success;
4108
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004109 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004110 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004111 return Failure;
4112 }
4113
4114 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4115 // If this module has already been finalized in the PCMCache, we're stuck
4116 // with it; we can only load a single version of each module.
4117 //
4118 // This can happen when a module is imported in two contexts: in one, as a
4119 // user module; in another, as a system module (due to an import from
4120 // another module marked with the [system] flag). It usually indicates a
4121 // bug in the module map: this module should also be marked with [system].
4122 //
4123 // If -Wno-system-headers (the default), and the first import is as a
4124 // system module, then validation will fail during the as-user import,
4125 // since -Werror flags won't have been validated. However, it's reasonable
4126 // to treat this consistently as a system module.
4127 //
4128 // If -Wsystem-headers, the PCM on disk was built with
4129 // -Wno-system-headers, and the first import is as a user module, then
4130 // validation will fail during the as-system import since the PCM on disk
4131 // doesn't guarantee that -Werror was respected. However, the -Werror
4132 // flags were checked during the initial as-user import.
4133 if (PCMCache.isBufferFinal(F.FileName)) {
4134 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4135 return Success;
4136 }
4137 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004138
4139 return Result;
4140}
4141
4142ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4143 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4144 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4145 bool ValidateDiagnosticOptions) {
4146 // Initialize a stream.
4147 BitstreamCursor Stream(StreamData);
4148
4149 // Sniff for the signature.
4150 if (!startsWithASTFileMagic(Stream))
4151 return Failure;
4152
4153 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4154 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4155 return Failure;
4156
4157 // Read all of the records in the options block.
4158 RecordData Record;
4159 ASTReadResult Result = Success;
4160 while (1) {
4161 llvm::BitstreamEntry Entry = Stream.advance();
4162
4163 switch (Entry.Kind) {
4164 case llvm::BitstreamEntry::Error:
4165 case llvm::BitstreamEntry::SubBlock:
4166 return Failure;
4167
4168 case llvm::BitstreamEntry::EndBlock:
4169 return Result;
4170
4171 case llvm::BitstreamEntry::Record:
4172 // The interesting case.
4173 break;
4174 }
4175
4176 // Read and process a record.
4177 Record.clear();
4178 switch (
4179 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4180 case SIGNATURE: {
4181 if (F)
4182 std::copy(Record.begin(), Record.end(), F->Signature.data());
4183 break;
4184 }
4185 case DIAGNOSTIC_OPTIONS: {
4186 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4187 if (Listener && ValidateDiagnosticOptions &&
4188 !AllowCompatibleConfigurationMismatch &&
4189 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004190 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004191 break;
4192 }
4193 case DIAG_PRAGMA_MAPPINGS:
4194 if (!F)
4195 break;
4196 if (F->PragmaDiagMappings.empty())
4197 F->PragmaDiagMappings.swap(Record);
4198 else
4199 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4200 Record.begin(), Record.end());
4201 break;
4202 }
4203 }
4204}
4205
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004206/// Parse a record and blob containing module file extension metadata.
4207static bool parseModuleFileExtensionMetadata(
4208 const SmallVectorImpl<uint64_t> &Record,
4209 StringRef Blob,
4210 ModuleFileExtensionMetadata &Metadata) {
4211 if (Record.size() < 4) return true;
4212
4213 Metadata.MajorVersion = Record[0];
4214 Metadata.MinorVersion = Record[1];
4215
4216 unsigned BlockNameLen = Record[2];
4217 unsigned UserInfoLen = Record[3];
4218
4219 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4220
4221 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4222 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4223 Blob.data() + BlockNameLen + UserInfoLen);
4224 return false;
4225}
4226
4227ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4228 BitstreamCursor &Stream = F.Stream;
4229
4230 RecordData Record;
4231 while (true) {
4232 llvm::BitstreamEntry Entry = Stream.advance();
4233 switch (Entry.Kind) {
4234 case llvm::BitstreamEntry::SubBlock:
4235 if (Stream.SkipBlock())
4236 return Failure;
4237
4238 continue;
4239
4240 case llvm::BitstreamEntry::EndBlock:
4241 return Success;
4242
4243 case llvm::BitstreamEntry::Error:
4244 return HadErrors;
4245
4246 case llvm::BitstreamEntry::Record:
4247 break;
4248 }
4249
4250 Record.clear();
4251 StringRef Blob;
4252 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4253 switch (RecCode) {
4254 case EXTENSION_METADATA: {
4255 ModuleFileExtensionMetadata Metadata;
4256 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4257 return Failure;
4258
4259 // Find a module file extension with this block name.
4260 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4261 if (Known == ModuleFileExtensions.end()) break;
4262
4263 // Form a reader.
4264 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4265 F, Stream)) {
4266 F.ExtensionReaders.push_back(std::move(Reader));
4267 }
4268
4269 break;
4270 }
4271 }
4272 }
4273
4274 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275}
4276
Richard Smitha7e2cc62015-05-01 01:53:09 +00004277void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 // If there's a listener, notify them that we "read" the translation unit.
4279 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004280 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 Context.getTranslationUnitDecl());
4282
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 // FIXME: Find a better way to deal with collisions between these
4284 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004285
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 // Load the special types.
4287 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4288 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4289 if (!Context.CFConstantStringTypeDecl)
4290 Context.setCFConstantStringType(GetType(String));
4291 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004292
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4294 QualType FileType = GetType(File);
4295 if (FileType.isNull()) {
4296 Error("FILE type is NULL");
4297 return;
4298 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004299
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 if (!Context.FILEDecl) {
4301 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4302 Context.setFILEDecl(Typedef->getDecl());
4303 else {
4304 const TagType *Tag = FileType->getAs<TagType>();
4305 if (!Tag) {
4306 Error("Invalid FILE type in AST file");
4307 return;
4308 }
4309 Context.setFILEDecl(Tag->getDecl());
4310 }
4311 }
4312 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004313
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4315 QualType Jmp_bufType = GetType(Jmp_buf);
4316 if (Jmp_bufType.isNull()) {
4317 Error("jmp_buf type is NULL");
4318 return;
4319 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 if (!Context.jmp_bufDecl) {
4322 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4323 Context.setjmp_bufDecl(Typedef->getDecl());
4324 else {
4325 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4326 if (!Tag) {
4327 Error("Invalid jmp_buf type in AST file");
4328 return;
4329 }
4330 Context.setjmp_bufDecl(Tag->getDecl());
4331 }
4332 }
4333 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004334
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4336 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4337 if (Sigjmp_bufType.isNull()) {
4338 Error("sigjmp_buf type is NULL");
4339 return;
4340 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004341
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 if (!Context.sigjmp_bufDecl) {
4343 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4344 Context.setsigjmp_bufDecl(Typedef->getDecl());
4345 else {
4346 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4347 assert(Tag && "Invalid sigjmp_buf type in AST file");
4348 Context.setsigjmp_bufDecl(Tag->getDecl());
4349 }
4350 }
4351 }
4352
4353 if (unsigned ObjCIdRedef
4354 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4355 if (Context.ObjCIdRedefinitionType.isNull())
4356 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4357 }
4358
4359 if (unsigned ObjCClassRedef
4360 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4361 if (Context.ObjCClassRedefinitionType.isNull())
4362 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4363 }
4364
4365 if (unsigned ObjCSelRedef
4366 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4367 if (Context.ObjCSelRedefinitionType.isNull())
4368 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4369 }
4370
4371 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4372 QualType Ucontext_tType = GetType(Ucontext_t);
4373 if (Ucontext_tType.isNull()) {
4374 Error("ucontext_t type is NULL");
4375 return;
4376 }
4377
4378 if (!Context.ucontext_tDecl) {
4379 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4380 Context.setucontext_tDecl(Typedef->getDecl());
4381 else {
4382 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4383 assert(Tag && "Invalid ucontext_t type in AST file");
4384 Context.setucontext_tDecl(Tag->getDecl());
4385 }
4386 }
4387 }
4388 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004389
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4391
4392 // If there were any CUDA special declarations, deserialize them.
4393 if (!CUDASpecialDeclRefs.empty()) {
4394 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4395 Context.setcudaConfigureCallDecl(
4396 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4397 }
Richard Smith56be7542014-03-21 00:33:59 +00004398
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004400 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004401 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004402 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004403 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004404 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004405 if (Import.ImportLoc.isValid())
4406 PP.makeModuleVisible(Imported, Import.ImportLoc);
4407 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004408 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410 ImportedModules.clear();
4411}
4412
4413void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004414 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004415}
4416
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004417/// \brief Reads and return the signature record from \p PCH's control block, or
4418/// else returns 0.
4419static ASTFileSignature readASTFileSignature(StringRef PCH) {
4420 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004421 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004422 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004423
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004424 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4425 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4426 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004427
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004428 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004429 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004430 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004431 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004432 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004433 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004434
4435 Record.clear();
4436 StringRef Blob;
4437 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004438 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4439 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004440 }
4441}
4442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443/// \brief Retrieve the name of the original source file name
4444/// directly from the AST file, without actually loading the AST
4445/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004446std::string ASTReader::getOriginalSourceFile(
4447 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004448 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004450 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004452 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4453 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 return std::string();
4455 }
4456
4457 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004458 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004459
4460 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004461 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4463 return std::string();
4464 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004465
Chris Lattnere7b154b2013-01-19 21:39:22 +00004466 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004467 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004468 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4469 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004471
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004472 // Scan for ORIGINAL_FILE inside the control block.
4473 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004474 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004475 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004476 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4477 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004478
Chris Lattnere7b154b2013-01-19 21:39:22 +00004479 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4480 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4481 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004483
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004485 StringRef Blob;
4486 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4487 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004489}
4490
4491namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004492
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 class SimplePCHValidator : public ASTReaderListener {
4494 const LangOptions &ExistingLangOpts;
4495 const TargetOptions &ExistingTargetOpts;
4496 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004497 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004499
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 public:
4501 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4502 const TargetOptions &ExistingTargetOpts,
4503 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004504 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 FileManager &FileMgr)
4506 : ExistingLangOpts(ExistingLangOpts),
4507 ExistingTargetOpts(ExistingTargetOpts),
4508 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004509 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 FileMgr(FileMgr)
4511 {
4512 }
4513
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004514 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4515 bool AllowCompatibleDifferences) override {
4516 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4517 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004519
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004520 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4521 bool AllowCompatibleDifferences) override {
4522 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4523 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004525
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004526 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4527 StringRef SpecificModuleCachePath,
4528 bool Complain) override {
4529 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4530 ExistingModuleCachePath,
4531 nullptr, ExistingLangOpts);
4532 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004533
Craig Topper3e89dfe2014-03-13 02:13:41 +00004534 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4535 bool Complain,
4536 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004537 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004538 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004541
4542} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004543
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004544bool ASTReader::readASTFileControlBlock(
4545 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004546 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004547 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004548 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004550 // FIXME: This allows use of the VFS; we do not allow use of the
4551 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004552 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 if (!Buffer) {
4554 return true;
4555 }
4556
4557 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004558 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4559 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560
4561 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004562 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004564
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004565 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004566 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004567 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004568
4569 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004570 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004571 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004572 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004573
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004575 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004576 bool DoneWithControlBlock = false;
4577 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004578 llvm::BitstreamEntry Entry = Stream.advance();
4579
4580 switch (Entry.Kind) {
4581 case llvm::BitstreamEntry::SubBlock: {
4582 switch (Entry.ID) {
4583 case OPTIONS_BLOCK_ID: {
4584 std::string IgnoredSuggestedPredefines;
4585 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4586 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004587 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004588 return true;
4589 break;
4590 }
4591
4592 case INPUT_FILES_BLOCK_ID:
4593 InputFilesCursor = Stream;
4594 if (Stream.SkipBlock() ||
4595 (NeedsInputFiles &&
4596 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4597 return true;
4598 break;
4599
4600 default:
4601 if (Stream.SkipBlock())
4602 return true;
4603 break;
4604 }
4605
4606 continue;
4607 }
4608
4609 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004610 DoneWithControlBlock = true;
4611 break;
Richard Smith0516b182015-09-08 19:40:14 +00004612
4613 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004614 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004615
4616 case llvm::BitstreamEntry::Record:
4617 break;
4618 }
4619
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004620 if (DoneWithControlBlock) break;
4621
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004623 StringRef Blob;
4624 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004625 switch ((ControlRecordTypes)RecCode) {
4626 case METADATA: {
4627 if (Record[0] != VERSION_MAJOR)
4628 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004629
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004630 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004631 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004632
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004633 break;
4634 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004635 case MODULE_NAME:
4636 Listener.ReadModuleName(Blob);
4637 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004638 case MODULE_DIRECTORY:
4639 ModuleDir = Blob;
4640 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004641 case MODULE_MAP_FILE: {
4642 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004643 auto Path = ReadString(Record, Idx);
4644 ResolveImportedPath(Path, ModuleDir);
4645 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004646 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004647 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004648 case INPUT_FILE_OFFSETS: {
4649 if (!NeedsInputFiles)
4650 break;
4651
4652 unsigned NumInputFiles = Record[0];
4653 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004654 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004655 for (unsigned I = 0; I != NumInputFiles; ++I) {
4656 // Go find this input file.
4657 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004658
4659 if (isSystemFile && !NeedsSystemInputFiles)
4660 break; // the rest are system input files
4661
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004662 BitstreamCursor &Cursor = InputFilesCursor;
4663 SavedStreamPosition SavedPosition(Cursor);
4664 Cursor.JumpToBit(InputFileOffs[I]);
4665
4666 unsigned Code = Cursor.ReadCode();
4667 RecordData Record;
4668 StringRef Blob;
4669 bool shouldContinue = false;
4670 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4671 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004672 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004673 std::string Filename = Blob;
4674 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004675 shouldContinue = Listener.visitInputFile(
4676 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004677 break;
4678 }
4679 if (!shouldContinue)
4680 break;
4681 }
4682 break;
4683 }
4684
Richard Smithd4b230b2014-10-27 23:01:16 +00004685 case IMPORTS: {
4686 if (!NeedsImports)
4687 break;
4688
4689 unsigned Idx = 0, N = Record.size();
4690 while (Idx < N) {
4691 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004692 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004693 std::string Filename = ReadString(Record, Idx);
4694 ResolveImportedPath(Filename, ModuleDir);
4695 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004696 }
4697 break;
4698 }
4699
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004700 default:
4701 // No other validation to perform.
4702 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 }
4704 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004705
4706 // Look for module file extension blocks, if requested.
4707 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004708 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004709 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4710 bool DoneWithExtensionBlock = false;
4711 while (!DoneWithExtensionBlock) {
4712 llvm::BitstreamEntry Entry = Stream.advance();
4713
4714 switch (Entry.Kind) {
4715 case llvm::BitstreamEntry::SubBlock:
4716 if (Stream.SkipBlock())
4717 return true;
4718
4719 continue;
4720
4721 case llvm::BitstreamEntry::EndBlock:
4722 DoneWithExtensionBlock = true;
4723 continue;
4724
4725 case llvm::BitstreamEntry::Error:
4726 return true;
4727
4728 case llvm::BitstreamEntry::Record:
4729 break;
4730 }
4731
4732 Record.clear();
4733 StringRef Blob;
4734 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4735 switch (RecCode) {
4736 case EXTENSION_METADATA: {
4737 ModuleFileExtensionMetadata Metadata;
4738 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4739 return true;
4740
4741 Listener.readModuleFileExtension(Metadata);
4742 break;
4743 }
4744 }
4745 }
4746 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004747 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004748 }
4749
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004750 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4751 if (readUnhashedControlBlockImpl(
4752 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4753 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4754 ValidateDiagnosticOptions) != Success)
4755 return true;
4756
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004757 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004758}
4759
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004760bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4761 const PCHContainerReader &PCHContainerRdr,
4762 const LangOptions &LangOpts,
4763 const TargetOptions &TargetOpts,
4764 const PreprocessorOptions &PPOpts,
4765 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004766 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4767 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004768 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004769 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004770 validator,
4771 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004772}
4773
Ben Langmuir2c9af442014-04-10 17:57:43 +00004774ASTReader::ASTReadResult
4775ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 // Enter the submodule block.
4777 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4778 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004779 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 }
4781
4782 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4783 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004784 Module *CurrentModule = nullptr;
Richard Smith145e15a2017-04-24 23:12:30 +00004785 Module::ModuleKind ModuleKind = Module::ModuleMapModule;
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 RecordData Record;
4787 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004788 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004789
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004790 switch (Entry.Kind) {
4791 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4792 case llvm::BitstreamEntry::Error:
4793 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004794 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004795 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004796 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004797 case llvm::BitstreamEntry::Record:
4798 // The interesting case.
4799 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004801
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004803 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004805 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4806
4807 if ((Kind == SUBMODULE_METADATA) != First) {
4808 Error("submodule metadata record should be at beginning of block");
4809 return Failure;
4810 }
4811 First = false;
4812
4813 // Submodule information is only valid if we have a current module.
4814 // FIXME: Should we error on these cases?
4815 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4816 Kind != SUBMODULE_DEFINITION)
4817 continue;
4818
4819 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 default: // Default behavior: ignore.
4821 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004822
Richard Smith03478d92014-10-23 22:12:14 +00004823 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004824 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004826 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 }
Richard Smith03478d92014-10-23 22:12:14 +00004828
Chris Lattner0e6c9402013-01-20 02:38:54 +00004829 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004830 unsigned Idx = 0;
4831 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4832 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4833 bool IsFramework = Record[Idx++];
4834 bool IsExplicit = Record[Idx++];
4835 bool IsSystem = Record[Idx++];
4836 bool IsExternC = Record[Idx++];
4837 bool InferSubmodules = Record[Idx++];
4838 bool InferExplicitSubmodules = Record[Idx++];
4839 bool InferExportWildcard = Record[Idx++];
4840 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004841
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004842 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004843 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004845
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 // Retrieve this (sub)module from the module map, creating it if
4847 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004848 CurrentModule =
4849 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4850 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004851
4852 // FIXME: set the definition loc for CurrentModule, or call
4853 // ModMap.setInferredModuleAllowedBy()
4854
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4856 if (GlobalIndex >= SubmodulesLoaded.size() ||
4857 SubmodulesLoaded[GlobalIndex]) {
4858 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004859 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004861
Douglas Gregor7029ce12013-03-19 00:28:20 +00004862 if (!ParentModule) {
4863 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4864 if (CurFile != F.File) {
4865 if (!Diags.isDiagnosticInFlight()) {
4866 Diag(diag::err_module_file_conflict)
4867 << CurrentModule->getTopLevelModuleName()
4868 << CurFile->getName()
4869 << F.File->getName();
4870 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004871 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004872 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004873 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004874
4875 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004876 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004877
Richard Smith145e15a2017-04-24 23:12:30 +00004878 CurrentModule->Kind = ModuleKind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00004879 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 CurrentModule->IsFromModuleFile = true;
4881 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004882 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 CurrentModule->InferSubmodules = InferSubmodules;
4884 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4885 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004886 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 if (DeserializationListener)
4888 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004889
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004891
Richard Smith8a3e39a2016-03-28 21:31:09 +00004892 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004893 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004894 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004895 CurrentModule->UnresolvedConflicts.clear();
4896 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004897
4898 // The module is available unless it's missing a requirement; relevant
4899 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4900 // Missing headers that were present when the module was built do not
4901 // make it unavailable -- if we got this far, this must be an explicitly
4902 // imported module file.
4903 CurrentModule->Requirements.clear();
4904 CurrentModule->MissingHeaders.clear();
4905 CurrentModule->IsMissingRequirement =
4906 ParentModule && ParentModule->IsMissingRequirement;
4907 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 break;
4909 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004910
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004912 std::string Filename = Blob;
4913 ResolveImportedPath(F, Filename);
4914 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004916 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4917 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00004918 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4919 Error("mismatched umbrella headers in submodule");
4920 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 }
4922 }
4923 break;
4924 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004925
Richard Smith202210b2014-10-24 20:23:01 +00004926 case SUBMODULE_HEADER:
4927 case SUBMODULE_EXCLUDED_HEADER:
4928 case SUBMODULE_PRIVATE_HEADER:
4929 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004930 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4931 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004932 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004933
Richard Smith202210b2014-10-24 20:23:01 +00004934 case SUBMODULE_TEXTUAL_HEADER:
4935 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4936 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4937 // them here.
4938 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004939
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004941 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 break;
4943 }
4944
4945 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004946 std::string Dirname = Blob;
4947 ResolveImportedPath(F, Dirname);
4948 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004950 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4951 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004952 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4953 Error("mismatched umbrella directories in submodule");
4954 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 }
4956 }
4957 break;
4958 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004959
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 F.BaseSubmoduleID = getTotalNumSubmodules();
4962 F.LocalNumSubmodules = Record[0];
4963 unsigned LocalBaseSubmoduleID = Record[1];
4964 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004965 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 // module.
4967 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004968
4969 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 // module.
4971 F.SubmoduleRemap.insertOrReplace(
4972 std::make_pair(LocalBaseSubmoduleID,
4973 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004974
Ben Langmuir52ca6782014-10-20 16:27:32 +00004975 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4976 }
Richard Smith145e15a2017-04-24 23:12:30 +00004977 ModuleKind = (Module::ModuleKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 break;
4979 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004980
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004983 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 Unresolved.File = &F;
4985 Unresolved.Mod = CurrentModule;
4986 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004987 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004989 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 }
4991 break;
4992 }
4993
4994 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004996 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 Unresolved.File = &F;
4998 Unresolved.Mod = CurrentModule;
4999 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005000 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005002 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005004
5005 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 // the parsed, unresolved exports around.
5007 CurrentModule->UnresolvedExports.clear();
5008 break;
5009 }
5010 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00005011 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 Context.getTargetInfo());
5013 break;
5014 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005015
5016 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005017 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005018 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005019 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005020
5021 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005022 CurrentModule->ConfigMacros.push_back(Blob.str());
5023 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005024
5025 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005026 UnresolvedModuleRef Unresolved;
5027 Unresolved.File = &F;
5028 Unresolved.Mod = CurrentModule;
5029 Unresolved.ID = Record[0];
5030 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5031 Unresolved.IsWildcard = false;
5032 Unresolved.String = Blob;
5033 UnresolvedModuleRefs.push_back(Unresolved);
5034 break;
5035 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005036
5037 case SUBMODULE_INITIALIZERS:
5038 SmallVector<uint32_t, 16> Inits;
5039 for (auto &ID : Record)
5040 Inits.push_back(getGlobalDeclID(F, ID));
5041 Context.addLazyModuleInitializers(CurrentModule, Inits);
5042 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 }
5044 }
5045}
5046
5047/// \brief Parse the record that corresponds to a LangOptions data
5048/// structure.
5049///
5050/// This routine parses the language options from the AST file and then gives
5051/// them to the AST listener if one is set.
5052///
5053/// \returns true if the listener deems the file unacceptable, false otherwise.
5054bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5055 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005056 ASTReaderListener &Listener,
5057 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 LangOptions LangOpts;
5059 unsigned Idx = 0;
5060#define LANGOPT(Name, Bits, Default, Description) \
5061 LangOpts.Name = Record[Idx++];
5062#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5063 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5064#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005065#define SANITIZER(NAME, ID) \
5066 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005067#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005068
Ben Langmuircd98cb72015-06-23 18:20:18 +00005069 for (unsigned N = Record[Idx++]; N; --N)
5070 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5071
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5073 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5074 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005075
Ben Langmuird4a667a2015-06-23 18:20:23 +00005076 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005077
5078 // Comment options.
5079 for (unsigned N = Record[Idx++]; N; --N) {
5080 LangOpts.CommentOpts.BlockCommandNames.push_back(
5081 ReadString(Record, Idx));
5082 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005083 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005084
Samuel Antaoee8fb302016-01-06 13:42:12 +00005085 // OpenMP offloading options.
5086 for (unsigned N = Record[Idx++]; N; --N) {
5087 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5088 }
5089
5090 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5091
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005092 return Listener.ReadLanguageOptions(LangOpts, Complain,
5093 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005094}
5095
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005096bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5097 ASTReaderListener &Listener,
5098 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 unsigned Idx = 0;
5100 TargetOptions TargetOpts;
5101 TargetOpts.Triple = ReadString(Record, Idx);
5102 TargetOpts.CPU = ReadString(Record, Idx);
5103 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 for (unsigned N = Record[Idx++]; N; --N) {
5105 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5106 }
5107 for (unsigned N = Record[Idx++]; N; --N) {
5108 TargetOpts.Features.push_back(ReadString(Record, Idx));
5109 }
5110
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005111 return Listener.ReadTargetOptions(TargetOpts, Complain,
5112 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005113}
5114
5115bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5116 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005117 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005119#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005120#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005121 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005122#include "clang/Basic/DiagnosticOptions.def"
5123
Richard Smith3be1cb22014-08-07 00:24:21 +00005124 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005125 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005126 for (unsigned N = Record[Idx++]; N; --N)
5127 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005128
5129 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5130}
5131
5132bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5133 ASTReaderListener &Listener) {
5134 FileSystemOptions FSOpts;
5135 unsigned Idx = 0;
5136 FSOpts.WorkingDir = ReadString(Record, Idx);
5137 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5138}
5139
5140bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5141 bool Complain,
5142 ASTReaderListener &Listener) {
5143 HeaderSearchOptions HSOpts;
5144 unsigned Idx = 0;
5145 HSOpts.Sysroot = ReadString(Record, Idx);
5146
5147 // Include entries.
5148 for (unsigned N = Record[Idx++]; N; --N) {
5149 std::string Path = ReadString(Record, Idx);
5150 frontend::IncludeDirGroup Group
5151 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 bool IsFramework = Record[Idx++];
5153 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005154 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5155 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 }
5157
5158 // System header prefixes.
5159 for (unsigned N = Record[Idx++]; N; --N) {
5160 std::string Prefix = ReadString(Record, Idx);
5161 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005162 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 }
5164
5165 HSOpts.ResourceDir = ReadString(Record, Idx);
5166 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005167 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 HSOpts.DisableModuleHash = Record[Idx++];
5169 HSOpts.UseBuiltinIncludes = Record[Idx++];
5170 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5171 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5172 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005173 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005174
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005175 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5176 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005177}
5178
5179bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5180 bool Complain,
5181 ASTReaderListener &Listener,
5182 std::string &SuggestedPredefines) {
5183 PreprocessorOptions PPOpts;
5184 unsigned Idx = 0;
5185
5186 // Macro definitions/undefs
5187 for (unsigned N = Record[Idx++]; N; --N) {
5188 std::string Macro = ReadString(Record, Idx);
5189 bool IsUndef = Record[Idx++];
5190 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5191 }
5192
5193 // Includes
5194 for (unsigned N = Record[Idx++]; N; --N) {
5195 PPOpts.Includes.push_back(ReadString(Record, Idx));
5196 }
5197
5198 // Macro Includes
5199 for (unsigned N = Record[Idx++]; N; --N) {
5200 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5201 }
5202
5203 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005204 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5206 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5207 PPOpts.ObjCXXARCStandardLibrary =
5208 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5209 SuggestedPredefines.clear();
5210 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5211 SuggestedPredefines);
5212}
5213
5214std::pair<ModuleFile *, unsigned>
5215ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5216 GlobalPreprocessedEntityMapType::iterator
5217 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005218 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 "Corrupted global preprocessed entity map");
5220 ModuleFile *M = I->second;
5221 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5222 return std::make_pair(M, LocalIndex);
5223}
5224
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005225llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005226ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5227 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5228 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5229 Mod.NumPreprocessedEntities);
5230
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005231 return llvm::make_range(PreprocessingRecord::iterator(),
5232 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005233}
5234
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005235llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005236ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005237 return llvm::make_range(
5238 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5239 ModuleDeclIterator(this, &Mod,
5240 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005241}
5242
5243PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5244 PreprocessedEntityID PPID = Index+1;
5245 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5246 ModuleFile &M = *PPInfo.first;
5247 unsigned LocalIndex = PPInfo.second;
5248 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5249
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 if (!PP.getPreprocessingRecord()) {
5251 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005252 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005254
5255 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005256 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5257
5258 llvm::BitstreamEntry Entry =
5259 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5260 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005261 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005262
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005264 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5265 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005267 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 RecordData Record;
5269 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005270 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5271 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 switch (RecType) {
5273 case PPD_MACRO_EXPANSION: {
5274 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005275 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005276 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 if (isBuiltin)
5278 Name = getLocalIdentifier(M, Record[1]);
5279 else {
Richard Smith66a81862015-05-04 02:25:31 +00005280 PreprocessedEntityID GlobalID =
5281 getGlobalPreprocessedEntityID(M, Record[1]);
5282 Def = cast<MacroDefinitionRecord>(
5283 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 }
5285
5286 MacroExpansion *ME;
5287 if (isBuiltin)
5288 ME = new (PPRec) MacroExpansion(Name, Range);
5289 else
5290 ME = new (PPRec) MacroExpansion(Def, Range);
5291
5292 return ME;
5293 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005294
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 case PPD_MACRO_DEFINITION: {
5296 // Decode the identifier info and then check again; if the macro is
5297 // still defined and associated with the identifier,
5298 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005299 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005300
5301 if (DeserializationListener)
5302 DeserializationListener->MacroDefinitionRead(PPID, MD);
5303
5304 return MD;
5305 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005306
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005308 const char *FullFileNameStart = Blob.data() + Record[0];
5309 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005310 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 if (!FullFileName.empty())
5312 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005313
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 // FIXME: Stable encoding
5315 InclusionDirective::InclusionKind Kind
5316 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5317 InclusionDirective *ID
5318 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005319 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 Record[1], Record[3],
5321 File,
5322 Range);
5323 return ID;
5324 }
5325 }
5326
5327 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5328}
5329
5330/// \brief \arg SLocMapI points at a chunk of a module that contains no
5331/// preprocessed entities or the entities it contains are not the ones we are
5332/// looking for. Find the next module that contains entities and return the ID
5333/// of the first entry.
5334PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5335 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5336 ++SLocMapI;
5337 for (GlobalSLocOffsetMapType::const_iterator
5338 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5339 ModuleFile &M = *SLocMapI->second;
5340 if (M.NumPreprocessedEntities)
5341 return M.BasePreprocessedEntityID;
5342 }
5343
5344 return getTotalNumPreprocessedEntities();
5345}
5346
5347namespace {
5348
Guy Benyei11169dd2012-12-18 14:30:41 +00005349struct PPEntityComp {
5350 const ASTReader &Reader;
5351 ModuleFile &M;
5352
5353 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5354
5355 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5356 SourceLocation LHS = getLoc(L);
5357 SourceLocation RHS = getLoc(R);
5358 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5359 }
5360
5361 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5362 SourceLocation LHS = getLoc(L);
5363 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5364 }
5365
5366 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5367 SourceLocation RHS = getLoc(R);
5368 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5369 }
5370
5371 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005372 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 }
5374};
5375
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005376} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005377
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005378PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5379 bool EndsAfter) const {
5380 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 return getTotalNumPreprocessedEntities();
5382
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005383 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5384 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5386 "Corrupted global sloc offset map");
5387
5388 if (SLocMapI->second->NumPreprocessedEntities == 0)
5389 return findNextPreprocessedEntity(SLocMapI);
5390
5391 ModuleFile &M = *SLocMapI->second;
5392 typedef const PPEntityOffset *pp_iterator;
5393 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5394 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5395
5396 size_t Count = M.NumPreprocessedEntities;
5397 size_t Half;
5398 pp_iterator First = pp_begin;
5399 pp_iterator PPI;
5400
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005401 if (EndsAfter) {
5402 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005403 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005404 } else {
5405 // Do a binary search manually instead of using std::lower_bound because
5406 // The end locations of entities may be unordered (when a macro expansion
5407 // is inside another macro argument), but for this case it is not important
5408 // whether we get the first macro expansion or its containing macro.
5409 while (Count > 0) {
5410 Half = Count / 2;
5411 PPI = First;
5412 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005413 if (SourceMgr.isBeforeInTranslationUnit(
5414 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005415 First = PPI;
5416 ++First;
5417 Count = Count - Half - 1;
5418 } else
5419 Count = Half;
5420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 }
5422
5423 if (PPI == pp_end)
5424 return findNextPreprocessedEntity(SLocMapI);
5425
5426 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5427}
5428
Guy Benyei11169dd2012-12-18 14:30:41 +00005429/// \brief Returns a pair of [Begin, End) indices of preallocated
5430/// preprocessed entities that \arg Range encompasses.
5431std::pair<unsigned, unsigned>
5432 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5433 if (Range.isInvalid())
5434 return std::make_pair(0,0);
5435 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5436
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005437 PreprocessedEntityID BeginID =
5438 findPreprocessedEntity(Range.getBegin(), false);
5439 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 return std::make_pair(BeginID, EndID);
5441}
5442
5443/// \brief Optionally returns true or false if the preallocated preprocessed
5444/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005445Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 FileID FID) {
5447 if (FID.isInvalid())
5448 return false;
5449
5450 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5451 ModuleFile &M = *PPInfo.first;
5452 unsigned LocalIndex = PPInfo.second;
5453 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005454
Richard Smithcb34bd32016-03-27 07:28:06 +00005455 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 if (Loc.isInvalid())
5457 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005458
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5460 return true;
5461 else
5462 return false;
5463}
5464
5465namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005466
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 /// \brief Visitor used to search for information about a header file.
5468 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005470
David Blaikie05785d12013-02-20 22:23:23 +00005471 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005472
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005474 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5475 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005476
5477 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 HeaderFileInfoLookupTable *Table
5479 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5480 if (!Table)
5481 return false;
5482
5483 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005484 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005485 if (Pos == Table->end())
5486 return false;
5487
Richard Smithbdf2d932015-07-30 03:37:16 +00005488 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 return true;
5490 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005491
David Blaikie05785d12013-02-20 22:23:23 +00005492 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005494
5495} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005496
5497HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005498 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005499 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005500 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005501 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005502
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 return HeaderFileInfo();
5504}
5505
5506void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005507 using DiagState = DiagnosticsEngine::DiagState;
5508 SmallVector<DiagState *, 32> DiagStates;
5509
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005510 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005512 auto &Record = F.PragmaDiagMappings;
5513 if (Record.empty())
5514 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005515
Richard Smithd230de22017-01-26 01:01:01 +00005516 DiagStates.clear();
5517
5518 auto ReadDiagState =
5519 [&](const DiagState &BasedOn, SourceLocation Loc,
5520 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5521 unsigned BackrefID = Record[Idx++];
5522 if (BackrefID != 0)
5523 return DiagStates[BackrefID - 1];
5524
Guy Benyei11169dd2012-12-18 14:30:41 +00005525 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005526 Diag.DiagStates.push_back(BasedOn);
5527 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005529 unsigned Size = Record[Idx++];
5530 assert(Idx + Size * 2 <= Record.size() &&
5531 "Invalid data, not enough diag/map pairs");
5532 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005533 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005534 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005535 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005536 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5537 continue;
5538
5539 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5540
5541 // If this mapping was specified as a warning but the severity was
5542 // upgraded due to diagnostic settings, simulate the current diagnostic
5543 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005544 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5545 NewMapping.setSeverity(diag::Severity::Warning);
5546 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005547 }
5548
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005549 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005550 }
Richard Smithd230de22017-01-26 01:01:01 +00005551 return NewState;
5552 };
5553
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005554 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005555 DiagState *FirstState;
5556 if (F.Kind == MK_ImplicitModule) {
5557 // Implicitly-built modules are reused with different diagnostic
5558 // settings. Use the initial diagnostic state from Diag to simulate this
5559 // compilation's diagnostic settings.
5560 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5561 DiagStates.push_back(FirstState);
5562
5563 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005564 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005565 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005566 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005567 assert(Idx < Record.size() &&
5568 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005569 } else if (F.isModule()) {
5570 // For an explicit module, preserve the flags from the module build
5571 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5572 // -Wblah flags.
5573 unsigned Flags = Record[Idx++];
5574 DiagState Initial;
5575 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5576 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5577 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5578 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5579 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5580 Initial.ExtBehavior = (diag::Severity)Flags;
5581 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005582
Richard Smithe37391c2017-05-03 00:28:49 +00005583 // Set up the root buffer of the module to start with the initial
5584 // diagnostic state of the module itself, to cover files that contain no
5585 // explicit transitions (for which we did not serialize anything).
5586 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5587 .StateTransitions.push_back({FirstState, 0});
5588 } else {
5589 // For prefix ASTs, start with whatever the user configured on the
5590 // command line.
5591 Idx++; // Skip flags.
5592 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5593 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005594 }
Richard Smithd230de22017-01-26 01:01:01 +00005595
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005596 // Read the state transitions.
5597 unsigned NumLocations = Record[Idx++];
5598 while (NumLocations--) {
5599 assert(Idx < Record.size() &&
5600 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005601 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5602 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5603 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5604 unsigned Transitions = Record[Idx++];
5605
5606 // Note that we don't need to set up Parent/ParentOffset here, because
5607 // we won't be changing the diagnostic state within imported FileIDs
5608 // (other than perhaps appending to the main source file, which has no
5609 // parent).
5610 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5611 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5612 for (unsigned I = 0; I != Transitions; ++I) {
5613 unsigned Offset = Record[Idx++];
5614 auto *State =
5615 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5616 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 }
5618 }
Richard Smithd230de22017-01-26 01:01:01 +00005619
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005620 // Read the final state.
5621 assert(Idx < Record.size() &&
5622 "Invalid data, missing final pragma diagnostic state");
5623 SourceLocation CurStateLoc =
5624 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5625 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5626
5627 if (!F.isModule()) {
5628 Diag.DiagStatesByLoc.CurDiagState = CurState;
5629 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5630
5631 // Preserve the property that the imaginary root file describes the
5632 // current state.
5633 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5634 if (T.empty())
5635 T.push_back({CurState, 0});
5636 else
5637 T[0].State = CurState;
5638 }
5639
Richard Smithd230de22017-01-26 01:01:01 +00005640 // Don't try to read these mappings again.
5641 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 }
5643}
5644
5645/// \brief Get the correct cursor and offset for loading a type.
5646ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5647 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5648 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5649 ModuleFile *M = I->second;
5650 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5651}
5652
5653/// \brief Read and return the type with the given index..
5654///
5655/// The index is the type ID, shifted and minus the number of predefs. This
5656/// routine actually reads the record corresponding to the type at the given
5657/// location. It is a helper routine for GetType, which deals with reading type
5658/// IDs.
5659QualType ASTReader::readTypeRecord(unsigned Index) {
5660 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005661 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005662
5663 // Keep track of where we are in the stream, then jump back there
5664 // after reading this type.
5665 SavedStreamPosition SavedPosition(DeclsCursor);
5666
5667 ReadingKindTracker ReadingKind(Read_Type, *this);
5668
5669 // Note that we are loading a type record.
5670 Deserializing AType(this);
5671
5672 unsigned Idx = 0;
5673 DeclsCursor.JumpToBit(Loc.Offset);
5674 RecordData Record;
5675 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005676 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 case TYPE_EXT_QUAL: {
5678 if (Record.size() != 2) {
5679 Error("Incorrect encoding of extended qualifier type");
5680 return QualType();
5681 }
5682 QualType Base = readType(*Loc.F, Record, Idx);
5683 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5684 return Context.getQualifiedType(Base, Quals);
5685 }
5686
5687 case TYPE_COMPLEX: {
5688 if (Record.size() != 1) {
5689 Error("Incorrect encoding of complex type");
5690 return QualType();
5691 }
5692 QualType ElemType = readType(*Loc.F, Record, Idx);
5693 return Context.getComplexType(ElemType);
5694 }
5695
5696 case TYPE_POINTER: {
5697 if (Record.size() != 1) {
5698 Error("Incorrect encoding of pointer type");
5699 return QualType();
5700 }
5701 QualType PointeeType = readType(*Loc.F, Record, Idx);
5702 return Context.getPointerType(PointeeType);
5703 }
5704
Reid Kleckner8a365022013-06-24 17:51:48 +00005705 case TYPE_DECAYED: {
5706 if (Record.size() != 1) {
5707 Error("Incorrect encoding of decayed type");
5708 return QualType();
5709 }
5710 QualType OriginalType = readType(*Loc.F, Record, Idx);
5711 QualType DT = Context.getAdjustedParameterType(OriginalType);
5712 if (!isa<DecayedType>(DT))
5713 Error("Decayed type does not decay");
5714 return DT;
5715 }
5716
Reid Kleckner0503a872013-12-05 01:23:43 +00005717 case TYPE_ADJUSTED: {
5718 if (Record.size() != 2) {
5719 Error("Incorrect encoding of adjusted type");
5720 return QualType();
5721 }
5722 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5723 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5724 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5725 }
5726
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 case TYPE_BLOCK_POINTER: {
5728 if (Record.size() != 1) {
5729 Error("Incorrect encoding of block pointer type");
5730 return QualType();
5731 }
5732 QualType PointeeType = readType(*Loc.F, Record, Idx);
5733 return Context.getBlockPointerType(PointeeType);
5734 }
5735
5736 case TYPE_LVALUE_REFERENCE: {
5737 if (Record.size() != 2) {
5738 Error("Incorrect encoding of lvalue reference type");
5739 return QualType();
5740 }
5741 QualType PointeeType = readType(*Loc.F, Record, Idx);
5742 return Context.getLValueReferenceType(PointeeType, Record[1]);
5743 }
5744
5745 case TYPE_RVALUE_REFERENCE: {
5746 if (Record.size() != 1) {
5747 Error("Incorrect encoding of rvalue reference type");
5748 return QualType();
5749 }
5750 QualType PointeeType = readType(*Loc.F, Record, Idx);
5751 return Context.getRValueReferenceType(PointeeType);
5752 }
5753
5754 case TYPE_MEMBER_POINTER: {
5755 if (Record.size() != 2) {
5756 Error("Incorrect encoding of member pointer type");
5757 return QualType();
5758 }
5759 QualType PointeeType = readType(*Loc.F, Record, Idx);
5760 QualType ClassType = readType(*Loc.F, Record, Idx);
5761 if (PointeeType.isNull() || ClassType.isNull())
5762 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005763
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5765 }
5766
5767 case TYPE_CONSTANT_ARRAY: {
5768 QualType ElementType = readType(*Loc.F, Record, Idx);
5769 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5770 unsigned IndexTypeQuals = Record[2];
5771 unsigned Idx = 3;
5772 llvm::APInt Size = ReadAPInt(Record, Idx);
5773 return Context.getConstantArrayType(ElementType, Size,
5774 ASM, IndexTypeQuals);
5775 }
5776
5777 case TYPE_INCOMPLETE_ARRAY: {
5778 QualType ElementType = readType(*Loc.F, Record, Idx);
5779 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5780 unsigned IndexTypeQuals = Record[2];
5781 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5782 }
5783
5784 case TYPE_VARIABLE_ARRAY: {
5785 QualType ElementType = readType(*Loc.F, Record, Idx);
5786 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5787 unsigned IndexTypeQuals = Record[2];
5788 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5789 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5790 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5791 ASM, IndexTypeQuals,
5792 SourceRange(LBLoc, RBLoc));
5793 }
5794
5795 case TYPE_VECTOR: {
5796 if (Record.size() != 3) {
5797 Error("incorrect encoding of vector type in AST file");
5798 return QualType();
5799 }
5800
5801 QualType ElementType = readType(*Loc.F, Record, Idx);
5802 unsigned NumElements = Record[1];
5803 unsigned VecKind = Record[2];
5804 return Context.getVectorType(ElementType, NumElements,
5805 (VectorType::VectorKind)VecKind);
5806 }
5807
5808 case TYPE_EXT_VECTOR: {
5809 if (Record.size() != 3) {
5810 Error("incorrect encoding of extended vector type in AST file");
5811 return QualType();
5812 }
5813
5814 QualType ElementType = readType(*Loc.F, Record, Idx);
5815 unsigned NumElements = Record[1];
5816 return Context.getExtVectorType(ElementType, NumElements);
5817 }
5818
5819 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005820 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 Error("incorrect encoding of no-proto function type");
5822 return QualType();
5823 }
5824 QualType ResultType = readType(*Loc.F, Record, Idx);
5825 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005826 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 return Context.getFunctionNoProtoType(ResultType, Info);
5828 }
5829
5830 case TYPE_FUNCTION_PROTO: {
5831 QualType ResultType = readType(*Loc.F, Record, Idx);
5832
5833 FunctionProtoType::ExtProtoInfo EPI;
5834 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5835 /*hasregparm*/ Record[2],
5836 /*regparm*/ Record[3],
5837 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005838 /*produces*/ Record[5],
5839 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005840
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005841 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00005842
5843 EPI.Variadic = Record[Idx++];
5844 EPI.HasTrailingReturn = Record[Idx++];
5845 EPI.TypeQuals = Record[Idx++];
5846 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005847 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005848 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005849
5850 unsigned NumParams = Record[Idx++];
5851 SmallVector<QualType, 16> ParamTypes;
5852 for (unsigned I = 0; I != NumParams; ++I)
5853 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5854
John McCall18afab72016-03-01 00:49:02 +00005855 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5856 if (Idx != Record.size()) {
5857 for (unsigned I = 0; I != NumParams; ++I)
5858 ExtParameterInfos.push_back(
5859 FunctionProtoType::ExtParameterInfo
5860 ::getFromOpaqueValue(Record[Idx++]));
5861 EPI.ExtParameterInfos = ExtParameterInfos.data();
5862 }
5863
5864 assert(Idx == Record.size());
5865
Jordan Rose5c382722013-03-08 21:51:21 +00005866 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 }
5868
5869 case TYPE_UNRESOLVED_USING: {
5870 unsigned Idx = 0;
5871 return Context.getTypeDeclType(
5872 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5873 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005874
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 case TYPE_TYPEDEF: {
5876 if (Record.size() != 2) {
5877 Error("incorrect encoding of typedef type");
5878 return QualType();
5879 }
5880 unsigned Idx = 0;
5881 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5882 QualType Canonical = readType(*Loc.F, Record, Idx);
5883 if (!Canonical.isNull())
5884 Canonical = Context.getCanonicalType(Canonical);
5885 return Context.getTypedefType(Decl, Canonical);
5886 }
5887
5888 case TYPE_TYPEOF_EXPR:
5889 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5890
5891 case TYPE_TYPEOF: {
5892 if (Record.size() != 1) {
5893 Error("incorrect encoding of typeof(type) in AST file");
5894 return QualType();
5895 }
5896 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5897 return Context.getTypeOfType(UnderlyingType);
5898 }
5899
5900 case TYPE_DECLTYPE: {
5901 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5902 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5903 }
5904
5905 case TYPE_UNARY_TRANSFORM: {
5906 QualType BaseType = readType(*Loc.F, Record, Idx);
5907 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5908 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5909 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5910 }
5911
Richard Smith74aeef52013-04-26 16:15:35 +00005912 case TYPE_AUTO: {
5913 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005914 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005915 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005916 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005918
Richard Smith600b5262017-01-26 20:40:47 +00005919 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5920 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5921 QualType Deduced = readType(*Loc.F, Record, Idx);
5922 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5923 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5924 IsDependent);
5925 }
5926
Guy Benyei11169dd2012-12-18 14:30:41 +00005927 case TYPE_RECORD: {
5928 if (Record.size() != 2) {
5929 Error("incorrect encoding of record type");
5930 return QualType();
5931 }
5932 unsigned Idx = 0;
5933 bool IsDependent = Record[Idx++];
5934 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5935 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5936 QualType T = Context.getRecordType(RD);
5937 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5938 return T;
5939 }
5940
5941 case TYPE_ENUM: {
5942 if (Record.size() != 2) {
5943 Error("incorrect encoding of enum type");
5944 return QualType();
5945 }
5946 unsigned Idx = 0;
5947 bool IsDependent = Record[Idx++];
5948 QualType T
5949 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5950 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5951 return T;
5952 }
5953
5954 case TYPE_ATTRIBUTED: {
5955 if (Record.size() != 3) {
5956 Error("incorrect encoding of attributed type");
5957 return QualType();
5958 }
5959 QualType modifiedType = readType(*Loc.F, Record, Idx);
5960 QualType equivalentType = readType(*Loc.F, Record, Idx);
5961 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5962 return Context.getAttributedType(kind, modifiedType, equivalentType);
5963 }
5964
5965 case TYPE_PAREN: {
5966 if (Record.size() != 1) {
5967 Error("incorrect encoding of paren type");
5968 return QualType();
5969 }
5970 QualType InnerType = readType(*Loc.F, Record, Idx);
5971 return Context.getParenType(InnerType);
5972 }
5973
5974 case TYPE_PACK_EXPANSION: {
5975 if (Record.size() != 2) {
5976 Error("incorrect encoding of pack expansion type");
5977 return QualType();
5978 }
5979 QualType Pattern = readType(*Loc.F, Record, Idx);
5980 if (Pattern.isNull())
5981 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005982 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 if (Record[1])
5984 NumExpansions = Record[1] - 1;
5985 return Context.getPackExpansionType(Pattern, NumExpansions);
5986 }
5987
5988 case TYPE_ELABORATED: {
5989 unsigned Idx = 0;
5990 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5991 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5992 QualType NamedType = readType(*Loc.F, Record, Idx);
5993 return Context.getElaboratedType(Keyword, NNS, NamedType);
5994 }
5995
5996 case TYPE_OBJC_INTERFACE: {
5997 unsigned Idx = 0;
5998 ObjCInterfaceDecl *ItfD
5999 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6000 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6001 }
6002
Manman Rene6be26c2016-09-13 17:25:08 +00006003 case TYPE_OBJC_TYPE_PARAM: {
6004 unsigned Idx = 0;
6005 ObjCTypeParamDecl *Decl
6006 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6007 unsigned NumProtos = Record[Idx++];
6008 SmallVector<ObjCProtocolDecl*, 4> Protos;
6009 for (unsigned I = 0; I != NumProtos; ++I)
6010 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6011 return Context.getObjCTypeParamType(Decl, Protos);
6012 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006013 case TYPE_OBJC_OBJECT: {
6014 unsigned Idx = 0;
6015 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006016 unsigned NumTypeArgs = Record[Idx++];
6017 SmallVector<QualType, 4> TypeArgs;
6018 for (unsigned I = 0; I != NumTypeArgs; ++I)
6019 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006020 unsigned NumProtos = Record[Idx++];
6021 SmallVector<ObjCProtocolDecl*, 4> Protos;
6022 for (unsigned I = 0; I != NumProtos; ++I)
6023 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006024 bool IsKindOf = Record[Idx++];
6025 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006026 }
6027
6028 case TYPE_OBJC_OBJECT_POINTER: {
6029 unsigned Idx = 0;
6030 QualType Pointee = readType(*Loc.F, Record, Idx);
6031 return Context.getObjCObjectPointerType(Pointee);
6032 }
6033
6034 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6035 unsigned Idx = 0;
6036 QualType Parm = readType(*Loc.F, Record, Idx);
6037 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006038 return Context.getSubstTemplateTypeParmType(
6039 cast<TemplateTypeParmType>(Parm),
6040 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 }
6042
6043 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6044 unsigned Idx = 0;
6045 QualType Parm = readType(*Loc.F, Record, Idx);
6046 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6047 return Context.getSubstTemplateTypeParmPackType(
6048 cast<TemplateTypeParmType>(Parm),
6049 ArgPack);
6050 }
6051
6052 case TYPE_INJECTED_CLASS_NAME: {
6053 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6054 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6055 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6056 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006057 const Type *T = nullptr;
6058 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6059 if (const Type *Existing = DI->getTypeForDecl()) {
6060 T = Existing;
6061 break;
6062 }
6063 }
6064 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006065 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006066 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6067 DI->setTypeForDecl(T);
6068 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006069 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 }
6071
6072 case TYPE_TEMPLATE_TYPE_PARM: {
6073 unsigned Idx = 0;
6074 unsigned Depth = Record[Idx++];
6075 unsigned Index = Record[Idx++];
6076 bool Pack = Record[Idx++];
6077 TemplateTypeParmDecl *D
6078 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6079 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6080 }
6081
6082 case TYPE_DEPENDENT_NAME: {
6083 unsigned Idx = 0;
6084 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6085 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006086 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 QualType Canon = readType(*Loc.F, Record, Idx);
6088 if (!Canon.isNull())
6089 Canon = Context.getCanonicalType(Canon);
6090 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6091 }
6092
6093 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6094 unsigned Idx = 0;
6095 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6096 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006097 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 unsigned NumArgs = Record[Idx++];
6099 SmallVector<TemplateArgument, 8> Args;
6100 Args.reserve(NumArgs);
6101 while (NumArgs--)
6102 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6103 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006104 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 }
6106
6107 case TYPE_DEPENDENT_SIZED_ARRAY: {
6108 unsigned Idx = 0;
6109
6110 // ArrayType
6111 QualType ElementType = readType(*Loc.F, Record, Idx);
6112 ArrayType::ArraySizeModifier ASM
6113 = (ArrayType::ArraySizeModifier)Record[Idx++];
6114 unsigned IndexTypeQuals = Record[Idx++];
6115
6116 // DependentSizedArrayType
6117 Expr *NumElts = ReadExpr(*Loc.F);
6118 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6119
6120 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6121 IndexTypeQuals, Brackets);
6122 }
6123
6124 case TYPE_TEMPLATE_SPECIALIZATION: {
6125 unsigned Idx = 0;
6126 bool IsDependent = Record[Idx++];
6127 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6128 SmallVector<TemplateArgument, 8> Args;
6129 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6130 QualType Underlying = readType(*Loc.F, Record, Idx);
6131 QualType T;
6132 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006133 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006135 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6137 return T;
6138 }
6139
6140 case TYPE_ATOMIC: {
6141 if (Record.size() != 1) {
6142 Error("Incorrect encoding of atomic type");
6143 return QualType();
6144 }
6145 QualType ValueType = readType(*Loc.F, Record, Idx);
6146 return Context.getAtomicType(ValueType);
6147 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006148
Joey Goulye3c85de2016-12-01 11:30:49 +00006149 case TYPE_PIPE: {
6150 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006151 Error("Incorrect encoding of pipe type");
6152 return QualType();
6153 }
6154
6155 // Reading the pipe element type.
6156 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006157 unsigned ReadOnly = Record[1];
6158 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006159 }
6160
Alex Lorenz00aee432017-03-22 10:04:48 +00006161 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6162 unsigned Idx = 0;
6163
6164 // DependentSizedExtVectorType
6165 QualType ElementType = readType(*Loc.F, Record, Idx);
6166 Expr *SizeExpr = ReadExpr(*Loc.F);
6167 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6168
6169 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6170 AttrLoc);
6171 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 }
6173 llvm_unreachable("Invalid TypeCode!");
6174}
6175
Richard Smith564417a2014-03-20 21:47:22 +00006176void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6177 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006178 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006179 const RecordData &Record, unsigned &Idx) {
6180 ExceptionSpecificationType EST =
6181 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006182 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006183 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006184 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006185 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006186 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006187 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006188 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006189 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006190 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6191 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006192 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006193 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006194 }
6195}
6196
Guy Benyei11169dd2012-12-18 14:30:41 +00006197class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006198 ModuleFile *F;
6199 ASTReader *Reader;
6200 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006201 unsigned &Idx;
6202
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006203 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006204 return Reader->ReadSourceLocation(*F, Record, Idx);
6205 }
6206
6207 TypeSourceInfo *GetTypeSourceInfo() {
6208 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6209 }
6210
6211 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6212 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 }
6214
Guy Benyei11169dd2012-12-18 14:30:41 +00006215public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006216 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006218 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006219
6220 // We want compile-time assurance that we've enumerated all of
6221 // these, so unfortunately we have to declare them first, then
6222 // define them out-of-line.
6223#define ABSTRACT_TYPELOC(CLASS, PARENT)
6224#define TYPELOC(CLASS, PARENT) \
6225 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6226#include "clang/AST/TypeLocNodes.def"
6227
6228 void VisitFunctionTypeLoc(FunctionTypeLoc);
6229 void VisitArrayTypeLoc(ArrayTypeLoc);
6230};
6231
6232void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6233 // nothing to do
6234}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006235
Guy Benyei11169dd2012-12-18 14:30:41 +00006236void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006237 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006239 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6240 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6241 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6242 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 }
6244}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006245
Guy Benyei11169dd2012-12-18 14:30:41 +00006246void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006247 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006248}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006249
Guy Benyei11169dd2012-12-18 14:30:41 +00006250void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006251 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006252}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006253
Reid Kleckner8a365022013-06-24 17:51:48 +00006254void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6255 // nothing to do
6256}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006257
Reid Kleckner0503a872013-12-05 01:23:43 +00006258void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6259 // nothing to do
6260}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006261
Guy Benyei11169dd2012-12-18 14:30:41 +00006262void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006263 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006264}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006265
Guy Benyei11169dd2012-12-18 14:30:41 +00006266void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006267 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006268}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006269
Guy Benyei11169dd2012-12-18 14:30:41 +00006270void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006271 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006272}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006273
Guy Benyei11169dd2012-12-18 14:30:41 +00006274void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006275 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006276 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006277}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006278
Guy Benyei11169dd2012-12-18 14:30:41 +00006279void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006280 TL.setLBracketLoc(ReadSourceLocation());
6281 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006282 if (Record[Idx++])
6283 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 else
Craig Toppera13603a2014-05-22 05:54:18 +00006285 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006286}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006287
Guy Benyei11169dd2012-12-18 14:30:41 +00006288void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6289 VisitArrayTypeLoc(TL);
6290}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006291
Guy Benyei11169dd2012-12-18 14:30:41 +00006292void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6293 VisitArrayTypeLoc(TL);
6294}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006295
Guy Benyei11169dd2012-12-18 14:30:41 +00006296void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6297 VisitArrayTypeLoc(TL);
6298}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006299
Guy Benyei11169dd2012-12-18 14:30:41 +00006300void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6301 DependentSizedArrayTypeLoc TL) {
6302 VisitArrayTypeLoc(TL);
6303}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006304
Guy Benyei11169dd2012-12-18 14:30:41 +00006305void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6306 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006307 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006308}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006309
Guy Benyei11169dd2012-12-18 14:30:41 +00006310void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006311 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006312}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006313
Guy Benyei11169dd2012-12-18 14:30:41 +00006314void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006315 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006316}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006317
Guy Benyei11169dd2012-12-18 14:30:41 +00006318void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006319 TL.setLocalRangeBegin(ReadSourceLocation());
6320 TL.setLParenLoc(ReadSourceLocation());
6321 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006322 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6323 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006324 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006325 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006326 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 }
6328}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006329
Guy Benyei11169dd2012-12-18 14:30:41 +00006330void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6331 VisitFunctionTypeLoc(TL);
6332}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006333
Guy Benyei11169dd2012-12-18 14:30:41 +00006334void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6335 VisitFunctionTypeLoc(TL);
6336}
6337void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006338 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006339}
6340void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006341 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006342}
6343void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006344 TL.setTypeofLoc(ReadSourceLocation());
6345 TL.setLParenLoc(ReadSourceLocation());
6346 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006347}
6348void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006349 TL.setTypeofLoc(ReadSourceLocation());
6350 TL.setLParenLoc(ReadSourceLocation());
6351 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006352 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006353}
6354void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006355 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006356}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006357
Guy Benyei11169dd2012-12-18 14:30:41 +00006358void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006359 TL.setKWLoc(ReadSourceLocation());
6360 TL.setLParenLoc(ReadSourceLocation());
6361 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006362 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006363}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006364
Guy Benyei11169dd2012-12-18 14:30:41 +00006365void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006366 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006367}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006368
Richard Smith600b5262017-01-26 20:40:47 +00006369void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6370 DeducedTemplateSpecializationTypeLoc TL) {
6371 TL.setTemplateNameLoc(ReadSourceLocation());
6372}
6373
Guy Benyei11169dd2012-12-18 14:30:41 +00006374void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006375 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006376}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006377
Guy Benyei11169dd2012-12-18 14:30:41 +00006378void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006379 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006380}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006381
Guy Benyei11169dd2012-12-18 14:30:41 +00006382void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006383 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 if (TL.hasAttrOperand()) {
6385 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006386 range.setBegin(ReadSourceLocation());
6387 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 TL.setAttrOperandParensRange(range);
6389 }
6390 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006391 if (Record[Idx++])
6392 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 else
Craig Toppera13603a2014-05-22 05:54:18 +00006394 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006396 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006397}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006398
Guy Benyei11169dd2012-12-18 14:30:41 +00006399void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006400 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006401}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006402
Guy Benyei11169dd2012-12-18 14:30:41 +00006403void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6404 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006405 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006406}
6407void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6408 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006409 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006410}
6411void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6412 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006413 TL.setTemplateKeywordLoc(ReadSourceLocation());
6414 TL.setTemplateNameLoc(ReadSourceLocation());
6415 TL.setLAngleLoc(ReadSourceLocation());
6416 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006418 TL.setArgLocInfo(
6419 i,
6420 Reader->GetTemplateArgumentLocInfo(
6421 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006422}
6423void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006424 TL.setLParenLoc(ReadSourceLocation());
6425 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006426}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006427
Guy Benyei11169dd2012-12-18 14:30:41 +00006428void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006429 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006430 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006431}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006432
Guy Benyei11169dd2012-12-18 14:30:41 +00006433void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006434 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006435}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006436
Guy Benyei11169dd2012-12-18 14:30:41 +00006437void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006438 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006439 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006440 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006441}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006442
Guy Benyei11169dd2012-12-18 14:30:41 +00006443void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6444 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006445 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006446 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006447 TL.setTemplateKeywordLoc(ReadSourceLocation());
6448 TL.setTemplateNameLoc(ReadSourceLocation());
6449 TL.setLAngleLoc(ReadSourceLocation());
6450 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006452 TL.setArgLocInfo(
6453 I,
6454 Reader->GetTemplateArgumentLocInfo(
6455 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006456}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006459 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006460}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006461
Guy Benyei11169dd2012-12-18 14:30:41 +00006462void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006463 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006464}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006465
Manman Rene6be26c2016-09-13 17:25:08 +00006466void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6467 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006468 TL.setProtocolLAngleLoc(ReadSourceLocation());
6469 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006470 }
6471 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006472 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006473}
6474
Guy Benyei11169dd2012-12-18 14:30:41 +00006475void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006476 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006477 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6478 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006479 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006480 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006481 TL.setProtocolLAngleLoc(ReadSourceLocation());
6482 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006484 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006485}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006486
Guy Benyei11169dd2012-12-18 14:30:41 +00006487void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006488 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006489}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006490
Guy Benyei11169dd2012-12-18 14:30:41 +00006491void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006492 TL.setKWLoc(ReadSourceLocation());
6493 TL.setLParenLoc(ReadSourceLocation());
6494 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006495}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006496
Xiuli Pan9c14e282016-01-09 12:53:17 +00006497void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006498 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006499}
Guy Benyei11169dd2012-12-18 14:30:41 +00006500
David L. Jonesbe1557a2016-12-21 00:17:49 +00006501TypeSourceInfo *
6502ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6503 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006504 QualType InfoTy = readType(F, Record, Idx);
6505 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006506 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006507
6508 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006509 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006510 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6511 TLR.Visit(TL);
6512 return TInfo;
6513}
6514
6515QualType ASTReader::GetType(TypeID ID) {
6516 unsigned FastQuals = ID & Qualifiers::FastMask;
6517 unsigned Index = ID >> Qualifiers::FastWidth;
6518
6519 if (Index < NUM_PREDEF_TYPE_IDS) {
6520 QualType T;
6521 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006522 case PREDEF_TYPE_NULL_ID:
6523 return QualType();
6524 case PREDEF_TYPE_VOID_ID:
6525 T = Context.VoidTy;
6526 break;
6527 case PREDEF_TYPE_BOOL_ID:
6528 T = Context.BoolTy;
6529 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006530
6531 case PREDEF_TYPE_CHAR_U_ID:
6532 case PREDEF_TYPE_CHAR_S_ID:
6533 // FIXME: Check that the signedness of CharTy is correct!
6534 T = Context.CharTy;
6535 break;
6536
Alexey Baderbdf7c842015-09-15 12:18:29 +00006537 case PREDEF_TYPE_UCHAR_ID:
6538 T = Context.UnsignedCharTy;
6539 break;
6540 case PREDEF_TYPE_USHORT_ID:
6541 T = Context.UnsignedShortTy;
6542 break;
6543 case PREDEF_TYPE_UINT_ID:
6544 T = Context.UnsignedIntTy;
6545 break;
6546 case PREDEF_TYPE_ULONG_ID:
6547 T = Context.UnsignedLongTy;
6548 break;
6549 case PREDEF_TYPE_ULONGLONG_ID:
6550 T = Context.UnsignedLongLongTy;
6551 break;
6552 case PREDEF_TYPE_UINT128_ID:
6553 T = Context.UnsignedInt128Ty;
6554 break;
6555 case PREDEF_TYPE_SCHAR_ID:
6556 T = Context.SignedCharTy;
6557 break;
6558 case PREDEF_TYPE_WCHAR_ID:
6559 T = Context.WCharTy;
6560 break;
6561 case PREDEF_TYPE_SHORT_ID:
6562 T = Context.ShortTy;
6563 break;
6564 case PREDEF_TYPE_INT_ID:
6565 T = Context.IntTy;
6566 break;
6567 case PREDEF_TYPE_LONG_ID:
6568 T = Context.LongTy;
6569 break;
6570 case PREDEF_TYPE_LONGLONG_ID:
6571 T = Context.LongLongTy;
6572 break;
6573 case PREDEF_TYPE_INT128_ID:
6574 T = Context.Int128Ty;
6575 break;
6576 case PREDEF_TYPE_HALF_ID:
6577 T = Context.HalfTy;
6578 break;
6579 case PREDEF_TYPE_FLOAT_ID:
6580 T = Context.FloatTy;
6581 break;
6582 case PREDEF_TYPE_DOUBLE_ID:
6583 T = Context.DoubleTy;
6584 break;
6585 case PREDEF_TYPE_LONGDOUBLE_ID:
6586 T = Context.LongDoubleTy;
6587 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006588 case PREDEF_TYPE_FLOAT128_ID:
6589 T = Context.Float128Ty;
6590 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006591 case PREDEF_TYPE_OVERLOAD_ID:
6592 T = Context.OverloadTy;
6593 break;
6594 case PREDEF_TYPE_BOUND_MEMBER:
6595 T = Context.BoundMemberTy;
6596 break;
6597 case PREDEF_TYPE_PSEUDO_OBJECT:
6598 T = Context.PseudoObjectTy;
6599 break;
6600 case PREDEF_TYPE_DEPENDENT_ID:
6601 T = Context.DependentTy;
6602 break;
6603 case PREDEF_TYPE_UNKNOWN_ANY:
6604 T = Context.UnknownAnyTy;
6605 break;
6606 case PREDEF_TYPE_NULLPTR_ID:
6607 T = Context.NullPtrTy;
6608 break;
6609 case PREDEF_TYPE_CHAR16_ID:
6610 T = Context.Char16Ty;
6611 break;
6612 case PREDEF_TYPE_CHAR32_ID:
6613 T = Context.Char32Ty;
6614 break;
6615 case PREDEF_TYPE_OBJC_ID:
6616 T = Context.ObjCBuiltinIdTy;
6617 break;
6618 case PREDEF_TYPE_OBJC_CLASS:
6619 T = Context.ObjCBuiltinClassTy;
6620 break;
6621 case PREDEF_TYPE_OBJC_SEL:
6622 T = Context.ObjCBuiltinSelTy;
6623 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006624#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6625 case PREDEF_TYPE_##Id##_ID: \
6626 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006627 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006628#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006629 case PREDEF_TYPE_SAMPLER_ID:
6630 T = Context.OCLSamplerTy;
6631 break;
6632 case PREDEF_TYPE_EVENT_ID:
6633 T = Context.OCLEventTy;
6634 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006635 case PREDEF_TYPE_CLK_EVENT_ID:
6636 T = Context.OCLClkEventTy;
6637 break;
6638 case PREDEF_TYPE_QUEUE_ID:
6639 T = Context.OCLQueueTy;
6640 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006641 case PREDEF_TYPE_RESERVE_ID_ID:
6642 T = Context.OCLReserveIDTy;
6643 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006644 case PREDEF_TYPE_AUTO_DEDUCT:
6645 T = Context.getAutoDeductType();
6646 break;
6647
6648 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6649 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 break;
6651
6652 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6653 T = Context.ARCUnbridgedCastTy;
6654 break;
6655
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 case PREDEF_TYPE_BUILTIN_FN:
6657 T = Context.BuiltinFnTy;
6658 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006659
6660 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6661 T = Context.OMPArraySectionTy;
6662 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 }
6664
6665 assert(!T.isNull() && "Unknown predefined type");
6666 return T.withFastQualifiers(FastQuals);
6667 }
6668
6669 Index -= NUM_PREDEF_TYPE_IDS;
6670 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6671 if (TypesLoaded[Index].isNull()) {
6672 TypesLoaded[Index] = readTypeRecord(Index);
6673 if (TypesLoaded[Index].isNull())
6674 return QualType();
6675
6676 TypesLoaded[Index]->setFromAST();
6677 if (DeserializationListener)
6678 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6679 TypesLoaded[Index]);
6680 }
6681
6682 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6683}
6684
6685QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6686 return GetType(getGlobalTypeID(F, LocalID));
6687}
6688
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006689serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006690ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6691 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6692 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006693
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6695 return LocalID;
6696
Richard Smith37a93df2017-02-18 00:32:02 +00006697 if (!F.ModuleOffsetMap.empty())
6698 ReadModuleOffsetMap(F);
6699
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6701 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6702 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006703
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 unsigned GlobalIndex = LocalIndex + I->second;
6705 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6706}
6707
6708TemplateArgumentLocInfo
6709ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6710 TemplateArgument::ArgKind Kind,
6711 const RecordData &Record,
6712 unsigned &Index) {
6713 switch (Kind) {
6714 case TemplateArgument::Expression:
6715 return ReadExpr(F);
6716 case TemplateArgument::Type:
6717 return GetTypeSourceInfo(F, Record, Index);
6718 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006719 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 Index);
6721 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6722 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6723 SourceLocation());
6724 }
6725 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006726 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 Index);
6728 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6729 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006730 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 EllipsisLoc);
6732 }
6733 case TemplateArgument::Null:
6734 case TemplateArgument::Integral:
6735 case TemplateArgument::Declaration:
6736 case TemplateArgument::NullPtr:
6737 case TemplateArgument::Pack:
6738 // FIXME: Is this right?
6739 return TemplateArgumentLocInfo();
6740 }
6741 llvm_unreachable("unexpected template argument loc");
6742}
6743
6744TemplateArgumentLoc
6745ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6746 const RecordData &Record, unsigned &Index) {
6747 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6748
6749 if (Arg.getKind() == TemplateArgument::Expression) {
6750 if (Record[Index++]) // bool InfoHasSameExpr.
6751 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6752 }
6753 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6754 Record, Index));
6755}
6756
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006757const ASTTemplateArgumentListInfo*
6758ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6759 const RecordData &Record,
6760 unsigned &Index) {
6761 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6762 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6763 unsigned NumArgsAsWritten = Record[Index++];
6764 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6765 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6766 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6767 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6768}
6769
Guy Benyei11169dd2012-12-18 14:30:41 +00006770Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6771 return GetDecl(ID);
6772}
6773
Richard Smith053f6c62014-05-16 23:01:30 +00006774void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006775 if (NumCurrentElementsDeserializing) {
6776 // We arrange to not care about the complete redeclaration chain while we're
6777 // deserializing. Just remember that the AST has marked this one as complete
6778 // but that it's not actually complete yet, so we know we still need to
6779 // complete it later.
6780 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6781 return;
6782 }
6783
Richard Smith053f6c62014-05-16 23:01:30 +00006784 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6785
Richard Smith053f6c62014-05-16 23:01:30 +00006786 // If this is a named declaration, complete it by looking it up
6787 // within its context.
6788 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006789 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006790 // all mergeable entities within it.
6791 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6792 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6793 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006794 if (!getContext().getLangOpts().CPlusPlus &&
6795 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006796 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006797 // the identifier instead. (For C++ modules, we don't store decls
6798 // in the serialized identifier table, so we do the lookup in the TU.)
6799 auto *II = Name.getAsIdentifierInfo();
6800 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006801 if (II->isOutOfDate())
6802 updateOutOfDateIdentifier(*II);
6803 } else
6804 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006805 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006806 // Find all declarations of this kind from the relevant context.
6807 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6808 auto *DC = cast<DeclContext>(DCDecl);
6809 SmallVector<Decl*, 8> Decls;
6810 FindExternalLexicalDecls(
6811 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6812 }
Richard Smith053f6c62014-05-16 23:01:30 +00006813 }
6814 }
Richard Smith50895422015-01-31 03:04:55 +00006815
6816 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6817 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6818 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6819 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6820 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6821 if (auto *Template = FD->getPrimaryTemplate())
6822 Template->LoadLazySpecializations();
6823 }
Richard Smith053f6c62014-05-16 23:01:30 +00006824}
6825
Richard Smithc2bb8182015-03-24 06:36:48 +00006826CXXCtorInitializer **
6827ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6828 RecordLocation Loc = getLocalBitOffset(Offset);
6829 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6830 SavedStreamPosition SavedPosition(Cursor);
6831 Cursor.JumpToBit(Loc.Offset);
6832 ReadingKindTracker ReadingKind(Read_Decl, *this);
6833
6834 RecordData Record;
6835 unsigned Code = Cursor.ReadCode();
6836 unsigned RecCode = Cursor.readRecord(Code, Record);
6837 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6838 Error("malformed AST file: missing C++ ctor initializers");
6839 return nullptr;
6840 }
6841
6842 unsigned Idx = 0;
6843 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6844}
6845
Guy Benyei11169dd2012-12-18 14:30:41 +00006846CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6847 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006848 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006849 SavedStreamPosition SavedPosition(Cursor);
6850 Cursor.JumpToBit(Loc.Offset);
6851 ReadingKindTracker ReadingKind(Read_Decl, *this);
6852 RecordData Record;
6853 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006854 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006856 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006857 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 }
6859
6860 unsigned Idx = 0;
6861 unsigned NumBases = Record[Idx++];
6862 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6863 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6864 for (unsigned I = 0; I != NumBases; ++I)
6865 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6866 return Bases;
6867}
6868
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006869serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006870ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6871 if (LocalID < NUM_PREDEF_DECL_IDS)
6872 return LocalID;
6873
Richard Smith37a93df2017-02-18 00:32:02 +00006874 if (!F.ModuleOffsetMap.empty())
6875 ReadModuleOffsetMap(F);
6876
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6878 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6879 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006880
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 return LocalID + I->second;
6882}
6883
6884bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6885 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006886 // Predefined decls aren't from any module.
6887 if (ID < NUM_PREDEF_DECL_IDS)
6888 return false;
6889
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006890 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006891 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006892}
6893
Douglas Gregor9f782892013-01-21 15:25:38 +00006894ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006896 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006897 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6898 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6899 return I->second;
6900}
6901
6902SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6903 if (ID < NUM_PREDEF_DECL_IDS)
6904 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006905
Guy Benyei11169dd2012-12-18 14:30:41 +00006906 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6907
6908 if (Index > DeclsLoaded.size()) {
6909 Error("declaration ID out-of-range for AST file");
6910 return SourceLocation();
6911 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006912
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 if (Decl *D = DeclsLoaded[Index])
6914 return D->getLocation();
6915
Richard Smithcb34bd32016-03-27 07:28:06 +00006916 SourceLocation Loc;
6917 DeclCursorForID(ID, Loc);
6918 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006919}
6920
Richard Smithfe620d22015-03-05 23:24:12 +00006921static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6922 switch (ID) {
6923 case PREDEF_DECL_NULL_ID:
6924 return nullptr;
6925
6926 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6927 return Context.getTranslationUnitDecl();
6928
6929 case PREDEF_DECL_OBJC_ID_ID:
6930 return Context.getObjCIdDecl();
6931
6932 case PREDEF_DECL_OBJC_SEL_ID:
6933 return Context.getObjCSelDecl();
6934
6935 case PREDEF_DECL_OBJC_CLASS_ID:
6936 return Context.getObjCClassDecl();
6937
6938 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6939 return Context.getObjCProtocolDecl();
6940
6941 case PREDEF_DECL_INT_128_ID:
6942 return Context.getInt128Decl();
6943
6944 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6945 return Context.getUInt128Decl();
6946
6947 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6948 return Context.getObjCInstanceTypeDecl();
6949
6950 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6951 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006952
Richard Smith9b88a4c2015-07-27 05:40:23 +00006953 case PREDEF_DECL_VA_LIST_TAG:
6954 return Context.getVaListTagDecl();
6955
Charles Davisc7d5c942015-09-17 20:55:33 +00006956 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6957 return Context.getBuiltinMSVaListDecl();
6958
Richard Smithf19e1272015-03-07 00:04:49 +00006959 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6960 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006961
6962 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6963 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006964
6965 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6966 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006967
6968 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6969 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006970
6971 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6972 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006973 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006974 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006975}
6976
Richard Smithcd45dbc2014-04-19 03:48:30 +00006977Decl *ASTReader::GetExistingDecl(DeclID ID) {
6978 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006979 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6980 if (D) {
6981 // Track that we have merged the declaration with ID \p ID into the
6982 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006983 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006984 if (Merged.empty())
6985 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 }
Richard Smithfe620d22015-03-05 23:24:12 +00006987 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006989
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6991
6992 if (Index >= DeclsLoaded.size()) {
6993 assert(0 && "declaration ID out-of-range for AST file");
6994 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006995 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006997
6998 return DeclsLoaded[Index];
6999}
7000
7001Decl *ASTReader::GetDecl(DeclID ID) {
7002 if (ID < NUM_PREDEF_DECL_IDS)
7003 return GetExistingDecl(ID);
7004
7005 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7006
7007 if (Index >= DeclsLoaded.size()) {
7008 assert(0 && "declaration ID out-of-range for AST file");
7009 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007010 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007011 }
7012
Guy Benyei11169dd2012-12-18 14:30:41 +00007013 if (!DeclsLoaded[Index]) {
7014 ReadDeclRecord(ID);
7015 if (DeserializationListener)
7016 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7017 }
7018
7019 return DeclsLoaded[Index];
7020}
7021
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007022DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 DeclID GlobalID) {
7024 if (GlobalID < NUM_PREDEF_DECL_IDS)
7025 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007026
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7028 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7029 ModuleFile *Owner = I->second;
7030
7031 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7032 = M.GlobalToLocalDeclIDs.find(Owner);
7033 if (Pos == M.GlobalToLocalDeclIDs.end())
7034 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 return GlobalID - Owner->BaseDeclID + Pos->second;
7037}
7038
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007039serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 const RecordData &Record,
7041 unsigned &Idx) {
7042 if (Idx >= Record.size()) {
7043 Error("Corrupted AST file");
7044 return 0;
7045 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007046
Guy Benyei11169dd2012-12-18 14:30:41 +00007047 return getGlobalDeclID(F, Record[Idx++]);
7048}
7049
7050/// \brief Resolve the offset of a statement into a statement.
7051///
7052/// This operation will read a new statement from the external
7053/// source each time it is called, and is meant to be used via a
7054/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7055Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7056 // Switch case IDs are per Decl.
7057 ClearSwitchCaseIDs();
7058
7059 // Offset here is a global offset across the entire chain.
7060 RecordLocation Loc = getLocalBitOffset(Offset);
7061 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007062 assert(NumCurrentElementsDeserializing == 0 &&
7063 "should not be called while already deserializing");
7064 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 return ReadStmtFromStream(*Loc.F);
7066}
7067
Richard Smith3cb15722015-08-05 22:41:45 +00007068void ASTReader::FindExternalLexicalDecls(
7069 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7070 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007071 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7072
Richard Smith9ccdd932015-08-06 22:14:12 +00007073 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007074 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7075 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7076 auto K = (Decl::Kind)+LexicalDecls[I];
7077 if (!IsKindWeWant(K))
7078 continue;
7079
7080 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7081
7082 // Don't add predefined declarations to the lexical context more
7083 // than once.
7084 if (ID < NUM_PREDEF_DECL_IDS) {
7085 if (PredefsVisited[ID])
7086 continue;
7087
7088 PredefsVisited[ID] = true;
7089 }
7090
7091 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007092 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007093 if (!DC->isDeclInLexicalTraversal(D))
7094 Decls.push_back(D);
7095 }
7096 }
7097 };
7098
7099 if (isa<TranslationUnitDecl>(DC)) {
7100 for (auto Lexical : TULexicalDecls)
7101 Visit(Lexical.first, Lexical.second);
7102 } else {
7103 auto I = LexicalDecls.find(DC);
7104 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007105 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007106 }
7107
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007109}
7110
7111namespace {
7112
7113class DeclIDComp {
7114 ASTReader &Reader;
7115 ModuleFile &Mod;
7116
7117public:
7118 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7119
7120 bool operator()(LocalDeclID L, LocalDeclID R) const {
7121 SourceLocation LHS = getLocation(L);
7122 SourceLocation RHS = getLocation(R);
7123 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7124 }
7125
7126 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7127 SourceLocation RHS = getLocation(R);
7128 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7129 }
7130
7131 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7132 SourceLocation LHS = getLocation(L);
7133 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7134 }
7135
7136 SourceLocation getLocation(LocalDeclID ID) const {
7137 return Reader.getSourceManager().getFileLoc(
7138 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7139 }
7140};
7141
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007142} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007143
7144void ASTReader::FindFileRegionDecls(FileID File,
7145 unsigned Offset, unsigned Length,
7146 SmallVectorImpl<Decl *> &Decls) {
7147 SourceManager &SM = getSourceManager();
7148
7149 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7150 if (I == FileDeclIDs.end())
7151 return;
7152
7153 FileDeclsInfo &DInfo = I->second;
7154 if (DInfo.Decls.empty())
7155 return;
7156
7157 SourceLocation
7158 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7159 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7160
7161 DeclIDComp DIDComp(*this, *DInfo.Mod);
7162 ArrayRef<serialization::LocalDeclID>::iterator
7163 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7164 BeginLoc, DIDComp);
7165 if (BeginIt != DInfo.Decls.begin())
7166 --BeginIt;
7167
7168 // If we are pointing at a top-level decl inside an objc container, we need
7169 // to backtrack until we find it otherwise we will fail to report that the
7170 // region overlaps with an objc container.
7171 while (BeginIt != DInfo.Decls.begin() &&
7172 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7173 ->isTopLevelDeclInObjCContainer())
7174 --BeginIt;
7175
7176 ArrayRef<serialization::LocalDeclID>::iterator
7177 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7178 EndLoc, DIDComp);
7179 if (EndIt != DInfo.Decls.end())
7180 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007181
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 for (ArrayRef<serialization::LocalDeclID>::iterator
7183 DIt = BeginIt; DIt != EndIt; ++DIt)
7184 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7185}
7186
Richard Smith9ce12e32013-02-07 03:30:24 +00007187bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007188ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7189 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007190 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 "DeclContext has no visible decls in storage");
7192 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007193 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007194
Richard Smithd88a7f12015-09-01 20:35:42 +00007195 auto It = Lookups.find(DC);
7196 if (It == Lookups.end())
7197 return false;
7198
Richard Smith8c913ec2014-08-14 02:21:01 +00007199 Deserializing LookupResults(this);
7200
Richard Smithd88a7f12015-09-01 20:35:42 +00007201 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007202 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007203 for (DeclID ID : It->second.Table.find(Name)) {
7204 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7205 if (ND->getDeclName() == Name)
7206 Decls.push_back(ND);
7207 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007208
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 ++NumVisibleDeclContextsRead;
7210 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007211 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007212}
7213
Guy Benyei11169dd2012-12-18 14:30:41 +00007214void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7215 if (!DC->hasExternalVisibleStorage())
7216 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007217
7218 auto It = Lookups.find(DC);
7219 assert(It != Lookups.end() &&
7220 "have external visible storage but no lookup tables");
7221
Craig Topper79be4cd2013-07-05 04:33:53 +00007222 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007223
Richard Smithd88a7f12015-09-01 20:35:42 +00007224 for (DeclID ID : It->second.Table.findAll()) {
7225 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7226 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 }
7228
Guy Benyei11169dd2012-12-18 14:30:41 +00007229 ++NumVisibleDeclContextsRead;
7230
Craig Topper79be4cd2013-07-05 04:33:53 +00007231 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7233 }
7234 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7235}
7236
Richard Smithd88a7f12015-09-01 20:35:42 +00007237const serialization::reader::DeclContextLookupTable *
7238ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7239 auto I = Lookups.find(Primary);
7240 return I == Lookups.end() ? nullptr : &I->second;
7241}
7242
Guy Benyei11169dd2012-12-18 14:30:41 +00007243/// \brief Under non-PCH compilation the consumer receives the objc methods
7244/// before receiving the implementation, and codegen depends on this.
7245/// We simulate this by deserializing and passing to consumer the methods of the
7246/// implementation before passing the deserialized implementation decl.
7247static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7248 ASTConsumer *Consumer) {
7249 assert(ImplD && Consumer);
7250
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007251 for (auto *I : ImplD->methods())
7252 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007253
7254 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7255}
7256
Guy Benyei11169dd2012-12-18 14:30:41 +00007257void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7258 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7259 PassObjCImplDeclToConsumer(ImplD, Consumer);
7260 else
7261 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7262}
7263
7264void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7265 this->Consumer = Consumer;
7266
Richard Smith9e2341d2015-03-23 03:25:59 +00007267 if (Consumer)
7268 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007269
7270 if (DeserializationListener)
7271 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007272}
7273
7274void ASTReader::PrintStats() {
7275 std::fprintf(stderr, "*** AST File Statistics:\n");
7276
7277 unsigned NumTypesLoaded
7278 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7279 QualType());
7280 unsigned NumDeclsLoaded
7281 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007282 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 unsigned NumIdentifiersLoaded
7284 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7285 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007286 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007287 unsigned NumMacrosLoaded
7288 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7289 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007290 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007291 unsigned NumSelectorsLoaded
7292 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7293 SelectorsLoaded.end(),
7294 Selector());
7295
7296 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7297 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7298 NumSLocEntriesRead, TotalNumSLocEntries,
7299 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7300 if (!TypesLoaded.empty())
7301 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7302 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7303 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7304 if (!DeclsLoaded.empty())
7305 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7306 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7307 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7308 if (!IdentifiersLoaded.empty())
7309 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7310 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7311 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7312 if (!MacrosLoaded.empty())
7313 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7314 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7315 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7316 if (!SelectorsLoaded.empty())
7317 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7318 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7319 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7320 if (TotalNumStatements)
7321 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7322 NumStatementsRead, TotalNumStatements,
7323 ((float)NumStatementsRead/TotalNumStatements * 100));
7324 if (TotalNumMacros)
7325 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7326 NumMacrosRead, TotalNumMacros,
7327 ((float)NumMacrosRead/TotalNumMacros * 100));
7328 if (TotalLexicalDeclContexts)
7329 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7330 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7331 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7332 * 100));
7333 if (TotalVisibleDeclContexts)
7334 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7335 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7336 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7337 * 100));
7338 if (TotalNumMethodPoolEntries) {
7339 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7340 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7341 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7342 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007344 if (NumMethodPoolLookups) {
7345 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7346 NumMethodPoolHits, NumMethodPoolLookups,
7347 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7348 }
7349 if (NumMethodPoolTableLookups) {
7350 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7351 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7352 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7353 * 100.0));
7354 }
7355
Douglas Gregor00a50f72013-01-25 00:38:33 +00007356 if (NumIdentifierLookupHits) {
7357 std::fprintf(stderr,
7358 " %u / %u identifier table lookups succeeded (%f%%)\n",
7359 NumIdentifierLookupHits, NumIdentifierLookups,
7360 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7361 }
7362
Douglas Gregore060e572013-01-25 01:03:03 +00007363 if (GlobalIndex) {
7364 std::fprintf(stderr, "\n");
7365 GlobalIndex->printStats();
7366 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007367
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 std::fprintf(stderr, "\n");
7369 dump();
7370 std::fprintf(stderr, "\n");
7371}
7372
7373template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007374LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007375dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007376 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 InitialCapacity> &Map) {
7378 if (Map.begin() == Map.end())
7379 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007380
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7382 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007383 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 I != IEnd; ++I) {
7385 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7386 << "\n";
7387 }
7388}
7389
Yaron Kerencdae9412016-01-29 19:38:18 +00007390LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007391 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7392 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7393 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7394 dumpModuleIDMap("Global type map", GlobalTypeMap);
7395 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7396 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7397 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7398 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7399 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007400 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007401 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007402
Guy Benyei11169dd2012-12-18 14:30:41 +00007403 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007404 for (ModuleFile &M : ModuleMgr)
7405 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007406}
7407
7408/// Return the amount of memory used by memory buffers, breaking down
7409/// by heap-backed versus mmap'ed memory.
7410void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007411 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007412 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 size_t bytes = buf->getBufferSize();
7414 switch (buf->getBufferKind()) {
7415 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7416 sizes.malloc_bytes += bytes;
7417 break;
7418 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7419 sizes.mmap_bytes += bytes;
7420 break;
7421 }
7422 }
7423 }
7424}
7425
7426void ASTReader::InitializeSema(Sema &S) {
7427 SemaObj = &S;
7428 S.addExternalSource(this);
7429
7430 // Makes sure any declarations that were deserialized "too early"
7431 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007432 for (uint64_t ID : PreloadedDeclIDs) {
7433 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7434 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007435 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007436 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007437
Richard Smith3d8e97e2013-10-18 06:54:39 +00007438 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 if (!FPPragmaOptions.empty()) {
7440 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007441 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 }
7443
Yaxun Liu5b746652016-12-18 05:18:55 +00007444 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7445 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7446 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007447
7448 UpdateSema();
7449}
7450
7451void ASTReader::UpdateSema() {
7452 assert(SemaObj && "no Sema to update");
7453
7454 // Load the offsets of the declarations that Sema references.
7455 // They will be lazily deserialized when needed.
7456 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007457 assert(SemaDeclRefs.size() % 3 == 0);
7458 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007459 if (!SemaObj->StdNamespace)
7460 SemaObj->StdNamespace = SemaDeclRefs[I];
7461 if (!SemaObj->StdBadAlloc)
7462 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007463 if (!SemaObj->StdAlignValT)
7464 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007465 }
7466 SemaDeclRefs.clear();
7467 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007468
Nico Weber779355f2016-03-02 23:22:00 +00007469 // Update the state of pragmas. Use the same API as if we had encountered the
7470 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007471 if(OptimizeOffPragmaLocation.isValid())
7472 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007473 if (PragmaMSStructState != -1)
7474 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007475 if (PointersToMembersPragmaLocation.isValid()) {
7476 SemaObj->ActOnPragmaMSPointersToMembers(
7477 (LangOptions::PragmaMSPointersToMembersKind)
7478 PragmaMSPointersToMembersState,
7479 PointersToMembersPragmaLocation);
7480 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007481 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007482
7483 if (PragmaPackCurrentValue) {
7484 // The bottom of the stack might have a default value. It must be adjusted
7485 // to the current value to ensure that the packing state is preserved after
7486 // popping entries that were included/imported from a PCH/module.
7487 bool DropFirst = false;
7488 if (!PragmaPackStack.empty() &&
7489 PragmaPackStack.front().Location.isInvalid()) {
7490 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7491 "Expected a default alignment value");
7492 SemaObj->PackStack.Stack.emplace_back(
7493 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7494 SemaObj->PackStack.CurrentPragmaLocation);
7495 DropFirst = true;
7496 }
7497 for (const auto &Entry :
7498 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7499 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7500 Entry.Location);
7501 if (PragmaPackCurrentLocation.isInvalid()) {
7502 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7503 "Expected a default alignment value");
7504 // Keep the current values.
7505 } else {
7506 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7507 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7508 }
7509 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007510}
7511
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007512IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 // Note that we are loading an identifier.
7514 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007515
Douglas Gregor7211ac12013-01-25 23:32:03 +00007516 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007517 NumIdentifierLookups,
7518 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007519
7520 // We don't need to do identifier table lookups in C++ modules (we preload
7521 // all interesting declarations, and don't need to use the scope for name
7522 // lookups). Perform the lookup in PCH files, though, since we don't build
7523 // a complete initial identifier table if we're carrying on from a PCH.
7524 if (Context.getLangOpts().CPlusPlus) {
7525 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007526 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007527 break;
7528 } else {
7529 // If there is a global index, look there first to determine which modules
7530 // provably do not have any results for this identifier.
7531 GlobalModuleIndex::HitSet Hits;
7532 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7533 if (!loadGlobalIndex()) {
7534 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7535 HitsPtr = &Hits;
7536 }
7537 }
7538
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007539 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007540 }
7541
Guy Benyei11169dd2012-12-18 14:30:41 +00007542 IdentifierInfo *II = Visitor.getIdentifierInfo();
7543 markIdentifierUpToDate(II);
7544 return II;
7545}
7546
7547namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007548
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 /// \brief An identifier-lookup iterator that enumerates all of the
7550 /// identifiers stored within a set of AST files.
7551 class ASTIdentifierIterator : public IdentifierIterator {
7552 /// \brief The AST reader whose identifiers are being enumerated.
7553 const ASTReader &Reader;
7554
7555 /// \brief The current index into the chain of AST files stored in
7556 /// the AST reader.
7557 unsigned Index;
7558
7559 /// \brief The current position within the identifier lookup table
7560 /// of the current AST file.
7561 ASTIdentifierLookupTable::key_iterator Current;
7562
7563 /// \brief The end position within the identifier lookup table of
7564 /// the current AST file.
7565 ASTIdentifierLookupTable::key_iterator End;
7566
Ben Langmuir537c5b52016-05-04 00:53:13 +00007567 /// \brief Whether to skip any modules in the ASTReader.
7568 bool SkipModules;
7569
Guy Benyei11169dd2012-12-18 14:30:41 +00007570 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007571 explicit ASTIdentifierIterator(const ASTReader &Reader,
7572 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007573
Craig Topper3e89dfe2014-03-13 02:13:41 +00007574 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007575 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007576
7577} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007578
Ben Langmuir537c5b52016-05-04 00:53:13 +00007579ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7580 bool SkipModules)
7581 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007582}
7583
7584StringRef ASTIdentifierIterator::Next() {
7585 while (Current == End) {
7586 // If we have exhausted all of our AST files, we're done.
7587 if (Index == 0)
7588 return StringRef();
7589
7590 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007591 ModuleFile &F = Reader.ModuleMgr[Index];
7592 if (SkipModules && F.isModule())
7593 continue;
7594
7595 ASTIdentifierLookupTable *IdTable =
7596 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 Current = IdTable->key_begin();
7598 End = IdTable->key_end();
7599 }
7600
7601 // We have any identifiers remaining in the current AST file; return
7602 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007603 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007605 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007606}
7607
Ben Langmuir537c5b52016-05-04 00:53:13 +00007608namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007609
Ben Langmuir537c5b52016-05-04 00:53:13 +00007610/// A utility for appending two IdentifierIterators.
7611class ChainedIdentifierIterator : public IdentifierIterator {
7612 std::unique_ptr<IdentifierIterator> Current;
7613 std::unique_ptr<IdentifierIterator> Queued;
7614
7615public:
7616 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7617 std::unique_ptr<IdentifierIterator> Second)
7618 : Current(std::move(First)), Queued(std::move(Second)) {}
7619
7620 StringRef Next() override {
7621 if (!Current)
7622 return StringRef();
7623
7624 StringRef result = Current->Next();
7625 if (!result.empty())
7626 return result;
7627
7628 // Try the queued iterator, which may itself be empty.
7629 Current.reset();
7630 std::swap(Current, Queued);
7631 return Next();
7632 }
7633};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007634
Ben Langmuir537c5b52016-05-04 00:53:13 +00007635} // end anonymous namespace.
7636
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007637IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007638 if (!loadGlobalIndex()) {
7639 std::unique_ptr<IdentifierIterator> ReaderIter(
7640 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7641 std::unique_ptr<IdentifierIterator> ModulesIter(
7642 GlobalIndex->createIdentifierIterator());
7643 return new ChainedIdentifierIterator(std::move(ReaderIter),
7644 std::move(ModulesIter));
7645 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007646
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 return new ASTIdentifierIterator(*this);
7648}
7649
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007650namespace clang {
7651namespace serialization {
7652
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 class ReadMethodPoolVisitor {
7654 ASTReader &Reader;
7655 Selector Sel;
7656 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007657 unsigned InstanceBits;
7658 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007659 bool InstanceHasMoreThanOneDecl;
7660 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007661 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7662 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007663
7664 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007665 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007667 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007668 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7669 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007670
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007671 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 if (!M.SelectorLookupTable)
7673 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007674
Guy Benyei11169dd2012-12-18 14:30:41 +00007675 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007676 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007677 return true;
7678
Richard Smithbdf2d932015-07-30 03:37:16 +00007679 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 ASTSelectorLookupTable *PoolTable
7681 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007682 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 if (Pos == PoolTable->end())
7684 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007685
Richard Smithbdf2d932015-07-30 03:37:16 +00007686 ++Reader.NumMethodPoolTableHits;
7687 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 // FIXME: Not quite happy with the statistics here. We probably should
7689 // disable this tracking when called via LoadSelector.
7690 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007691 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007693 if (Reader.DeserializationListener)
7694 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007695
Richard Smithbdf2d932015-07-30 03:37:16 +00007696 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7697 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7698 InstanceBits = Data.InstanceBits;
7699 FactoryBits = Data.FactoryBits;
7700 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7701 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007702 return true;
7703 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007704
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007706 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7707 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 }
7709
7710 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007711 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 return FactoryMethods;
7713 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007714
7715 unsigned getInstanceBits() const { return InstanceBits; }
7716 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007717 bool instanceHasMoreThanOneDecl() const {
7718 return InstanceHasMoreThanOneDecl;
7719 }
7720 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007722
7723} // end namespace serialization
7724} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007725
7726/// \brief Add the given set of methods to the method list.
7727static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7728 ObjCMethodList &List) {
7729 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7730 S.addMethodToGlobalList(&List, Methods[I]);
7731 }
7732}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007733
Guy Benyei11169dd2012-12-18 14:30:41 +00007734void ASTReader::ReadMethodPool(Selector Sel) {
7735 // Get the selector generation and update it to the current generation.
7736 unsigned &Generation = SelectorGeneration[Sel];
7737 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007738 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007739 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007740
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007742 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007744 ModuleMgr.visit(Visitor);
7745
Guy Benyei11169dd2012-12-18 14:30:41 +00007746 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007747 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007749
7750 ++NumMethodPoolHits;
7751
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 if (!getSema())
7753 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007754
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 Sema &S = *getSema();
7756 Sema::GlobalMethodPool::iterator Pos
7757 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007758
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007759 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007760 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007761 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007762 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007763
7764 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7765 // when building a module we keep every method individually and may need to
7766 // update hasMoreThanOneDecl as we add the methods.
7767 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7768 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007769}
7770
Manman Rena0f31a02016-04-29 19:04:05 +00007771void ASTReader::updateOutOfDateSelector(Selector Sel) {
7772 if (SelectorOutOfDate[Sel])
7773 ReadMethodPool(Sel);
7774}
7775
Guy Benyei11169dd2012-12-18 14:30:41 +00007776void ASTReader::ReadKnownNamespaces(
7777 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7778 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007779
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007781 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7783 Namespaces.push_back(Namespace);
7784 }
7785}
7786
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007787void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007788 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007789 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7790 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007791 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007792 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007793 Undefined.insert(std::make_pair(D, Loc));
7794 }
7795}
Nick Lewycky8334af82013-01-26 00:35:08 +00007796
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007797void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7798 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7799 Exprs) {
7800 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7801 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7802 uint64_t Count = DelayedDeleteExprs[Idx++];
7803 for (uint64_t C = 0; C < Count; ++C) {
7804 SourceLocation DeleteLoc =
7805 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7806 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7807 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7808 }
7809 }
7810}
7811
Guy Benyei11169dd2012-12-18 14:30:41 +00007812void ASTReader::ReadTentativeDefinitions(
7813 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7814 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7815 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7816 if (Var)
7817 TentativeDefs.push_back(Var);
7818 }
7819 TentativeDefinitions.clear();
7820}
7821
7822void ASTReader::ReadUnusedFileScopedDecls(
7823 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7824 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7825 DeclaratorDecl *D
7826 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7827 if (D)
7828 Decls.push_back(D);
7829 }
7830 UnusedFileScopedDecls.clear();
7831}
7832
7833void ASTReader::ReadDelegatingConstructors(
7834 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7835 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7836 CXXConstructorDecl *D
7837 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7838 if (D)
7839 Decls.push_back(D);
7840 }
7841 DelegatingCtorDecls.clear();
7842}
7843
7844void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7845 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7846 TypedefNameDecl *D
7847 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7848 if (D)
7849 Decls.push_back(D);
7850 }
7851 ExtVectorDecls.clear();
7852}
7853
Nico Weber72889432014-09-06 01:25:55 +00007854void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7855 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7856 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7857 ++I) {
7858 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7859 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7860 if (D)
7861 Decls.insert(D);
7862 }
7863 UnusedLocalTypedefNameCandidates.clear();
7864}
7865
Guy Benyei11169dd2012-12-18 14:30:41 +00007866void ASTReader::ReadReferencedSelectors(
7867 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7868 if (ReferencedSelectorsData.empty())
7869 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007870
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 // If there are @selector references added them to its pool. This is for
7872 // implementation of -Wselector.
7873 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7874 unsigned I = 0;
7875 while (I < DataSize) {
7876 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7877 SourceLocation SelLoc
7878 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7879 Sels.push_back(std::make_pair(Sel, SelLoc));
7880 }
7881 ReferencedSelectorsData.clear();
7882}
7883
7884void ASTReader::ReadWeakUndeclaredIdentifiers(
7885 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7886 if (WeakUndeclaredIdentifiers.empty())
7887 return;
7888
7889 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007890 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007892 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7894 SourceLocation Loc
7895 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7896 bool Used = WeakUndeclaredIdentifiers[I++];
7897 WeakInfo WI(AliasId, Loc);
7898 WI.setUsed(Used);
7899 WeakIDs.push_back(std::make_pair(WeakId, WI));
7900 }
7901 WeakUndeclaredIdentifiers.clear();
7902}
7903
7904void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7905 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7906 ExternalVTableUse VT;
7907 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7908 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7909 VT.DefinitionRequired = VTableUses[Idx++];
7910 VTables.push_back(VT);
7911 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007912
Guy Benyei11169dd2012-12-18 14:30:41 +00007913 VTableUses.clear();
7914}
7915
7916void ASTReader::ReadPendingInstantiations(
7917 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7918 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7919 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7920 SourceLocation Loc
7921 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7922
7923 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007925 PendingInstantiations.clear();
7926}
7927
Richard Smithe40f2ba2013-08-07 21:41:30 +00007928void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007929 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7930 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007931 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7932 /* In loop */) {
7933 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7934
Justin Lebar28f09c52016-10-10 16:26:08 +00007935 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007936 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7937
7938 ModuleFile *F = getOwningModuleFile(LT->D);
7939 assert(F && "No module");
7940
7941 unsigned TokN = LateParsedTemplates[Idx++];
7942 LT->Toks.reserve(TokN);
7943 for (unsigned T = 0; T < TokN; ++T)
7944 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7945
Justin Lebar28f09c52016-10-10 16:26:08 +00007946 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007947 }
7948
7949 LateParsedTemplates.clear();
7950}
7951
Guy Benyei11169dd2012-12-18 14:30:41 +00007952void ASTReader::LoadSelector(Selector Sel) {
7953 // It would be complicated to avoid reading the methods anyway. So don't.
7954 ReadMethodPool(Sel);
7955}
7956
7957void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7958 assert(ID && "Non-zero identifier ID required");
7959 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7960 IdentifiersLoaded[ID - 1] = II;
7961 if (DeserializationListener)
7962 DeserializationListener->IdentifierRead(ID, II);
7963}
7964
7965/// \brief Set the globally-visible declarations associated with the given
7966/// identifier.
7967///
7968/// If the AST reader is currently in a state where the given declaration IDs
7969/// cannot safely be resolved, they are queued until it is safe to resolve
7970/// them.
7971///
7972/// \param II an IdentifierInfo that refers to one or more globally-visible
7973/// declarations.
7974///
7975/// \param DeclIDs the set of declaration IDs with the name @p II that are
7976/// visible at global scope.
7977///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007978/// \param Decls if non-null, this vector will be populated with the set of
7979/// deserialized declarations. These declarations will not be pushed into
7980/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007981void
7982ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7983 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007984 SmallVectorImpl<Decl *> *Decls) {
7985 if (NumCurrentElementsDeserializing && !Decls) {
7986 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 return;
7988 }
7989
7990 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007991 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 // Queue this declaration so that it will be added to the
7993 // translation unit scope and identifier's declaration chain
7994 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007995 PreloadedDeclIDs.push_back(DeclIDs[I]);
7996 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007998
7999 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8000
8001 // If we're simply supposed to record the declarations, do so now.
8002 if (Decls) {
8003 Decls->push_back(D);
8004 continue;
8005 }
8006
8007 // Introduce this declaration into the translation-unit scope
8008 // and add it to the declaration chain for this identifier, so
8009 // that (unqualified) name lookup will find it.
8010 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 }
8012}
8013
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008014IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008016 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008017
8018 if (IdentifiersLoaded.empty()) {
8019 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008020 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 }
8022
8023 ID -= 1;
8024 if (!IdentifiersLoaded[ID]) {
8025 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8026 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8027 ModuleFile *M = I->second;
8028 unsigned Index = ID - M->BaseIdentifierID;
8029 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8030
8031 // All of the strings in the AST file are preceded by a 16-bit length.
8032 // Extract that 16-bit length to avoid having to execute strlen().
8033 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8034 // unsigned integers. This is important to avoid integer overflow when
8035 // we cast them to 'unsigned'.
8036 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8037 unsigned StrLen = (((unsigned) StrLenPtr[0])
8038 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008039 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8040 IdentifiersLoaded[ID] = &II;
8041 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008042 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008043 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 }
8045
8046 return IdentifiersLoaded[ID];
8047}
8048
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008049IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8050 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008051}
8052
8053IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8054 if (LocalID < NUM_PREDEF_IDENT_IDS)
8055 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008056
Richard Smith37a93df2017-02-18 00:32:02 +00008057 if (!M.ModuleOffsetMap.empty())
8058 ReadModuleOffsetMap(M);
8059
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8061 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008062 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008064
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 return LocalID + I->second;
8066}
8067
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008068MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008069 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008070 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008071
8072 if (MacrosLoaded.empty()) {
8073 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008074 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 }
8076
8077 ID -= NUM_PREDEF_MACRO_IDS;
8078 if (!MacrosLoaded[ID]) {
8079 GlobalMacroMapType::iterator I
8080 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8081 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8082 ModuleFile *M = I->second;
8083 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008084 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008085
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008086 if (DeserializationListener)
8087 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8088 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 }
8090
8091 return MacrosLoaded[ID];
8092}
8093
8094MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8095 if (LocalID < NUM_PREDEF_MACRO_IDS)
8096 return LocalID;
8097
Richard Smith37a93df2017-02-18 00:32:02 +00008098 if (!M.ModuleOffsetMap.empty())
8099 ReadModuleOffsetMap(M);
8100
Guy Benyei11169dd2012-12-18 14:30:41 +00008101 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8102 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8103 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8104
8105 return LocalID + I->second;
8106}
8107
8108serialization::SubmoduleID
8109ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8110 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8111 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008112
Richard Smith37a93df2017-02-18 00:32:02 +00008113 if (!M.ModuleOffsetMap.empty())
8114 ReadModuleOffsetMap(M);
8115
Guy Benyei11169dd2012-12-18 14:30:41 +00008116 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8117 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008118 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 return LocalID + I->second;
8122}
8123
8124Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8125 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8126 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008127 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 if (GlobalID > SubmodulesLoaded.size()) {
8131 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008132 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008134
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8136}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008137
8138Module *ASTReader::getModule(unsigned ID) {
8139 return getSubmodule(ID);
8140}
8141
Richard Smithd88a7f12015-09-01 20:35:42 +00008142ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8143 if (ID & 1) {
8144 // It's a module, look it up by submodule ID.
8145 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8146 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8147 } else {
8148 // It's a prefix (preamble, PCH, ...). Look it up by index.
8149 unsigned IndexFromEnd = ID >> 1;
8150 assert(IndexFromEnd && "got reference to unknown module file");
8151 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8152 }
8153}
8154
8155unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8156 if (!F)
8157 return 1;
8158
8159 // For a file representing a module, use the submodule ID of the top-level
8160 // module as the file ID. For any other kind of file, the number of such
8161 // files loaded beforehand will be the same on reload.
8162 // FIXME: Is this true even if we have an explicit module file and a PCH?
8163 if (F->isModule())
8164 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8165
8166 auto PCHModules = getModuleManager().pch_modules();
8167 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8168 assert(I != PCHModules.end() && "emitting reference to unknown file");
8169 return (I - PCHModules.end()) << 1;
8170}
8171
Adrian Prantl15bcf702015-06-30 17:39:43 +00008172llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8173ASTReader::getSourceDescriptor(unsigned ID) {
8174 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008175 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008176
8177 // If there is only a single PCH, return it instead.
8178 // Chained PCH are not suported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008179 const auto &PCHChain = ModuleMgr.pch_modules();
8180 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008181 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008182 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008183 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8184 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8185 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008186 }
8187 return None;
8188}
8189
David Blaikie1ac9c982017-04-11 21:13:37 +00008190ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
David Blaikiee6b7c282017-04-11 20:46:34 +00008191 auto I = BodySource.find(FD);
8192 if (I == BodySource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008193 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008194 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008195}
8196
Guy Benyei11169dd2012-12-18 14:30:41 +00008197Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8198 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8199}
8200
8201Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8202 if (ID == 0)
8203 return Selector();
8204
8205 if (ID > SelectorsLoaded.size()) {
8206 Error("selector ID out of range in AST file");
8207 return Selector();
8208 }
8209
Craig Toppera13603a2014-05-22 05:54:18 +00008210 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 // Load this selector from the selector table.
8212 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8213 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8214 ModuleFile &M = *I->second;
8215 ASTSelectorLookupTrait Trait(*this, M);
8216 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8217 SelectorsLoaded[ID - 1] =
8218 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8219 if (DeserializationListener)
8220 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8221 }
8222
8223 return SelectorsLoaded[ID - 1];
8224}
8225
8226Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8227 return DecodeSelector(ID);
8228}
8229
8230uint32_t ASTReader::GetNumExternalSelectors() {
8231 // ID 0 (the null selector) is considered an external selector.
8232 return getTotalNumSelectors() + 1;
8233}
8234
8235serialization::SelectorID
8236ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8237 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8238 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008239
Richard Smith37a93df2017-02-18 00:32:02 +00008240 if (!M.ModuleOffsetMap.empty())
8241 ReadModuleOffsetMap(M);
8242
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8244 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008245 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008247
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 return LocalID + I->second;
8249}
8250
8251DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008252ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 const RecordData &Record, unsigned &Idx) {
8254 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8255 switch (Kind) {
8256 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008257 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008258
8259 case DeclarationName::ObjCZeroArgSelector:
8260 case DeclarationName::ObjCOneArgSelector:
8261 case DeclarationName::ObjCMultiArgSelector:
8262 return DeclarationName(ReadSelector(F, Record, Idx));
8263
8264 case DeclarationName::CXXConstructorName:
8265 return Context.DeclarationNames.getCXXConstructorName(
8266 Context.getCanonicalType(readType(F, Record, Idx)));
8267
8268 case DeclarationName::CXXDestructorName:
8269 return Context.DeclarationNames.getCXXDestructorName(
8270 Context.getCanonicalType(readType(F, Record, Idx)));
8271
Richard Smith35845152017-02-07 01:37:30 +00008272 case DeclarationName::CXXDeductionGuideName:
8273 return Context.DeclarationNames.getCXXDeductionGuideName(
8274 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8275
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 case DeclarationName::CXXConversionFunctionName:
8277 return Context.DeclarationNames.getCXXConversionFunctionName(
8278 Context.getCanonicalType(readType(F, Record, Idx)));
8279
8280 case DeclarationName::CXXOperatorName:
8281 return Context.DeclarationNames.getCXXOperatorName(
8282 (OverloadedOperatorKind)Record[Idx++]);
8283
8284 case DeclarationName::CXXLiteralOperatorName:
8285 return Context.DeclarationNames.getCXXLiteralOperatorName(
8286 GetIdentifierInfo(F, Record, Idx));
8287
8288 case DeclarationName::CXXUsingDirective:
8289 return DeclarationName::getUsingDirectiveName();
8290 }
8291
8292 llvm_unreachable("Invalid NameKind!");
8293}
8294
8295void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8296 DeclarationNameLoc &DNLoc,
8297 DeclarationName Name,
8298 const RecordData &Record, unsigned &Idx) {
8299 switch (Name.getNameKind()) {
8300 case DeclarationName::CXXConstructorName:
8301 case DeclarationName::CXXDestructorName:
8302 case DeclarationName::CXXConversionFunctionName:
8303 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8304 break;
8305
8306 case DeclarationName::CXXOperatorName:
8307 DNLoc.CXXOperatorName.BeginOpNameLoc
8308 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8309 DNLoc.CXXOperatorName.EndOpNameLoc
8310 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8311 break;
8312
8313 case DeclarationName::CXXLiteralOperatorName:
8314 DNLoc.CXXLiteralOperatorName.OpNameLoc
8315 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8316 break;
8317
8318 case DeclarationName::Identifier:
8319 case DeclarationName::ObjCZeroArgSelector:
8320 case DeclarationName::ObjCOneArgSelector:
8321 case DeclarationName::ObjCMultiArgSelector:
8322 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008323 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 break;
8325 }
8326}
8327
8328void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8329 DeclarationNameInfo &NameInfo,
8330 const RecordData &Record, unsigned &Idx) {
8331 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8332 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8333 DeclarationNameLoc DNLoc;
8334 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8335 NameInfo.setInfo(DNLoc);
8336}
8337
8338void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8339 const RecordData &Record, unsigned &Idx) {
8340 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8341 unsigned NumTPLists = Record[Idx++];
8342 Info.NumTemplParamLists = NumTPLists;
8343 if (NumTPLists) {
8344 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008345 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8347 }
8348}
8349
8350TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008351ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008352 unsigned &Idx) {
8353 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8354 switch (Kind) {
8355 case TemplateName::Template:
8356 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8357
8358 case TemplateName::OverloadedTemplate: {
8359 unsigned size = Record[Idx++];
8360 UnresolvedSet<8> Decls;
8361 while (size--)
8362 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8363
8364 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8365 }
8366
8367 case TemplateName::QualifiedTemplate: {
8368 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8369 bool hasTemplKeyword = Record[Idx++];
8370 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8371 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8372 }
8373
8374 case TemplateName::DependentTemplate: {
8375 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8376 if (Record[Idx++]) // isIdentifier
8377 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008378 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 Idx));
8380 return Context.getDependentTemplateName(NNS,
8381 (OverloadedOperatorKind)Record[Idx++]);
8382 }
8383
8384 case TemplateName::SubstTemplateTemplateParm: {
8385 TemplateTemplateParmDecl *param
8386 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8387 if (!param) return TemplateName();
8388 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8389 return Context.getSubstTemplateTemplateParm(param, replacement);
8390 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008391
Guy Benyei11169dd2012-12-18 14:30:41 +00008392 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008393 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8395 if (!Param)
8396 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008397
Guy Benyei11169dd2012-12-18 14:30:41 +00008398 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8399 if (ArgPack.getKind() != TemplateArgument::Pack)
8400 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008401
Guy Benyei11169dd2012-12-18 14:30:41 +00008402 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8403 }
8404 }
8405
8406 llvm_unreachable("Unhandled template name kind!");
8407}
8408
Richard Smith2bb3c342015-08-09 01:05:31 +00008409TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8410 const RecordData &Record,
8411 unsigned &Idx,
8412 bool Canonicalize) {
8413 if (Canonicalize) {
8414 // The caller wants a canonical template argument. Sometimes the AST only
8415 // wants template arguments in canonical form (particularly as the template
8416 // argument lists of template specializations) so ensure we preserve that
8417 // canonical form across serialization.
8418 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8419 return Context.getCanonicalTemplateArgument(Arg);
8420 }
8421
Guy Benyei11169dd2012-12-18 14:30:41 +00008422 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8423 switch (Kind) {
8424 case TemplateArgument::Null:
8425 return TemplateArgument();
8426 case TemplateArgument::Type:
8427 return TemplateArgument(readType(F, Record, Idx));
8428 case TemplateArgument::Declaration: {
8429 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008430 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008431 }
8432 case TemplateArgument::NullPtr:
8433 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8434 case TemplateArgument::Integral: {
8435 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8436 QualType T = readType(F, Record, Idx);
8437 return TemplateArgument(Context, Value, T);
8438 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008439 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8441 case TemplateArgument::TemplateExpansion: {
8442 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008443 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008444 if (unsigned NumExpansions = Record[Idx++])
8445 NumTemplateExpansions = NumExpansions - 1;
8446 return TemplateArgument(Name, NumTemplateExpansions);
8447 }
8448 case TemplateArgument::Expression:
8449 return TemplateArgument(ReadExpr(F));
8450 case TemplateArgument::Pack: {
8451 unsigned NumArgs = Record[Idx++];
8452 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8453 for (unsigned I = 0; I != NumArgs; ++I)
8454 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008455 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 }
8457 }
8458
8459 llvm_unreachable("Unhandled template argument kind!");
8460}
8461
8462TemplateParameterList *
8463ASTReader::ReadTemplateParameterList(ModuleFile &F,
8464 const RecordData &Record, unsigned &Idx) {
8465 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8466 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8467 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8468
8469 unsigned NumParams = Record[Idx++];
8470 SmallVector<NamedDecl *, 16> Params;
8471 Params.reserve(NumParams);
8472 while (NumParams--)
8473 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8474
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008475 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 TemplateParameterList* TemplateParams =
8477 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008478 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008479 return TemplateParams;
8480}
8481
8482void
8483ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008484ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008485 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008486 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008487 unsigned NumTemplateArgs = Record[Idx++];
8488 TemplArgs.reserve(NumTemplateArgs);
8489 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008490 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008491}
8492
8493/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008494void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008495 const RecordData &Record, unsigned &Idx) {
8496 unsigned NumDecls = Record[Idx++];
8497 Set.reserve(Context, NumDecls);
8498 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008499 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008501 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 }
8503}
8504
8505CXXBaseSpecifier
8506ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8507 const RecordData &Record, unsigned &Idx) {
8508 bool isVirtual = static_cast<bool>(Record[Idx++]);
8509 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8510 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8511 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8512 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8513 SourceRange Range = ReadSourceRange(F, Record, Idx);
8514 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008515 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008516 EllipsisLoc);
8517 Result.setInheritConstructors(inheritConstructors);
8518 return Result;
8519}
8520
Richard Smithc2bb8182015-03-24 06:36:48 +00008521CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008522ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8523 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008525 assert(NumInitializers && "wrote ctor initializers but have no inits");
8526 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8527 for (unsigned i = 0; i != NumInitializers; ++i) {
8528 TypeSourceInfo *TInfo = nullptr;
8529 bool IsBaseVirtual = false;
8530 FieldDecl *Member = nullptr;
8531 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008532
Richard Smithc2bb8182015-03-24 06:36:48 +00008533 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8534 switch (Type) {
8535 case CTOR_INITIALIZER_BASE:
8536 TInfo = GetTypeSourceInfo(F, Record, Idx);
8537 IsBaseVirtual = Record[Idx++];
8538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008539
Richard Smithc2bb8182015-03-24 06:36:48 +00008540 case CTOR_INITIALIZER_DELEGATING:
8541 TInfo = GetTypeSourceInfo(F, Record, Idx);
8542 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008543
Richard Smithc2bb8182015-03-24 06:36:48 +00008544 case CTOR_INITIALIZER_MEMBER:
8545 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8546 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008547
Richard Smithc2bb8182015-03-24 06:36:48 +00008548 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8549 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8550 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008552
8553 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8554 Expr *Init = ReadExpr(F);
8555 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8556 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008557
8558 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008559 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008560 BOMInit = new (Context)
8561 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8562 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008563 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008564 BOMInit = new (Context)
8565 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008566 else if (Member)
8567 BOMInit = new (Context)
8568 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8569 Init, RParenLoc);
8570 else
8571 BOMInit = new (Context)
8572 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8573 LParenLoc, Init, RParenLoc);
8574
Richard Smith418ed822016-12-14 19:45:03 +00008575 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008576 unsigned SourceOrder = Record[Idx++];
8577 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008578 }
8579
Richard Smithc2bb8182015-03-24 06:36:48 +00008580 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008581 }
8582
Richard Smithc2bb8182015-03-24 06:36:48 +00008583 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008584}
8585
8586NestedNameSpecifier *
8587ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8588 const RecordData &Record, unsigned &Idx) {
8589 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008590 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 for (unsigned I = 0; I != N; ++I) {
8592 NestedNameSpecifier::SpecifierKind Kind
8593 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8594 switch (Kind) {
8595 case NestedNameSpecifier::Identifier: {
8596 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8597 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8598 break;
8599 }
8600
8601 case NestedNameSpecifier::Namespace: {
8602 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8603 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8604 break;
8605 }
8606
8607 case NestedNameSpecifier::NamespaceAlias: {
8608 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8609 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8610 break;
8611 }
8612
8613 case NestedNameSpecifier::TypeSpec:
8614 case NestedNameSpecifier::TypeSpecWithTemplate: {
8615 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8616 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008617 return nullptr;
8618
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 bool Template = Record[Idx++];
8620 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8621 break;
8622 }
8623
8624 case NestedNameSpecifier::Global: {
8625 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8626 // No associated value, and there can't be a prefix.
8627 break;
8628 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008629
8630 case NestedNameSpecifier::Super: {
8631 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8632 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8633 break;
8634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008635 }
8636 Prev = NNS;
8637 }
8638 return NNS;
8639}
8640
8641NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008642ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 unsigned &Idx) {
8644 unsigned N = Record[Idx++];
8645 NestedNameSpecifierLocBuilder Builder;
8646 for (unsigned I = 0; I != N; ++I) {
8647 NestedNameSpecifier::SpecifierKind Kind
8648 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8649 switch (Kind) {
8650 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008651 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008652 SourceRange Range = ReadSourceRange(F, Record, Idx);
8653 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8654 break;
8655 }
8656
8657 case NestedNameSpecifier::Namespace: {
8658 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8659 SourceRange Range = ReadSourceRange(F, Record, Idx);
8660 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8661 break;
8662 }
8663
8664 case NestedNameSpecifier::NamespaceAlias: {
8665 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8666 SourceRange Range = ReadSourceRange(F, Record, Idx);
8667 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8668 break;
8669 }
8670
8671 case NestedNameSpecifier::TypeSpec:
8672 case NestedNameSpecifier::TypeSpecWithTemplate: {
8673 bool Template = Record[Idx++];
8674 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8675 if (!T)
8676 return NestedNameSpecifierLoc();
8677 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8678
8679 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008680 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8682 T->getTypeLoc(), ColonColonLoc);
8683 break;
8684 }
8685
8686 case NestedNameSpecifier::Global: {
8687 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8688 Builder.MakeGlobal(Context, ColonColonLoc);
8689 break;
8690 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008691
8692 case NestedNameSpecifier::Super: {
8693 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8694 SourceRange Range = ReadSourceRange(F, Record, Idx);
8695 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8696 break;
8697 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008698 }
8699 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008700
Guy Benyei11169dd2012-12-18 14:30:41 +00008701 return Builder.getWithLocInContext(Context);
8702}
8703
8704SourceRange
8705ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8706 unsigned &Idx) {
8707 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8708 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8709 return SourceRange(beg, end);
8710}
8711
8712/// \brief Read an integral value
8713llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8714 unsigned BitWidth = Record[Idx++];
8715 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8716 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8717 Idx += NumWords;
8718 return Result;
8719}
8720
8721/// \brief Read a signed integral value
8722llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8723 bool isUnsigned = Record[Idx++];
8724 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8725}
8726
8727/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008728llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8729 const llvm::fltSemantics &Sem,
8730 unsigned &Idx) {
8731 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008732}
8733
8734// \brief Read a string
8735std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8736 unsigned Len = Record[Idx++];
8737 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8738 Idx += Len;
8739 return Result;
8740}
8741
Richard Smith7ed1bc92014-12-05 22:42:13 +00008742std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8743 unsigned &Idx) {
8744 std::string Filename = ReadString(Record, Idx);
8745 ResolveImportedPath(F, Filename);
8746 return Filename;
8747}
8748
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008749VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008750 unsigned &Idx) {
8751 unsigned Major = Record[Idx++];
8752 unsigned Minor = Record[Idx++];
8753 unsigned Subminor = Record[Idx++];
8754 if (Minor == 0)
8755 return VersionTuple(Major);
8756 if (Subminor == 0)
8757 return VersionTuple(Major, Minor - 1);
8758 return VersionTuple(Major, Minor - 1, Subminor - 1);
8759}
8760
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008761CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008762 const RecordData &Record,
8763 unsigned &Idx) {
8764 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8765 return CXXTemporary::Create(Context, Decl);
8766}
8767
Richard Smith37a93df2017-02-18 00:32:02 +00008768DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008769 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008770}
8771
Richard Smith37a93df2017-02-18 00:32:02 +00008772DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008773 return Diags.Report(Loc, DiagID);
8774}
8775
8776/// \brief Retrieve the identifier table associated with the
8777/// preprocessor.
8778IdentifierTable &ASTReader::getIdentifierTable() {
8779 return PP.getIdentifierTable();
8780}
8781
8782/// \brief Record that the given ID maps to the given switch-case
8783/// statement.
8784void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008785 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008786 "Already have a SwitchCase with this ID");
8787 (*CurrSwitchCaseStmts)[ID] = SC;
8788}
8789
8790/// \brief Retrieve the switch-case statement with the given ID.
8791SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008792 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 return (*CurrSwitchCaseStmts)[ID];
8794}
8795
8796void ASTReader::ClearSwitchCaseIDs() {
8797 CurrSwitchCaseStmts->clear();
8798}
8799
8800void ASTReader::ReadComments() {
8801 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008802 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008803 serialization::ModuleFile *> >::iterator
8804 I = CommentsCursors.begin(),
8805 E = CommentsCursors.end();
8806 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008807 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008808 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008809 serialization::ModuleFile &F = *I->second;
8810 SavedStreamPosition SavedPosition(Cursor);
8811
8812 RecordData Record;
8813 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008814 llvm::BitstreamEntry Entry =
8815 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008816
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008817 switch (Entry.Kind) {
8818 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8819 case llvm::BitstreamEntry::Error:
8820 Error("malformed block record in AST file");
8821 return;
8822 case llvm::BitstreamEntry::EndBlock:
8823 goto NextCursor;
8824 case llvm::BitstreamEntry::Record:
8825 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008826 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008827 }
8828
8829 // Read a record.
8830 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008831 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008832 case COMMENTS_RAW_COMMENT: {
8833 unsigned Idx = 0;
8834 SourceRange SR = ReadSourceRange(F, Record, Idx);
8835 RawComment::CommentKind Kind =
8836 (RawComment::CommentKind) Record[Idx++];
8837 bool IsTrailingComment = Record[Idx++];
8838 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008839 Comments.push_back(new (Context) RawComment(
8840 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8841 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008842 break;
8843 }
8844 }
8845 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008846 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008847 // De-serialized SourceLocations get negative FileIDs for other modules,
8848 // potentially invalidating the original order. Sort it again.
8849 std::sort(Comments.begin(), Comments.end(),
8850 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008851 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008852 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008853}
8854
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008855void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8856 bool IncludeSystem, bool Complain,
8857 llvm::function_ref<void(const serialization::InputFile &IF,
8858 bool isSystem)> Visitor) {
8859 unsigned NumUserInputs = MF.NumUserInputFiles;
8860 unsigned NumInputs = MF.InputFilesLoaded.size();
8861 assert(NumUserInputs <= NumInputs);
8862 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8863 for (unsigned I = 0; I < N; ++I) {
8864 bool IsSystem = I >= NumUserInputs;
8865 InputFile IF = getInputFile(MF, I+1, Complain);
8866 Visitor(IF, IsSystem);
8867 }
8868}
8869
Richard Smithcd45dbc2014-04-19 03:48:30 +00008870std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8871 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008872 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008873 return M->getFullModuleName();
8874
8875 // Otherwise, use the name of the top-level module the decl is within.
8876 if (ModuleFile *M = getOwningModuleFile(D))
8877 return M->ModuleName;
8878
8879 // Not from a module.
8880 return "";
8881}
8882
Guy Benyei11169dd2012-12-18 14:30:41 +00008883void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008884 while (!PendingIdentifierInfos.empty() ||
8885 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008886 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008887 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008888 // If any identifiers with corresponding top-level declarations have
8889 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008890 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8891 TopLevelDeclsMap;
8892 TopLevelDeclsMap TopLevelDecls;
8893
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008895 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008896 SmallVector<uint32_t, 4> DeclIDs =
8897 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008898 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008899
8900 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008901 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008902
Richard Smith851072e2014-05-19 20:59:20 +00008903 // For each decl chain that we wanted to complete while deserializing, mark
8904 // it as "still needs to be completed".
8905 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8906 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8907 }
8908 PendingIncompleteDeclChains.clear();
8909
Guy Benyei11169dd2012-12-18 14:30:41 +00008910 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008911 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008912 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008913 PendingDeclChains.clear();
8914
Douglas Gregor6168bd22013-02-18 15:53:43 +00008915 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008916 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8917 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008918 IdentifierInfo *II = TLD->first;
8919 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008920 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008921 }
8922 }
8923
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 // Load any pending macro definitions.
8925 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008926 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8927 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8928 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8929 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008930 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008931 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008932 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008933 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008934 resolvePendingMacro(II, Info);
8935 }
8936 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008937 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008938 ++IDIdx) {
8939 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008940 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008941 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008942 }
8943 }
8944 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008945
8946 // Wire up the DeclContexts for Decls that we delayed setting until
8947 // recursive loading is completed.
8948 while (!PendingDeclContextInfos.empty()) {
8949 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8950 PendingDeclContextInfos.pop_front();
8951 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8952 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8953 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8954 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008955
Richard Smithd1c46742014-04-30 02:24:17 +00008956 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008957 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008958 auto Update = PendingUpdateRecords.pop_back_val();
8959 ReadingKindTracker ReadingKind(Read_Decl, *this);
8960 loadDeclUpdateRecords(Update.first, Update.second);
8961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008962 }
Richard Smith8a639892015-01-24 01:07:20 +00008963
8964 // At this point, all update records for loaded decls are in place, so any
8965 // fake class definitions should have become real.
8966 assert(PendingFakeDefinitionData.empty() &&
8967 "faked up a class definition but never saw the real one");
8968
Guy Benyei11169dd2012-12-18 14:30:41 +00008969 // If we deserialized any C++ or Objective-C class definitions, any
8970 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008971 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008972 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008973 for (Decl *D : PendingDefinitions) {
8974 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008975 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008976 // Make sure that the TagType points at the definition.
8977 const_cast<TagType*>(TagT)->decl = TD;
8978 }
Richard Smith8ce51082015-03-11 01:44:51 +00008979
Craig Topperc6914d02014-08-25 04:15:02 +00008980 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008981 for (auto *R = getMostRecentExistingDecl(RD); R;
8982 R = R->getPreviousDecl()) {
8983 assert((R == D) ==
8984 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008985 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008986 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 }
8989
8990 continue;
8991 }
Richard Smith8ce51082015-03-11 01:44:51 +00008992
Craig Topperc6914d02014-08-25 04:15:02 +00008993 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008994 // Make sure that the ObjCInterfaceType points at the definition.
8995 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8996 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008997
8998 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8999 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9000
Guy Benyei11169dd2012-12-18 14:30:41 +00009001 continue;
9002 }
Richard Smith8ce51082015-03-11 01:44:51 +00009003
Craig Topperc6914d02014-08-25 04:15:02 +00009004 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009005 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9006 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9007
Guy Benyei11169dd2012-12-18 14:30:41 +00009008 continue;
9009 }
Richard Smith8ce51082015-03-11 01:44:51 +00009010
Craig Topperc6914d02014-08-25 04:15:02 +00009011 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009012 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9013 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009014 }
9015 PendingDefinitions.clear();
9016
9017 // Load the bodies of any functions or methods we've encountered. We do
9018 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00009019 // have been fully wired up (hasBody relies on this).
9020 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00009021 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9022 PBEnd = PendingBodies.end();
9023 PB != PBEnd; ++PB) {
9024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9025 // FIXME: Check for =delete/=default?
9026 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00009027 const FunctionDecl *Defn = nullptr;
David Blaikiee6b7c282017-04-11 20:46:34 +00009028 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009029 FD->setLazyBody(PB->second);
David Blaikiee6b7c282017-04-11 20:46:34 +00009030 } else
Richard Smith6561f922016-09-12 21:06:40 +00009031 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00009032 continue;
9033 }
9034
9035 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9036 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9037 MD->setLazyBody(PB->second);
9038 }
9039 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00009040
9041 // Do some cleanup.
9042 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9043 getContext().deduplicateMergedDefinitonsFor(ND);
9044 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009045}
9046
9047void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00009048 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9049 return;
9050
Richard Smitha0ce9c42014-07-29 23:23:27 +00009051 // Trigger the import of the full definition of each class that had any
9052 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009053 // These updates may in turn find and diagnose some ODR failures, so take
9054 // ownership of the set first.
9055 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9056 PendingOdrMergeFailures.clear();
9057 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009058 Merge.first->buildLookup();
9059 Merge.first->decls_begin();
9060 Merge.first->bases_begin();
9061 Merge.first->vbases_begin();
9062 for (auto *RD : Merge.second) {
9063 RD->decls_begin();
9064 RD->bases_begin();
9065 RD->vbases_begin();
9066 }
9067 }
9068
9069 // For each declaration from a merged context, check that the canonical
9070 // definition of that context also contains a declaration of the same
9071 // entity.
9072 //
9073 // Caution: this loop does things that might invalidate iterators into
9074 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9075 while (!PendingOdrMergeChecks.empty()) {
9076 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9077
9078 // FIXME: Skip over implicit declarations for now. This matters for things
9079 // like implicitly-declared special member functions. This isn't entirely
9080 // correct; we can end up with multiple unmerged declarations of the same
9081 // implicit entity.
9082 if (D->isImplicit())
9083 continue;
9084
9085 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009086
9087 bool Found = false;
9088 const Decl *DCanon = D->getCanonicalDecl();
9089
Richard Smith01bdb7a2014-08-28 05:44:07 +00009090 for (auto RI : D->redecls()) {
9091 if (RI->getLexicalDeclContext() == CanonDef) {
9092 Found = true;
9093 break;
9094 }
9095 }
9096 if (Found)
9097 continue;
9098
Richard Smith0f4e2c42015-08-06 04:23:48 +00009099 // Quick check failed, time to do the slow thing. Note, we can't just
9100 // look up the name of D in CanonDef here, because the member that is
9101 // in CanonDef might not be found by name lookup (it might have been
9102 // replaced by a more recent declaration in the lookup table), and we
9103 // can't necessarily find it in the redeclaration chain because it might
9104 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009105 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009106 for (auto *CanonMember : CanonDef->decls()) {
9107 if (CanonMember->getCanonicalDecl() == DCanon) {
9108 // This can happen if the declaration is merely mergeable and not
9109 // actually redeclarable (we looked for redeclarations earlier).
9110 //
9111 // FIXME: We should be able to detect this more efficiently, without
9112 // pulling in all of the members of CanonDef.
9113 Found = true;
9114 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009115 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009116 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9117 if (ND->getDeclName() == D->getDeclName())
9118 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009119 }
9120
9121 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009122 // The AST doesn't like TagDecls becoming invalid after they've been
9123 // completed. We only really need to mark FieldDecls as invalid here.
9124 if (!isa<TagDecl>(D))
9125 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009126
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009127 // Ensure we don't accidentally recursively enter deserialization while
9128 // we're producing our diagnostic.
9129 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009130
9131 std::string CanonDefModule =
9132 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9133 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9134 << D << getOwningModuleNameForDiagnostic(D)
9135 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9136
9137 if (Candidates.empty())
9138 Diag(cast<Decl>(CanonDef)->getLocation(),
9139 diag::note_module_odr_violation_no_possible_decls) << D;
9140 else {
9141 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9142 Diag(Candidates[I]->getLocation(),
9143 diag::note_module_odr_violation_possible_decl)
9144 << Candidates[I];
9145 }
9146
9147 DiagnosedOdrMergeFailures.insert(CanonDef);
9148 }
9149 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009150
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009151 if (OdrMergeFailures.empty())
9152 return;
9153
9154 // Ensure we don't accidentally recursively enter deserialization while
9155 // we're producing our diagnostics.
9156 Deserializing RecursionGuard(this);
9157
Richard Smithcd45dbc2014-04-19 03:48:30 +00009158 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009159 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009160 // If we've already pointed out a specific problem with this class, don't
9161 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009162 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009163 continue;
9164
9165 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009166 CXXRecordDecl *FirstRecord = Merge.first;
9167 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9168 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00009169 // Multiple different declarations got merged together; tell the user
9170 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009171 if (FirstRecord == SecondRecord)
9172 continue;
9173
9174 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9175 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9176 DeclHashes FirstHashes;
9177 DeclHashes SecondHashes;
9178 ODRHash Hash;
9179
9180 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9181 CXXRecordDecl *Record) {
9182 for (auto *D : Record->decls()) {
9183 // Due to decl merging, the first CXXRecordDecl is the parent of
9184 // Decls in both records.
9185 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9186 continue;
9187 Hash.clear();
9188 Hash.AddSubDecl(D);
9189 Hashes.emplace_back(D, Hash.CalculateHash());
9190 }
9191 };
9192 PopulateHashes(FirstHashes, FirstRecord);
9193 PopulateHashes(SecondHashes, SecondRecord);
9194
9195 // Used with err_module_odr_violation_mismatch_decl and
9196 // note_module_odr_violation_mismatch_decl
9197 enum {
9198 EndOfClass,
9199 PublicSpecifer,
9200 PrivateSpecifer,
9201 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009202 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009203 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009204 CXXMethod,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009205 Other
9206 } FirstDiffType = Other,
9207 SecondDiffType = Other;
9208
9209 auto DifferenceSelector = [](Decl *D) {
9210 assert(D && "valid Decl required");
9211 switch (D->getKind()) {
9212 default:
9213 return Other;
9214 case Decl::AccessSpec:
9215 switch (D->getAccess()) {
9216 case AS_public:
9217 return PublicSpecifer;
9218 case AS_private:
9219 return PrivateSpecifer;
9220 case AS_protected:
9221 return ProtectedSpecifer;
9222 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009223 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009224 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009225 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009226 case Decl::StaticAssert:
9227 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009228 case Decl::Field:
9229 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009230 case Decl::CXXMethod:
9231 return CXXMethod;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009232 }
9233 };
9234
9235 Decl *FirstDecl = nullptr;
9236 Decl *SecondDecl = nullptr;
9237 auto FirstIt = FirstHashes.begin();
9238 auto SecondIt = SecondHashes.begin();
9239
9240 // If there is a diagnoseable difference, FirstDiffType and
9241 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9242 // filled in if not EndOfClass.
9243 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009244 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9245 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009246 ++FirstIt;
9247 ++SecondIt;
9248 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009249 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009250
Richard Trieue7f7ed22017-02-22 01:11:25 +00009251 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9252 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9253
9254 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9255 SecondDiffType =
9256 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9257
9258 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009259 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009260
9261 if (FirstDiffType == Other || SecondDiffType == Other) {
9262 // Reaching this point means an unexpected Decl was encountered
9263 // or no difference was detected. This causes a generic error
9264 // message to be emitted.
9265 Diag(FirstRecord->getLocation(),
9266 diag::err_module_odr_violation_different_definitions)
9267 << FirstRecord << FirstModule.empty() << FirstModule;
9268
9269 Diag(SecondRecord->getLocation(),
9270 diag::note_module_odr_violation_different_definitions)
9271 << SecondModule;
9272 Diagnosed = true;
9273 break;
9274 }
9275
9276 if (FirstDiffType != SecondDiffType) {
9277 SourceLocation FirstLoc;
9278 SourceRange FirstRange;
9279 if (FirstDiffType == EndOfClass) {
9280 FirstLoc = FirstRecord->getBraceRange().getEnd();
9281 } else {
9282 FirstLoc = FirstIt->first->getLocation();
9283 FirstRange = FirstIt->first->getSourceRange();
9284 }
9285 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9286 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9287 << FirstDiffType;
9288
9289 SourceLocation SecondLoc;
9290 SourceRange SecondRange;
9291 if (SecondDiffType == EndOfClass) {
9292 SecondLoc = SecondRecord->getBraceRange().getEnd();
9293 } else {
9294 SecondLoc = SecondDecl->getLocation();
9295 SecondRange = SecondDecl->getSourceRange();
9296 }
9297 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9298 << SecondModule << SecondRange << SecondDiffType;
9299 Diagnosed = true;
9300 break;
9301 }
9302
Richard Trieu639d7b62017-02-22 22:22:42 +00009303 assert(FirstDiffType == SecondDiffType);
9304
9305 // Used with err_module_odr_violation_mismatch_decl_diff and
9306 // note_module_odr_violation_mismatch_decl_diff
9307 enum ODRDeclDifference{
9308 StaticAssertCondition,
9309 StaticAssertMessage,
9310 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009311 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009312 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009313 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009314 FieldDifferentWidthBitField,
9315 FieldSingleMutable,
9316 FieldSingleInitializer,
9317 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009318 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009319 MethodDeleted,
9320 MethodVirtual,
9321 MethodStatic,
9322 MethodVolatile,
9323 MethodConst,
9324 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009325 MethodNumberParameters,
9326 MethodParameterType,
9327 MethodParameterName,
Richard Trieu639d7b62017-02-22 22:22:42 +00009328 };
9329
9330 // These lambdas have the common portions of the ODR diagnostics. This
9331 // has the same return as Diag(), so addition parameters can be passed
9332 // in with operator<<
9333 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9334 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9335 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9336 << FirstRecord << FirstModule.empty() << FirstModule << Range
9337 << DiffType;
9338 };
9339 auto ODRDiagNote = [&SecondModule, this](
9340 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9341 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9342 << SecondModule << Range << DiffType;
9343 };
9344
9345 auto ComputeODRHash = [&Hash](const Stmt* S) {
9346 assert(S);
9347 Hash.clear();
9348 Hash.AddStmt(S);
9349 return Hash.CalculateHash();
9350 };
9351
Richard Trieu8459ddf2017-02-24 02:59:12 +00009352 auto ComputeDeclNameODRHash = [&Hash](const DeclarationName Name) {
9353 Hash.clear();
9354 Hash.AddDeclarationName(Name);
9355 return Hash.CalculateHash();
9356 };
9357
Richard Trieu02552272017-05-02 23:58:52 +00009358 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9359 Hash.clear();
9360 Hash.AddQualType(Ty);
9361 return Hash.CalculateHash();
9362 };
9363
Richard Trieu639d7b62017-02-22 22:22:42 +00009364 switch (FirstDiffType) {
9365 case Other:
9366 case EndOfClass:
9367 case PublicSpecifer:
9368 case PrivateSpecifer:
9369 case ProtectedSpecifer:
9370 llvm_unreachable("Invalid diff type");
9371
9372 case StaticAssert: {
9373 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9374 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9375
9376 Expr *FirstExpr = FirstSA->getAssertExpr();
9377 Expr *SecondExpr = SecondSA->getAssertExpr();
9378 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9379 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9380 if (FirstODRHash != SecondODRHash) {
9381 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9382 StaticAssertCondition);
9383 ODRDiagNote(SecondExpr->getLocStart(),
9384 SecondExpr->getSourceRange(), StaticAssertCondition);
9385 Diagnosed = true;
9386 break;
9387 }
9388
9389 StringLiteral *FirstStr = FirstSA->getMessage();
9390 StringLiteral *SecondStr = SecondSA->getMessage();
9391 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9392 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9393 SourceLocation FirstLoc, SecondLoc;
9394 SourceRange FirstRange, SecondRange;
9395 if (FirstStr) {
9396 FirstLoc = FirstStr->getLocStart();
9397 FirstRange = FirstStr->getSourceRange();
9398 } else {
9399 FirstLoc = FirstSA->getLocStart();
9400 FirstRange = FirstSA->getSourceRange();
9401 }
9402 if (SecondStr) {
9403 SecondLoc = SecondStr->getLocStart();
9404 SecondRange = SecondStr->getSourceRange();
9405 } else {
9406 SecondLoc = SecondSA->getLocStart();
9407 SecondRange = SecondSA->getSourceRange();
9408 }
9409 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9410 << (FirstStr == nullptr);
9411 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9412 << (SecondStr == nullptr);
9413 Diagnosed = true;
9414 break;
9415 }
9416
9417 if (FirstStr && SecondStr &&
9418 FirstStr->getString() != SecondStr->getString()) {
9419 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9420 StaticAssertMessage);
9421 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9422 StaticAssertMessage);
9423 Diagnosed = true;
9424 break;
9425 }
9426 break;
9427 }
Richard Trieud0786092017-02-23 00:23:01 +00009428 case Field: {
9429 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9430 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9431 IdentifierInfo *FirstII = FirstField->getIdentifier();
9432 IdentifierInfo *SecondII = SecondField->getIdentifier();
9433 if (FirstII->getName() != SecondII->getName()) {
9434 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9435 FieldName)
9436 << FirstII;
9437 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9438 FieldName)
9439 << SecondII;
9440
9441 Diagnosed = true;
9442 break;
9443 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009444
9445 assert(
9446 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9447
9448 QualType FirstType = FirstField->getType();
9449 QualType SecondType = SecondField->getType();
9450 const TypedefType *FirstTypedef = dyn_cast<TypedefType>(FirstType);
9451 const TypedefType *SecondTypedef = dyn_cast<TypedefType>(SecondType);
9452
9453 if ((FirstTypedef && !SecondTypedef) ||
9454 (!FirstTypedef && SecondTypedef)) {
9455 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9456 FieldTypeName)
9457 << FirstII << FirstType;
9458 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9459 FieldTypeName)
9460 << SecondII << SecondType;
9461
9462 Diagnosed = true;
9463 break;
9464 }
9465
9466 if (FirstTypedef && SecondTypedef) {
9467 unsigned FirstHash = ComputeDeclNameODRHash(
9468 FirstTypedef->getDecl()->getDeclName());
9469 unsigned SecondHash = ComputeDeclNameODRHash(
9470 SecondTypedef->getDecl()->getDeclName());
9471 if (FirstHash != SecondHash) {
9472 ODRDiagError(FirstField->getLocation(),
9473 FirstField->getSourceRange(), FieldTypeName)
9474 << FirstII << FirstType;
9475 ODRDiagNote(SecondField->getLocation(),
9476 SecondField->getSourceRange(), FieldTypeName)
9477 << SecondII << SecondType;
9478
9479 Diagnosed = true;
9480 break;
9481 }
9482 }
9483
Richard Trieu93772fc2017-02-24 20:59:28 +00009484 const bool IsFirstBitField = FirstField->isBitField();
9485 const bool IsSecondBitField = SecondField->isBitField();
9486 if (IsFirstBitField != IsSecondBitField) {
9487 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9488 FieldSingleBitField)
9489 << FirstII << IsFirstBitField;
9490 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9491 FieldSingleBitField)
9492 << SecondII << IsSecondBitField;
9493 Diagnosed = true;
9494 break;
9495 }
9496
9497 if (IsFirstBitField && IsSecondBitField) {
9498 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9499 FieldDifferentWidthBitField)
9500 << FirstII << FirstField->getBitWidth()->getSourceRange();
9501 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9502 FieldDifferentWidthBitField)
9503 << SecondII << SecondField->getBitWidth()->getSourceRange();
9504 Diagnosed = true;
9505 break;
9506 }
9507
Richard Trieu8d543e22017-02-24 23:35:37 +00009508 const bool IsFirstMutable = FirstField->isMutable();
9509 const bool IsSecondMutable = SecondField->isMutable();
9510 if (IsFirstMutable != IsSecondMutable) {
9511 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9512 FieldSingleMutable)
9513 << FirstII << IsFirstMutable;
9514 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9515 FieldSingleMutable)
9516 << SecondII << IsSecondMutable;
9517 Diagnosed = true;
9518 break;
9519 }
9520
9521 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9522 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9523 if ((!FirstInitializer && SecondInitializer) ||
9524 (FirstInitializer && !SecondInitializer)) {
9525 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9526 FieldSingleInitializer)
9527 << FirstII << (FirstInitializer != nullptr);
9528 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9529 FieldSingleInitializer)
9530 << SecondII << (SecondInitializer != nullptr);
9531 Diagnosed = true;
9532 break;
9533 }
9534
9535 if (FirstInitializer && SecondInitializer) {
9536 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9537 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9538 if (FirstInitHash != SecondInitHash) {
9539 ODRDiagError(FirstField->getLocation(),
9540 FirstField->getSourceRange(),
9541 FieldDifferentInitializers)
9542 << FirstII << FirstInitializer->getSourceRange();
9543 ODRDiagNote(SecondField->getLocation(),
9544 SecondField->getSourceRange(),
9545 FieldDifferentInitializers)
9546 << SecondII << SecondInitializer->getSourceRange();
9547 Diagnosed = true;
9548 break;
9549 }
9550 }
9551
Richard Trieud0786092017-02-23 00:23:01 +00009552 break;
9553 }
Richard Trieu48143742017-02-28 21:24:38 +00009554 case CXXMethod: {
9555 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9556 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu583e2c12017-03-04 00:08:58 +00009557 auto FirstName = FirstMethod->getDeclName();
9558 auto SecondName = SecondMethod->getDeclName();
9559 if (FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009560 ODRDiagError(FirstMethod->getLocation(),
9561 FirstMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009562 << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009563 ODRDiagNote(SecondMethod->getLocation(),
9564 SecondMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009565 << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009566
9567 Diagnosed = true;
9568 break;
9569 }
9570
Richard Trieu583e2c12017-03-04 00:08:58 +00009571 const bool FirstDeleted = FirstMethod->isDeleted();
9572 const bool SecondDeleted = SecondMethod->isDeleted();
9573 if (FirstDeleted != SecondDeleted) {
9574 ODRDiagError(FirstMethod->getLocation(),
9575 FirstMethod->getSourceRange(), MethodDeleted)
9576 << FirstName << FirstDeleted;
9577
9578 ODRDiagNote(SecondMethod->getLocation(),
9579 SecondMethod->getSourceRange(), MethodDeleted)
9580 << SecondName << SecondDeleted;
9581 Diagnosed = true;
9582 break;
9583 }
9584
9585 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9586 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9587 const bool FirstPure = FirstMethod->isPure();
9588 const bool SecondPure = SecondMethod->isPure();
9589 if ((FirstVirtual || SecondVirtual) &&
9590 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9591 ODRDiagError(FirstMethod->getLocation(),
9592 FirstMethod->getSourceRange(), MethodVirtual)
9593 << FirstName << FirstPure << FirstVirtual;
9594 ODRDiagNote(SecondMethod->getLocation(),
9595 SecondMethod->getSourceRange(), MethodVirtual)
9596 << SecondName << SecondPure << SecondVirtual;
9597 Diagnosed = true;
9598 break;
9599 }
9600
9601 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9602 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9603 // class needs to be checked instead.
9604 const auto FirstStorage = FirstMethod->getStorageClass();
9605 const auto SecondStorage = SecondMethod->getStorageClass();
9606 const bool FirstStatic = FirstStorage == SC_Static;
9607 const bool SecondStatic = SecondStorage == SC_Static;
9608 if (FirstStatic != SecondStatic) {
9609 ODRDiagError(FirstMethod->getLocation(),
9610 FirstMethod->getSourceRange(), MethodStatic)
9611 << FirstName << FirstStatic;
9612 ODRDiagNote(SecondMethod->getLocation(),
9613 SecondMethod->getSourceRange(), MethodStatic)
9614 << SecondName << SecondStatic;
9615 Diagnosed = true;
9616 break;
9617 }
9618
9619 const bool FirstVolatile = FirstMethod->isVolatile();
9620 const bool SecondVolatile = SecondMethod->isVolatile();
9621 if (FirstVolatile != SecondVolatile) {
9622 ODRDiagError(FirstMethod->getLocation(),
9623 FirstMethod->getSourceRange(), MethodVolatile)
9624 << FirstName << FirstVolatile;
9625 ODRDiagNote(SecondMethod->getLocation(),
9626 SecondMethod->getSourceRange(), MethodVolatile)
9627 << SecondName << SecondVolatile;
9628 Diagnosed = true;
9629 break;
9630 }
9631
9632 const bool FirstConst = FirstMethod->isConst();
9633 const bool SecondConst = SecondMethod->isConst();
9634 if (FirstConst != SecondConst) {
9635 ODRDiagError(FirstMethod->getLocation(),
9636 FirstMethod->getSourceRange(), MethodConst)
9637 << FirstName << FirstConst;
9638 ODRDiagNote(SecondMethod->getLocation(),
9639 SecondMethod->getSourceRange(), MethodConst)
9640 << SecondName << SecondConst;
9641 Diagnosed = true;
9642 break;
9643 }
9644
9645 const bool FirstInline = FirstMethod->isInlineSpecified();
9646 const bool SecondInline = SecondMethod->isInlineSpecified();
9647 if (FirstInline != SecondInline) {
9648 ODRDiagError(FirstMethod->getLocation(),
9649 FirstMethod->getSourceRange(), MethodInline)
9650 << FirstName << FirstInline;
9651 ODRDiagNote(SecondMethod->getLocation(),
9652 SecondMethod->getSourceRange(), MethodInline)
9653 << SecondName << SecondInline;
9654 Diagnosed = true;
9655 break;
9656 }
9657
Richard Trieu02552272017-05-02 23:58:52 +00009658 const unsigned FirstNumParameters = FirstMethod->param_size();
9659 const unsigned SecondNumParameters = SecondMethod->param_size();
9660 if (FirstNumParameters != SecondNumParameters) {
9661 ODRDiagError(FirstMethod->getLocation(),
9662 FirstMethod->getSourceRange(), MethodNumberParameters)
9663 << FirstName << FirstNumParameters;
9664 ODRDiagNote(SecondMethod->getLocation(),
9665 SecondMethod->getSourceRange(), MethodNumberParameters)
9666 << SecondName << SecondNumParameters;
9667 Diagnosed = true;
9668 break;
9669 }
9670
9671 // Need this status boolean to know when break out of the switch.
9672 bool ParameterMismatch = false;
9673 for (unsigned I = 0; I < FirstNumParameters; ++I) {
9674 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9675 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9676
9677 QualType FirstParamType = FirstParam->getType();
9678 QualType SecondParamType = SecondParam->getType();
9679 if (FirstParamType != SecondParamType &&
9680 ComputeQualTypeODRHash(FirstParamType) !=
9681 ComputeQualTypeODRHash(SecondParamType)) {
9682 if (const DecayedType *ParamDecayedType =
9683 FirstParamType->getAs<DecayedType>()) {
9684 ODRDiagError(FirstMethod->getLocation(),
9685 FirstMethod->getSourceRange(), MethodParameterType)
9686 << FirstName << (I + 1) << FirstParamType << true
9687 << ParamDecayedType->getOriginalType();
9688 } else {
9689 ODRDiagError(FirstMethod->getLocation(),
9690 FirstMethod->getSourceRange(), MethodParameterType)
9691 << FirstName << (I + 1) << FirstParamType << false;
9692 }
9693
9694 if (const DecayedType *ParamDecayedType =
9695 SecondParamType->getAs<DecayedType>()) {
9696 ODRDiagNote(SecondMethod->getLocation(),
9697 SecondMethod->getSourceRange(), MethodParameterType)
9698 << SecondName << (I + 1) << SecondParamType << true
9699 << ParamDecayedType->getOriginalType();
9700 } else {
9701 ODRDiagNote(SecondMethod->getLocation(),
9702 SecondMethod->getSourceRange(), MethodParameterType)
9703 << SecondName << (I + 1) << SecondParamType << false;
9704 }
9705 ParameterMismatch = true;
9706 break;
9707 }
9708
9709 DeclarationName FirstParamName = FirstParam->getDeclName();
9710 DeclarationName SecondParamName = SecondParam->getDeclName();
9711 if (FirstParamName != SecondParamName) {
9712 ODRDiagError(FirstMethod->getLocation(),
9713 FirstMethod->getSourceRange(), MethodParameterName)
9714 << FirstName << (I + 1) << FirstParamName;
9715 ODRDiagNote(SecondMethod->getLocation(),
9716 SecondMethod->getSourceRange(), MethodParameterName)
9717 << SecondName << (I + 1) << SecondParamName;
9718 ParameterMismatch = true;
9719 break;
9720 }
9721 }
9722
9723 if (ParameterMismatch) {
9724 Diagnosed = true;
9725 break;
9726 }
9727
Richard Trieu48143742017-02-28 21:24:38 +00009728 break;
9729 }
Richard Trieu639d7b62017-02-22 22:22:42 +00009730 }
9731
Richard Trieue7f7ed22017-02-22 01:11:25 +00009732 if (Diagnosed == true)
9733 continue;
9734
9735 Diag(FirstRecord->getLocation(),
9736 diag::err_module_odr_violation_different_definitions)
9737 << FirstRecord << FirstModule.empty() << FirstModule;
9738
9739 Diag(SecondRecord->getLocation(),
9740 diag::note_module_odr_violation_different_definitions)
9741 << SecondModule;
9742 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009743 }
9744
9745 if (!Diagnosed) {
9746 // All definitions are updates to the same declaration. This happens if a
9747 // module instantiates the declaration of a class template specialization
9748 // and two or more other modules instantiate its definition.
9749 //
9750 // FIXME: Indicate which modules had instantiations of this definition.
9751 // FIXME: How can this even happen?
9752 Diag(Merge.first->getLocation(),
9753 diag::err_module_odr_violation_different_instantiations)
9754 << Merge.first;
9755 }
9756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009757}
9758
Richard Smithce18a182015-07-14 00:26:00 +00009759void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009760 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009761 ReadTimer->startTimer();
9762}
9763
Guy Benyei11169dd2012-12-18 14:30:41 +00009764void ASTReader::FinishedDeserializing() {
9765 assert(NumCurrentElementsDeserializing &&
9766 "FinishedDeserializing not paired with StartedDeserializing");
9767 if (NumCurrentElementsDeserializing == 1) {
9768 // We decrease NumCurrentElementsDeserializing only after pending actions
9769 // are finished, to avoid recursively re-calling finishPendingActions().
9770 finishPendingActions();
9771 }
9772 --NumCurrentElementsDeserializing;
9773
Richard Smitha0ce9c42014-07-29 23:23:27 +00009774 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009775 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009776 while (!PendingExceptionSpecUpdates.empty()) {
9777 auto Updates = std::move(PendingExceptionSpecUpdates);
9778 PendingExceptionSpecUpdates.clear();
9779 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009780 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009781 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009782 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009783 if (auto *Listener = Context.getASTMutationListener())
9784 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009785 for (auto *Redecl : Update.second->redecls())
9786 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009787 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009788 }
9789
Richard Smithce18a182015-07-14 00:26:00 +00009790 if (ReadTimer)
9791 ReadTimer->stopTimer();
9792
Richard Smith0f4e2c42015-08-06 04:23:48 +00009793 diagnoseOdrViolations();
9794
Richard Smith04d05b52014-03-23 00:27:18 +00009795 // We are not in recursive loading, so it's safe to pass the "interesting"
9796 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009797 if (Consumer)
9798 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009799 }
9800}
9801
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009802void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009803 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9804 // Remove any fake results before adding any real ones.
9805 auto It = PendingFakeLookupResults.find(II);
9806 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009807 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009808 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009809 // FIXME: this works around module+PCH performance issue.
9810 // Rather than erase the result from the map, which is O(n), just clear
9811 // the vector of NamedDecls.
9812 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009813 }
9814 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009815
9816 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9817 SemaObj->TUScope->AddDecl(D);
9818 } else if (SemaObj->TUScope) {
9819 // Adding the decl to IdResolver may have failed because it was already in
9820 // (even though it was not added in scope). If it is already in, make sure
9821 // it gets in the scope as well.
9822 if (std::find(SemaObj->IdResolver.begin(Name),
9823 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9824 SemaObj->TUScope->AddDecl(D);
9825 }
9826}
9827
David Blaikie61137e12017-01-05 18:23:18 +00009828ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9829 const PCHContainerReader &PCHContainerRdr,
9830 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9831 StringRef isysroot, bool DisableValidation,
9832 bool AllowASTWithCompilerErrors,
9833 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9834 bool UseGlobalIndex,
9835 std::unique_ptr<llvm::Timer> ReadTimer)
9836 : Listener(DisableValidation
9837 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9838 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009839 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009840 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00009841 Context(Context),
9842 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9843 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9844 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009845 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009846 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9847 AllowConfigurationMismatch(AllowConfigurationMismatch),
9848 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009849 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009850 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009851
9852 for (const auto &Ext : Extensions) {
9853 auto BlockName = Ext->getExtensionMetadata().BlockName;
9854 auto Known = ModuleFileExtensions.find(BlockName);
9855 if (Known != ModuleFileExtensions.end()) {
9856 Diags.Report(diag::warn_duplicate_module_file_extension)
9857 << BlockName;
9858 continue;
9859 }
9860
9861 ModuleFileExtensions.insert({BlockName, Ext});
9862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009863}
9864
9865ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009866 if (OwnsDeserializationListener)
9867 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009868}
Richard Smith10379092016-05-06 23:14:07 +00009869
9870IdentifierResolver &ASTReader::getIdResolver() {
9871 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9872}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009873
9874unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9875 unsigned AbbrevID) {
9876 Idx = 0;
9877 Record.clear();
9878 return Cursor.readRecord(AbbrevID, Record);
9879}