blob: 9258a6fb1265a13853ebfa19d33525401b6c4dcf [file] [log] [blame]
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001//===- ASTReader.cpp - AST File Reader ------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
John McCallc2f18312019-12-14 03:01:28 -050013#include "clang/Serialization/ASTRecordReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
John McCalld505e572019-12-13 21:54:44 -050016#include "clang/AST/AbstractTypeReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#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"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000022#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000024#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000025#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000028#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000031#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000032#include "clang/AST/NestedNameSpecifier.h"
John McCallc2f18312019-12-14 03:01:28 -050033#include "clang/AST/OpenMPClause.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000034#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000036#include "clang/AST/TemplateBase.h"
37#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000039#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "clang/AST/UnresolvedSet.h"
42#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000043#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000044#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000048#include "clang/Basic/IdentifierTable.h"
49#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000051#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include "clang/Basic/ObjCRuntime.h"
53#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000055#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000056#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include "clang/Basic/SourceManager.h"
58#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000059#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include "clang/Basic/TargetInfo.h"
61#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000064#include "clang/Lex/HeaderSearch.h"
65#include "clang/Lex/HeaderSearchOptions.h"
66#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000067#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000068#include "clang/Lex/PreprocessingRecord.h"
69#include "clang/Lex/Preprocessor.h"
70#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000071#include "clang/Lex/Token.h"
72#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000073#include "clang/Sema/Scope.h"
74#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000075#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000076#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000077#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000078#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000079#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000080#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080081#include "clang/Serialization/ModuleFile.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000082#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000084#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000085#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include "llvm/ADT/APFloat.h"
87#include "llvm/ADT/APInt.h"
88#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000089#include "llvm/ADT/ArrayRef.h"
90#include "llvm/ADT/DenseMap.h"
91#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000092#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000093#include "llvm/ADT/IntrusiveRefCntPtr.h"
94#include "llvm/ADT/None.h"
95#include "llvm/ADT/Optional.h"
96#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000097#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000098#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000099#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000101#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000102#include "llvm/ADT/StringMap.h"
103#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000104#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000105#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000106#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000107#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000108#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000109#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000110#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000111#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000112#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000113#include "llvm/Support/ErrorHandling.h"
114#include "llvm/Support/FileSystem.h"
115#include "llvm/Support/MemoryBuffer.h"
116#include "llvm/Support/Path.h"
117#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000118#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000119#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000120#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000121#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000123#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000125#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000127#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000128#include <limits>
129#include <map>
130#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000131#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000132#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133#include <tuple>
134#include <utility>
135#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000136
137using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000138using namespace clang::serialization;
139using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000140using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000141
Ben Langmuircb69b572014-03-07 06:40:32 +0000142//===----------------------------------------------------------------------===//
143// ChainedASTReaderListener implementation
144//===----------------------------------------------------------------------===//
145
146bool
147ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
148 return First->ReadFullVersionInformation(FullVersion) ||
149 Second->ReadFullVersionInformation(FullVersion);
150}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000151
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000152void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
153 First->ReadModuleName(ModuleName);
154 Second->ReadModuleName(ModuleName);
155}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000156
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000157void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
158 First->ReadModuleMapFile(ModuleMapPath);
159 Second->ReadModuleMapFile(ModuleMapPath);
160}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000161
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000162bool
163ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
164 bool Complain,
165 bool AllowCompatibleDifferences) {
166 return First->ReadLanguageOptions(LangOpts, Complain,
167 AllowCompatibleDifferences) ||
168 Second->ReadLanguageOptions(LangOpts, Complain,
169 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000170}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000171
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000172bool ChainedASTReaderListener::ReadTargetOptions(
173 const TargetOptions &TargetOpts, bool Complain,
174 bool AllowCompatibleDifferences) {
175 return First->ReadTargetOptions(TargetOpts, Complain,
176 AllowCompatibleDifferences) ||
177 Second->ReadTargetOptions(TargetOpts, Complain,
178 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000179}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000180
Ben Langmuircb69b572014-03-07 06:40:32 +0000181bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000182 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000183 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
184 Second->ReadDiagnosticOptions(DiagOpts, Complain);
185}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000186
Ben Langmuircb69b572014-03-07 06:40:32 +0000187bool
188ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
189 bool Complain) {
190 return First->ReadFileSystemOptions(FSOpts, Complain) ||
191 Second->ReadFileSystemOptions(FSOpts, Complain);
192}
193
194bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000195 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
196 bool Complain) {
197 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
198 Complain) ||
199 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
200 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000201}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000202
Ben Langmuircb69b572014-03-07 06:40:32 +0000203bool ChainedASTReaderListener::ReadPreprocessorOptions(
204 const PreprocessorOptions &PPOpts, bool Complain,
205 std::string &SuggestedPredefines) {
206 return First->ReadPreprocessorOptions(PPOpts, Complain,
207 SuggestedPredefines) ||
208 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
209}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000210
Ben Langmuircb69b572014-03-07 06:40:32 +0000211void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
212 unsigned Value) {
213 First->ReadCounter(M, Value);
214 Second->ReadCounter(M, Value);
215}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000216
Ben Langmuircb69b572014-03-07 06:40:32 +0000217bool ChainedASTReaderListener::needsInputFileVisitation() {
218 return First->needsInputFileVisitation() ||
219 Second->needsInputFileVisitation();
220}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000221
Ben Langmuircb69b572014-03-07 06:40:32 +0000222bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
223 return First->needsSystemInputFileVisitation() ||
224 Second->needsSystemInputFileVisitation();
225}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000226
Richard Smith216a3bd2015-08-13 17:57:10 +0000227void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
228 ModuleKind Kind) {
229 First->visitModuleFile(Filename, Kind);
230 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000231}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000232
Ben Langmuircb69b572014-03-07 06:40:32 +0000233bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000234 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000235 bool isOverridden,
236 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000237 bool Continue = false;
238 if (First->needsInputFileVisitation() &&
239 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000240 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
241 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000242 if (Second->needsInputFileVisitation() &&
243 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000244 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
245 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000246 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000247}
248
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000249void ChainedASTReaderListener::readModuleFileExtension(
250 const ModuleFileExtensionMetadata &Metadata) {
251 First->readModuleFileExtension(Metadata);
252 Second->readModuleFileExtension(Metadata);
253}
254
Guy Benyei11169dd2012-12-18 14:30:41 +0000255//===----------------------------------------------------------------------===//
256// PCH validator implementation
257//===----------------------------------------------------------------------===//
258
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000259ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000261/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000262/// language options.
263///
264/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000265/// \param AllowCompatibleDifferences If true, differences between compatible
266/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000267///
268/// \returns true if the languagae options mis-match, false otherwise.
269static bool checkLanguageOptions(const LangOptions &LangOpts,
270 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000271 DiagnosticsEngine *Diags,
272 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000273#define LANGOPT(Name, Bits, Default, Description) \
274 if (ExistingLangOpts.Name != LangOpts.Name) { \
275 if (Diags) \
276 Diags->Report(diag::err_pch_langopt_mismatch) \
277 << Description << LangOpts.Name << ExistingLangOpts.Name; \
278 return true; \
279 }
280
281#define VALUE_LANGOPT(Name, Bits, Default, Description) \
282 if (ExistingLangOpts.Name != LangOpts.Name) { \
283 if (Diags) \
284 Diags->Report(diag::err_pch_langopt_value_mismatch) \
285 << Description; \
286 return true; \
287 }
288
289#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
290 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
291 if (Diags) \
292 Diags->Report(diag::err_pch_langopt_value_mismatch) \
293 << Description; \
294 return true; \
295 }
296
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000297#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
298 if (!AllowCompatibleDifferences) \
299 LANGOPT(Name, Bits, Default, Description)
300
301#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
302 if (!AllowCompatibleDifferences) \
303 ENUM_LANGOPT(Name, Bits, Default, Description)
304
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000305#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
306 if (!AllowCompatibleDifferences) \
307 VALUE_LANGOPT(Name, Bits, Default, Description)
308
Guy Benyei11169dd2012-12-18 14:30:41 +0000309#define BENIGN_LANGOPT(Name, Bits, Default, Description)
310#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000311#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000312#include "clang/Basic/LangOptions.def"
313
Ben Langmuircd98cb72015-06-23 18:20:18 +0000314 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
315 if (Diags)
316 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
317 return true;
318 }
319
Guy Benyei11169dd2012-12-18 14:30:41 +0000320 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
321 if (Diags)
322 Diags->Report(diag::err_pch_langopt_value_mismatch)
323 << "target Objective-C runtime";
324 return true;
325 }
326
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000327 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
328 LangOpts.CommentOpts.BlockCommandNames) {
329 if (Diags)
330 Diags->Report(diag::err_pch_langopt_value_mismatch)
331 << "block command names";
332 return true;
333 }
334
Vedant Kumar85a83c22017-06-01 20:01:01 +0000335 // Sanitizer feature mismatches are treated as compatible differences. If
336 // compatible differences aren't allowed, we still only want to check for
337 // mismatches of non-modular sanitizers (the only ones which can affect AST
338 // generation).
339 if (!AllowCompatibleDifferences) {
340 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
341 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
342 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
343 ExistingSanitizers.clear(ModularSanitizers);
344 ImportedSanitizers.clear(ModularSanitizers);
345 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
346 const std::string Flag = "-fsanitize=";
347 if (Diags) {
348#define SANITIZER(NAME, ID) \
349 { \
350 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
351 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
352 if (InExistingModule != InImportedModule) \
353 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
354 << InExistingModule << (Flag + NAME); \
355 }
356#include "clang/Basic/Sanitizers.def"
357 }
358 return true;
359 }
360 }
361
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 return false;
363}
364
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000365/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000366/// target options.
367///
368/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
369///
370/// \returns true if the target options mis-match, false otherwise.
371static bool checkTargetOptions(const TargetOptions &TargetOpts,
372 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000373 DiagnosticsEngine *Diags,
374 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000375#define CHECK_TARGET_OPT(Field, Name) \
376 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
377 if (Diags) \
378 Diags->Report(diag::err_pch_targetopt_mismatch) \
379 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
380 return true; \
381 }
382
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000383 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000386
387 // We can tolerate different CPUs in many cases, notably when one CPU
388 // supports a strict superset of another. When allowing compatible
389 // differences skip this check.
390 if (!AllowCompatibleDifferences)
391 CHECK_TARGET_OPT(CPU, "target CPU");
392
Guy Benyei11169dd2012-12-18 14:30:41 +0000393#undef CHECK_TARGET_OPT
394
395 // Compare feature sets.
396 SmallVector<StringRef, 4> ExistingFeatures(
397 ExistingTargetOpts.FeaturesAsWritten.begin(),
398 ExistingTargetOpts.FeaturesAsWritten.end());
399 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
400 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000401 llvm::sort(ExistingFeatures);
402 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000403
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000404 // We compute the set difference in both directions explicitly so that we can
405 // diagnose the differences differently.
406 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
407 std::set_difference(
408 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
409 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
410 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
411 ExistingFeatures.begin(), ExistingFeatures.end(),
412 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000413
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000414 // If we are allowing compatible differences and the read feature set is
415 // a strict subset of the existing feature set, there is nothing to diagnose.
416 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
417 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000418
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000419 if (Diags) {
420 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000422 << /* is-existing-feature */ false << Feature;
423 for (StringRef Feature : UnmatchedExistingFeatures)
424 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
425 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000426 }
427
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000428 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000429}
430
431bool
432PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000433 bool Complain,
434 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 const LangOptions &ExistingLangOpts = PP.getLangOpts();
436 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000437 Complain ? &Reader.Diags : nullptr,
438 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000439}
440
441bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000442 bool Complain,
443 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000444 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
445 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000446 Complain ? &Reader.Diags : nullptr,
447 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000448}
449
450namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000451
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000452using MacroDefinitionsMap =
453 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
454using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000455
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000456} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000457
Ben Langmuirb92de022014-04-29 16:25:26 +0000458static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
459 DiagnosticsEngine &Diags,
460 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000461 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000462
463 // Check current mappings for new -Werror mappings, and the stored mappings
464 // for cases that were explicitly mapped to *not* be errors that are now
465 // errors because of options like -Werror.
466 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
467
Vedant Kumar48b4f762018-04-14 01:40:48 +0000468 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000469 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
470 diag::kind DiagID = DiagIDMappingPair.first;
471 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
472 if (CurLevel < DiagnosticsEngine::Error)
473 continue; // not significant
474 Level StoredLevel =
475 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
476 if (StoredLevel < DiagnosticsEngine::Error) {
477 if (Complain)
478 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
479 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
480 return true;
481 }
482 }
483 }
484
485 return false;
486}
487
Alp Tokerac4e8e52014-06-22 21:58:33 +0000488static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
489 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
490 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
491 return true;
492 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000493}
494
495static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
496 DiagnosticsEngine &Diags,
497 bool IsSystem, bool Complain) {
498 // Top-level options
499 if (IsSystem) {
500 if (Diags.getSuppressSystemWarnings())
501 return false;
502 // If -Wsystem-headers was not enabled before, be conservative
503 if (StoredDiags.getSuppressSystemWarnings()) {
504 if (Complain)
505 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
506 return true;
507 }
508 }
509
510 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
511 if (Complain)
512 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
513 return true;
514 }
515
516 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
517 !StoredDiags.getEnableAllWarnings()) {
518 if (Complain)
519 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
520 return true;
521 }
522
523 if (isExtHandlingFromDiagsError(Diags) &&
524 !isExtHandlingFromDiagsError(StoredDiags)) {
525 if (Complain)
526 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
527 return true;
528 }
529
530 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
531}
532
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000533/// Return the top import module if it is implicit, nullptr otherwise.
534static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
535 Preprocessor &PP) {
536 // If the original import came from a file explicitly generated by the user,
537 // don't check the diagnostic mappings.
538 // FIXME: currently this is approximated by checking whether this is not a
539 // module import of an implicitly-loaded module file.
540 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
541 // the transitive closure of its imports, since unrelated modules cannot be
542 // imported until after this module finishes validation.
543 ModuleFile *TopImport = &*ModuleMgr.rbegin();
544 while (!TopImport->ImportedBy.empty())
545 TopImport = TopImport->ImportedBy[0];
546 if (TopImport->Kind != MK_ImplicitModule)
547 return nullptr;
548
549 StringRef ModuleName = TopImport->ModuleName;
550 assert(!ModuleName.empty() && "diagnostic options read before module name");
551
552 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
553 assert(M && "missing module");
554 return M;
555}
556
Ben Langmuirb92de022014-04-29 16:25:26 +0000557bool PCHValidator::ReadDiagnosticOptions(
558 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
559 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
560 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
561 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000562 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000563 // This should never fail, because we would have processed these options
564 // before writing them to an ASTFile.
565 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
566
567 ModuleManager &ModuleMgr = Reader.getModuleManager();
568 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
569
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000570 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
571 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000572 return false;
573
Ben Langmuirb92de022014-04-29 16:25:26 +0000574 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
575 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000576 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
577 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000578}
579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000580/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000581/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000582static void
583collectMacroDefinitions(const PreprocessorOptions &PPOpts,
584 MacroDefinitionsMap &Macros,
585 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000586 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
587 StringRef Macro = PPOpts.Macros[I].first;
588 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000589
590 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
591 StringRef MacroName = MacroPair.first;
592 StringRef MacroBody = MacroPair.second;
593
594 // For an #undef'd macro, we only care about the name.
595 if (IsUndef) {
596 if (MacroNames && !Macros.count(MacroName))
597 MacroNames->push_back(MacroName);
598
599 Macros[MacroName] = std::make_pair("", true);
600 continue;
601 }
602
603 // For a #define'd macro, figure out the actual definition.
604 if (MacroName.size() == Macro.size())
605 MacroBody = "1";
606 else {
607 // Note: GCC drops anything following an end-of-line character.
608 StringRef::size_type End = MacroBody.find_first_of("\n\r");
609 MacroBody = MacroBody.substr(0, End);
610 }
611
612 if (MacroNames && !Macros.count(MacroName))
613 MacroNames->push_back(MacroName);
614 Macros[MacroName] = std::make_pair(MacroBody, false);
615 }
616}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000617
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000618/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000619/// against the preprocessor options in an existing preprocessor.
620///
621/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000622/// \param Validate If true, validate preprocessor options. If false, allow
623/// macros defined by \p ExistingPPOpts to override those defined by
624/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000625static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
626 const PreprocessorOptions &ExistingPPOpts,
627 DiagnosticsEngine *Diags,
628 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000629 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000630 const LangOptions &LangOpts,
631 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 // Check macro definitions.
633 MacroDefinitionsMap ASTFileMacros;
634 collectMacroDefinitions(PPOpts, ASTFileMacros);
635 MacroDefinitionsMap ExistingMacros;
636 SmallVector<StringRef, 4> ExistingMacroNames;
637 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
638
Vedant Kumar48b4f762018-04-14 01:40:48 +0000639 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000641 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
643
644 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000645 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
646 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000647 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 // FIXME: Check whether this identifier was referenced anywhere in the
649 // AST file. If so, we should reject the AST file. Unfortunately, this
650 // information isn't in the control block. What shall we do about it?
651
652 if (Existing.second) {
653 SuggestedPredefines += "#undef ";
654 SuggestedPredefines += MacroName.str();
655 SuggestedPredefines += '\n';
656 } else {
657 SuggestedPredefines += "#define ";
658 SuggestedPredefines += MacroName.str();
659 SuggestedPredefines += ' ';
660 SuggestedPredefines += Existing.first.str();
661 SuggestedPredefines += '\n';
662 }
663 continue;
664 }
665
666 // If the macro was defined in one but undef'd in the other, we have a
667 // conflict.
668 if (Existing.second != Known->second.second) {
669 if (Diags) {
670 Diags->Report(diag::err_pch_macro_def_undef)
671 << MacroName << Known->second.second;
672 }
673 return true;
674 }
675
676 // If the macro was #undef'd in both, or if the macro bodies are identical,
677 // it's fine.
678 if (Existing.second || Existing.first == Known->second.first)
679 continue;
680
681 // The macro bodies differ; complain.
682 if (Diags) {
683 Diags->Report(diag::err_pch_macro_def_conflict)
684 << MacroName << Known->second.first << Existing.first;
685 }
686 return true;
687 }
688
689 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000690 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 if (Diags) {
692 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
693 }
694 return true;
695 }
696
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000697 // Detailed record is important since it is used for the module cache hash.
698 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000699 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000700 if (Diags) {
701 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
702 }
703 return true;
704 }
705
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000707 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
708 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000709
710 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
711 !ExistingPPOpts.PCHThroughHeader.empty()) {
712 // In case the through header is an include, we must add all the includes
713 // to the predefines so the start point can be determined.
714 SuggestedPredefines += "#include \"";
715 SuggestedPredefines += File;
716 SuggestedPredefines += "\"\n";
717 continue;
718 }
719
Guy Benyei11169dd2012-12-18 14:30:41 +0000720 if (File == ExistingPPOpts.ImplicitPCHInclude)
721 continue;
722
723 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
724 != PPOpts.Includes.end())
725 continue;
726
727 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000728 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 SuggestedPredefines += "\"\n";
730 }
731
Vedant Kumar48b4f762018-04-14 01:40:48 +0000732 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
733 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
735 File)
736 != PPOpts.MacroIncludes.end())
737 continue;
738
739 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000740 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 SuggestedPredefines += "\"\n##\n";
742 }
743
744 return false;
745}
746
747bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
748 bool Complain,
749 std::string &SuggestedPredefines) {
750 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
751
752 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000753 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000755 SuggestedPredefines,
756 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000757}
758
Yaxun Liu43712e02016-09-07 18:40:20 +0000759bool SimpleASTReaderListener::ReadPreprocessorOptions(
760 const PreprocessorOptions &PPOpts,
761 bool Complain,
762 std::string &SuggestedPredefines) {
763 return checkPreprocessorOptions(PPOpts,
764 PP.getPreprocessorOpts(),
765 nullptr,
766 PP.getFileManager(),
767 SuggestedPredefines,
768 PP.getLangOpts(),
769 false);
770}
771
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000772/// Check the header search options deserialized from the control block
773/// against the header search options in an existing preprocessor.
774///
775/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
776static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
777 StringRef SpecificModuleCachePath,
778 StringRef ExistingModuleCachePath,
779 DiagnosticsEngine *Diags,
780 const LangOptions &LangOpts) {
781 if (LangOpts.Modules) {
782 if (SpecificModuleCachePath != ExistingModuleCachePath) {
783 if (Diags)
784 Diags->Report(diag::err_pch_modulecache_mismatch)
785 << SpecificModuleCachePath << ExistingModuleCachePath;
786 return true;
787 }
788 }
789
790 return false;
791}
792
793bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
794 StringRef SpecificModuleCachePath,
795 bool Complain) {
796 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
797 PP.getHeaderSearchInfo().getModuleCachePath(),
798 Complain ? &Reader.Diags : nullptr,
799 PP.getLangOpts());
800}
801
Guy Benyei11169dd2012-12-18 14:30:41 +0000802void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
803 PP.setCounterValue(Value);
804}
805
806//===----------------------------------------------------------------------===//
807// AST reader implementation
808//===----------------------------------------------------------------------===//
809
Nico Weber824285e2014-05-08 04:26:47 +0000810void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
811 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000813 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000814}
815
Guy Benyei11169dd2012-12-18 14:30:41 +0000816unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
817 return serialization::ComputeHash(Sel);
818}
819
Guy Benyei11169dd2012-12-18 14:30:41 +0000820std::pair<unsigned, unsigned>
821ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000822 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000823
Justin Bogner57ba0b22014-03-28 22:03:24 +0000824 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
825 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 return std::make_pair(KeyLen, DataLen);
827}
828
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000829ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000830ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000831 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000832
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000834 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
835 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
836 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 if (N == 0)
838 return SelTable.getNullarySelector(FirstII);
839 else if (N == 1)
840 return SelTable.getUnarySelector(FirstII);
841
842 SmallVector<IdentifierInfo *, 16> Args;
843 Args.push_back(FirstII);
844 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000845 Args.push_back(Reader.getLocalIdentifier(
846 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000847
848 return SelTable.getSelector(N, Args.data());
849}
850
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000851ASTSelectorLookupTrait::data_type
852ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000853 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000854 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000855
856 data_type Result;
857
Justin Bogner57ba0b22014-03-28 22:03:24 +0000858 Result.ID = Reader.getGlobalSelectorID(
859 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000860 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
861 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
862 Result.InstanceBits = FullInstanceBits & 0x3;
863 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
864 Result.FactoryBits = FullFactoryBits & 0x3;
865 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
866 unsigned NumInstanceMethods = FullInstanceBits >> 3;
867 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000868
869 // Load instance methods
870 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000871 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000872 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000873 Result.Instance.push_back(Method);
874 }
875
876 // Load factory methods
877 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000878 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000879 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000880 Result.Factory.push_back(Method);
881 }
882
883 return Result;
884}
885
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000886unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000887 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000888}
889
890std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000891ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000892 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000893
Justin Bogner57ba0b22014-03-28 22:03:24 +0000894 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
895 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 return std::make_pair(KeyLen, DataLen);
897}
898
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000899ASTIdentifierLookupTraitBase::internal_key_type
900ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000901 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000902 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000903}
904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000905/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000906static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
907 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000908 return II.hadMacroDefinition() ||
909 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000910 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000911 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000912 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000913 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000914}
915
Richard Smith76c2f2c2015-07-17 20:09:43 +0000916static bool readBit(unsigned &Bits) {
917 bool Value = Bits & 0x1;
918 Bits >>= 1;
919 return Value;
920}
921
Richard Smith79bf9202015-08-24 03:33:22 +0000922IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
923 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000924
Richard Smith79bf9202015-08-24 03:33:22 +0000925 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
926 return Reader.getGlobalIdentifierID(F, RawID >> 1);
927}
928
Richard Smitheb4b58f62016-02-05 01:40:54 +0000929static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
930 if (!II.isFromAST()) {
931 II.setIsFromAST();
932 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
933 if (isInterestingIdentifier(Reader, II, IsModule))
934 II.setChangedSinceDeserialization();
935 }
936}
937
Guy Benyei11169dd2012-12-18 14:30:41 +0000938IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
939 const unsigned char* d,
940 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000942
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 bool IsInteresting = RawID & 0x01;
945
946 // Wipe out the "is interesting" bit.
947 RawID = RawID >> 1;
948
Richard Smith76c2f2c2015-07-17 20:09:43 +0000949 // Build the IdentifierInfo and link the identifier ID with it.
950 IdentifierInfo *II = KnownII;
951 if (!II) {
952 II = &Reader.getIdentifierTable().getOwn(k);
953 KnownII = II;
954 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000955 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000956 Reader.markIdentifierUpToDate(II);
957
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
959 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000960 // For uninteresting identifiers, there's nothing else to do. Just notify
961 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 return II;
964 }
965
Justin Bogner57ba0b22014-03-28 22:03:24 +0000966 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
967 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000968 bool CPlusPlusOperatorKeyword = readBit(Bits);
969 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000970 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000971 bool Poisoned = readBit(Bits);
972 bool ExtensionToken = readBit(Bits);
973 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000974
975 assert(Bits == 0 && "Extra bits in the identifier?");
976 DataLen -= 8;
977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 // Set or check the various bits in the IdentifierInfo structure.
979 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000980 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000981 II->revertTokenIDToIdentifier();
982 if (!F.isModule())
983 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
984 else if (HasRevertedBuiltin && II->getBuiltinID()) {
985 II->revertBuiltin();
986 assert((II->hasRevertedBuiltin() ||
987 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
988 "Incorrect ObjC keyword or builtin ID");
989 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 assert(II->isExtensionToken() == ExtensionToken &&
991 "Incorrect extension token flag");
992 (void)ExtensionToken;
993 if (Poisoned)
994 II->setIsPoisoned(true);
995 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
996 "Incorrect C++ operator keyword flag");
997 (void)CPlusPlusOperatorKeyword;
998
999 // If this identifier is a macro, deserialize the macro
1000 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +00001001 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001002 uint32_t MacroDirectivesOffset =
1003 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001004 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001005
Richard Smithd7329392015-04-21 21:46:32 +00001006 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001007 }
1008
1009 Reader.SetIdentifierInfo(ID, II);
1010
1011 // Read all of the declarations visible at global scope with this
1012 // name.
1013 if (DataLen > 0) {
1014 SmallVector<uint32_t, 4> DeclIDs;
1015 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001016 DeclIDs.push_back(Reader.getGlobalDeclID(
1017 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1019 }
1020
1021 return II;
1022}
1023
Richard Smitha06c7e62015-08-26 23:55:49 +00001024DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1025 : Kind(Name.getNameKind()) {
1026 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001028 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 break;
1030 case DeclarationName::ObjCZeroArgSelector:
1031 case DeclarationName::ObjCOneArgSelector:
1032 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001033 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 break;
1035 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001036 Data = Name.getCXXOverloadedOperator();
1037 break;
1038 case DeclarationName::CXXLiteralOperatorName:
1039 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1040 break;
Richard Smith35845152017-02-07 01:37:30 +00001041 case DeclarationName::CXXDeductionGuideName:
1042 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1043 ->getDeclName().getAsIdentifierInfo();
1044 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001045 case DeclarationName::CXXConstructorName:
1046 case DeclarationName::CXXDestructorName:
1047 case DeclarationName::CXXConversionFunctionName:
1048 case DeclarationName::CXXUsingDirective:
1049 Data = 0;
1050 break;
1051 }
1052}
1053
1054unsigned DeclarationNameKey::getHash() const {
1055 llvm::FoldingSetNodeID ID;
1056 ID.AddInteger(Kind);
1057
1058 switch (Kind) {
1059 case DeclarationName::Identifier:
1060 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001061 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001062 ID.AddString(((IdentifierInfo*)Data)->getName());
1063 break;
1064 case DeclarationName::ObjCZeroArgSelector:
1065 case DeclarationName::ObjCOneArgSelector:
1066 case DeclarationName::ObjCMultiArgSelector:
1067 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1068 break;
1069 case DeclarationName::CXXOperatorName:
1070 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 break;
1072 case DeclarationName::CXXConstructorName:
1073 case DeclarationName::CXXDestructorName:
1074 case DeclarationName::CXXConversionFunctionName:
1075 case DeclarationName::CXXUsingDirective:
1076 break;
1077 }
1078
1079 return ID.ComputeHash();
1080}
1081
Richard Smithd88a7f12015-09-01 20:35:42 +00001082ModuleFile *
1083ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1084 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001085
Richard Smithd88a7f12015-09-01 20:35:42 +00001086 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1087 return Reader.getLocalModuleFile(F, ModuleFileID);
1088}
1089
Guy Benyei11169dd2012-12-18 14:30:41 +00001090std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001091ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001092 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001093
Justin Bogner57ba0b22014-03-28 22:03:24 +00001094 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1095 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 return std::make_pair(KeyLen, DataLen);
1097}
1098
Richard Smitha06c7e62015-08-26 23:55:49 +00001099ASTDeclContextNameLookupTrait::internal_key_type
1100ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001101 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
Vedant Kumar48b4f762018-04-14 01:40:48 +00001103 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001104 uint64_t Data;
1105 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001107 case DeclarationName::CXXLiteralOperatorName:
1108 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001109 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001110 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 break;
1112 case DeclarationName::ObjCZeroArgSelector:
1113 case DeclarationName::ObjCOneArgSelector:
1114 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001115 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001116 (uint64_t)Reader.getLocalSelector(
1117 F, endian::readNext<uint32_t, little, unaligned>(
1118 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 break;
1120 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001121 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 case DeclarationName::CXXConstructorName:
1124 case DeclarationName::CXXDestructorName:
1125 case DeclarationName::CXXConversionFunctionName:
1126 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001127 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001128 break;
1129 }
1130
Richard Smitha06c7e62015-08-26 23:55:49 +00001131 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001132}
1133
Richard Smithd88a7f12015-09-01 20:35:42 +00001134void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1135 const unsigned char *d,
1136 unsigned DataLen,
1137 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001138 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001139
Richard Smithd88a7f12015-09-01 20:35:42 +00001140 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1141 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1142 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1143 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001144}
1145
Richard Smith0f4e2c42015-08-06 04:23:48 +00001146bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1147 BitstreamCursor &Cursor,
1148 uint64_t Offset,
1149 DeclContext *DC) {
1150 assert(Offset != 0);
1151
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001153 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1154 Error(std::move(Err));
1155 return true;
1156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001157
Richard Smith0f4e2c42015-08-06 04:23:48 +00001158 RecordData Record;
1159 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001160 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1161 if (!MaybeCode) {
1162 Error(MaybeCode.takeError());
1163 return true;
1164 }
1165 unsigned Code = MaybeCode.get();
1166
1167 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1168 if (!MaybeRecCode) {
1169 Error(MaybeRecCode.takeError());
1170 return true;
1171 }
1172 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001173 if (RecCode != DECL_CONTEXT_LEXICAL) {
1174 Error("Expected lexical block");
1175 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 }
1177
Richard Smith82f8fcd2015-08-06 22:07:25 +00001178 assert(!isa<TranslationUnitDecl>(DC) &&
1179 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001180 // If we are handling a C++ class template instantiation, we can see multiple
1181 // lexical updates for the same record. It's important that we select only one
1182 // of them, so that field numbering works properly. Just pick the first one we
1183 // see.
1184 auto &Lex = LexicalDecls[DC];
1185 if (!Lex.first) {
1186 Lex = std::make_pair(
1187 &M, llvm::makeArrayRef(
1188 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1189 Blob.data()),
1190 Blob.size() / 4));
1191 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001192 DC->setHasExternalLexicalStorage(true);
1193 return false;
1194}
Guy Benyei11169dd2012-12-18 14:30:41 +00001195
Richard Smith0f4e2c42015-08-06 04:23:48 +00001196bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1197 BitstreamCursor &Cursor,
1198 uint64_t Offset,
1199 DeclID ID) {
1200 assert(Offset != 0);
1201
1202 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001203 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1204 Error(std::move(Err));
1205 return true;
1206 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001207
1208 RecordData Record;
1209 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001210 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1211 if (!MaybeCode) {
1212 Error(MaybeCode.takeError());
1213 return true;
1214 }
1215 unsigned Code = MaybeCode.get();
1216
1217 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1218 if (!MaybeRecCode) {
1219 Error(MaybeRecCode.takeError());
1220 return true;
1221 }
1222 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001223 if (RecCode != DECL_CONTEXT_VISIBLE) {
1224 Error("Expected visible lookup table block");
1225 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 }
1227
Richard Smith0f4e2c42015-08-06 04:23:48 +00001228 // We can't safely determine the primary context yet, so delay attaching the
1229 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001230 auto *Data = (const unsigned char*)Blob.data();
1231 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 return false;
1233}
1234
Richard Smith37a93df2017-02-18 00:32:02 +00001235void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001236 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001237 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001238 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001239 Diag(diag::note_module_cache_path)
1240 << PP.getHeaderSearchInfo().getModuleCachePath();
1241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001242}
1243
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001244void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1245 StringRef Arg3) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 if (Diags.isDiagnosticInFlight())
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001247 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 else
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001249 Diag(DiagID) << Arg1 << Arg2 << Arg3;
Guy Benyei11169dd2012-12-18 14:30:41 +00001250}
1251
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001252void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1253 unsigned Select) const {
1254 if (!Diags.isDiagnosticInFlight())
1255 Diag(DiagID) << Arg1 << Arg2 << Select;
1256}
1257
JF Bastien0e828952019-06-26 19:50:12 +00001258void ASTReader::Error(llvm::Error &&Err) const {
1259 Error(toString(std::move(Err)));
1260}
1261
Guy Benyei11169dd2012-12-18 14:30:41 +00001262//===----------------------------------------------------------------------===//
1263// Source Manager Deserialization
1264//===----------------------------------------------------------------------===//
1265
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001266/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001267/// \returns true if there was an error.
1268bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001269 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 unsigned Idx = 0;
1271 LineTableInfo &LineTable = SourceMgr.getLineTable();
1272
1273 // Parse the file names
1274 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001275 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001276 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001278 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1280 }
Richard Smith63078492015-09-01 07:41:55 +00001281 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001282
1283 // Parse the line entries
1284 std::vector<LineEntry> Entries;
1285 while (Idx < Record.size()) {
1286 int FID = Record[Idx++];
1287 assert(FID >= 0 && "Serialized line entries for non-local file.");
1288 // Remap FileID from 1-based old view.
1289 FID += F.SLocEntryBaseID - 1;
1290
1291 // Extract the line entries
1292 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001293 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 Entries.clear();
1295 Entries.reserve(NumEntries);
1296 for (unsigned I = 0; I != NumEntries; ++I) {
1297 unsigned FileOffset = Record[Idx++];
1298 unsigned LineNo = Record[Idx++];
1299 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001300 SrcMgr::CharacteristicKind FileKind
1301 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 unsigned IncludeOffset = Record[Idx++];
1303 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1304 FileKind, IncludeOffset));
1305 }
1306 LineTable.AddEntry(FileID::get(FID), Entries);
1307 }
1308
1309 return false;
1310}
1311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001312/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001313bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1314 using namespace SrcMgr;
1315
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001316 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001317
1318 // Set the source-location entry cursor to the current position in
1319 // the stream. This cursor will be used to read the contents of the
1320 // source manager block initially, and then lazily read
1321 // source-location entries as needed.
1322 SLocEntryCursor = F.Stream;
1323
1324 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001325 if (llvm::Error Err = F.Stream.SkipBlock()) {
1326 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 return true;
1328 }
1329
1330 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001331 if (llvm::Error Err =
1332 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1333 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001334 return true;
1335 }
1336
1337 RecordData Record;
1338 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001339 Expected<llvm::BitstreamEntry> MaybeE =
1340 SLocEntryCursor.advanceSkippingSubblocks();
1341 if (!MaybeE) {
1342 Error(MaybeE.takeError());
1343 return true;
1344 }
1345 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001346
Chris Lattnere7b154b2013-01-19 21:39:22 +00001347 switch (E.Kind) {
1348 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1349 case llvm::BitstreamEntry::Error:
1350 Error("malformed block record in AST file");
1351 return true;
1352 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001354 case llvm::BitstreamEntry::Record:
1355 // The interesting case.
1356 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001361 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001362 Expected<unsigned> MaybeRecord =
1363 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1364 if (!MaybeRecord) {
1365 Error(MaybeRecord.takeError());
1366 return true;
1367 }
1368 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 default: // Default behavior: ignore.
1370 break;
1371
1372 case SM_SLOC_FILE_ENTRY:
1373 case SM_SLOC_BUFFER_ENTRY:
1374 case SM_SLOC_EXPANSION_ENTRY:
1375 // Once we hit one of the source location entries, we're done.
1376 return false;
1377 }
1378 }
1379}
1380
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001381/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001382/// and the PCH file was moved from its original location, try to resolve the
1383/// file by assuming that header+PCH were moved together and the header is in
1384/// the same place relative to the PCH.
1385static std::string
1386resolveFileRelativeToOriginalDir(const std::string &Filename,
1387 const std::string &OriginalDir,
1388 const std::string &CurrDir) {
1389 assert(OriginalDir != CurrDir &&
1390 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001391
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 SmallString<128> filePath(Filename);
1395 fs::make_absolute(filePath);
1396 assert(path::is_absolute(OriginalDir));
1397 SmallString<128> currPCHPath(CurrDir);
1398
1399 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1400 fileDirE = path::end(path::parent_path(filePath));
1401 path::const_iterator origDirI = path::begin(OriginalDir),
1402 origDirE = path::end(OriginalDir);
1403 // Skip the common path components from filePath and OriginalDir.
1404 while (fileDirI != fileDirE && origDirI != origDirE &&
1405 *fileDirI == *origDirI) {
1406 ++fileDirI;
1407 ++origDirI;
1408 }
1409 for (; origDirI != origDirE; ++origDirI)
1410 path::append(currPCHPath, "..");
1411 path::append(currPCHPath, fileDirI, fileDirE);
1412 path::append(currPCHPath, path::filename(Filename));
1413 return currPCHPath.str();
1414}
1415
1416bool ASTReader::ReadSLocEntry(int ID) {
1417 if (ID == 0)
1418 return false;
1419
1420 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1421 Error("source location entry ID out-of-range for AST file");
1422 return true;
1423 }
1424
Richard Smithaada85c2016-02-06 02:06:43 +00001425 // Local helper to read the (possibly-compressed) buffer data following the
1426 // entry record.
1427 auto ReadBuffer = [this](
1428 BitstreamCursor &SLocEntryCursor,
1429 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1430 RecordData Record;
1431 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001432 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1433 if (!MaybeCode) {
1434 Error(MaybeCode.takeError());
1435 return nullptr;
1436 }
1437 unsigned Code = MaybeCode.get();
1438
1439 Expected<unsigned> MaybeRecCode =
1440 SLocEntryCursor.readRecord(Code, Record, &Blob);
1441 if (!MaybeRecCode) {
1442 Error(MaybeRecCode.takeError());
1443 return nullptr;
1444 }
1445 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001446
1447 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001448 if (!llvm::zlib::isAvailable()) {
1449 Error("zlib is not available");
1450 return nullptr;
1451 }
Richard Smithaada85c2016-02-06 02:06:43 +00001452 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001453 if (llvm::Error E =
1454 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1455 Error("could not decompress embedded file contents: " +
1456 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001457 return nullptr;
1458 }
1459 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1460 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1461 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1462 } else {
1463 Error("AST record has invalid code");
1464 return nullptr;
1465 }
1466 };
1467
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001469 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1470 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1471 Error(std::move(Err));
1472 return true;
1473 }
1474
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001475 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001476 unsigned BaseOffset = F->SLocEntryBaseOffset;
1477
1478 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001479 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1480 if (!MaybeEntry) {
1481 Error(MaybeEntry.takeError());
1482 return true;
1483 }
1484 llvm::BitstreamEntry Entry = MaybeEntry.get();
1485
Chris Lattnere7b154b2013-01-19 21:39:22 +00001486 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001487 Error("incorrectly-formatted source location entry in AST file");
1488 return true;
1489 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001490
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001492 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001493 Expected<unsigned> MaybeSLOC =
1494 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1495 if (!MaybeSLOC) {
1496 Error(MaybeSLOC.takeError());
1497 return true;
1498 }
1499 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 default:
1501 Error("incorrectly-formatted source location entry in AST file");
1502 return true;
1503
1504 case SM_SLOC_FILE_ENTRY: {
1505 // We will detect whether a file changed and return 'Failure' for it, but
1506 // we will also try to fail gracefully by setting up the SLocEntry.
1507 unsigned InputID = Record[4];
1508 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001509 const FileEntry *File = IF.getFile();
1510 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001511
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001512 // Note that we only check if a File was returned. If it was out-of-date
1513 // we have complained but we will continue creating a FileID to recover
1514 // gracefully.
1515 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 return true;
1517
1518 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1519 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1520 // This is the module's main file.
1521 IncludeLoc = getImportLocation(F);
1522 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001523 SrcMgr::CharacteristicKind
1524 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001525 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1527 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001528 SrcMgr::FileInfo &FileInfo =
1529 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 FileInfo.NumCreatedFIDs = Record[5];
1531 if (Record[3])
1532 FileInfo.setHasLineDirectives();
1533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001535 if (NumFileDecls && ContextObj) {
Roman Lebedevbf4f1e02019-10-10 12:22:42 +00001536 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1538 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1539 NumFileDecls));
1540 }
Richard Smithaada85c2016-02-06 02:06:43 +00001541
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001543 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001545 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1546 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001547 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1548 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001550 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 }
1552
1553 break;
1554 }
1555
1556 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001557 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001559 SrcMgr::CharacteristicKind
1560 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001562 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 IncludeLoc = getImportLocation(F);
1564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001565
Richard Smithaada85c2016-02-06 02:06:43 +00001566 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1567 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001568 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001569 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001570 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 break;
1572 }
1573
1574 case SM_SLOC_EXPANSION_ENTRY: {
1575 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1576 SourceMgr.createExpansionLoc(SpellingLoc,
1577 ReadSourceLocation(*F, Record[2]),
1578 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001579 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 Record[4],
1581 ID,
1582 BaseOffset + Record[0]);
1583 break;
1584 }
1585 }
1586
1587 return false;
1588}
1589
1590std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1591 if (ID == 0)
1592 return std::make_pair(SourceLocation(), "");
1593
1594 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1595 Error("source location entry ID out-of-range for AST file");
1596 return std::make_pair(SourceLocation(), "");
1597 }
1598
1599 // Find which module file this entry lands in.
1600 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001601 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 return std::make_pair(SourceLocation(), "");
1603
1604 // FIXME: Can we map this down to a particular submodule? That would be
1605 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001606 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001607}
1608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001609/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001610SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1611 if (F->ImportLoc.isValid())
1612 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 // Otherwise we have a PCH. It's considered to be "imported" at the first
1615 // location of its includer.
1616 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001617 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001618 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001619 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 return F->ImportedBy[0]->FirstLoc;
1622}
1623
JF Bastien0e828952019-06-26 19:50:12 +00001624/// Enter a subblock of the specified BlockID with the specified cursor. Read
1625/// the abbreviations that are at the top of the block and then leave the cursor
1626/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001627bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001628 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1629 // FIXME this drops errors on the floor.
1630 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001631 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001632 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001633
1634 while (true) {
1635 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001636 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1637 if (!MaybeCode) {
1638 // FIXME this drops errors on the floor.
1639 consumeError(MaybeCode.takeError());
1640 return true;
1641 }
1642 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001643
1644 // We expect all abbrevs to be at the start of the block.
1645 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001646 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1647 // FIXME this drops errors on the floor.
1648 consumeError(std::move(Err));
1649 return true;
1650 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 return false;
1652 }
JF Bastien0e828952019-06-26 19:50:12 +00001653 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1654 // FIXME this drops errors on the floor.
1655 consumeError(std::move(Err));
1656 return true;
1657 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 }
1659}
1660
Richard Smithe40f2ba2013-08-07 21:41:30 +00001661Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001662 unsigned &Idx) {
1663 Token Tok;
1664 Tok.startToken();
1665 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1666 Tok.setLength(Record[Idx++]);
1667 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1668 Tok.setIdentifierInfo(II);
1669 Tok.setKind((tok::TokenKind)Record[Idx++]);
1670 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1671 return Tok;
1672}
1673
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001674MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001675 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001676
1677 // Keep track of where we are in the stream, then jump back there
1678 // after reading this macro.
1679 SavedStreamPosition SavedPosition(Stream);
1680
JF Bastien0e828952019-06-26 19:50:12 +00001681 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1682 // FIXME this drops errors on the floor.
1683 consumeError(std::move(Err));
1684 return nullptr;
1685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001687 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001688 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001689
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001691 // Advance to the next record, but if we get to the end of the block, don't
1692 // pop it (removing all the abbreviations from the cursor) since we want to
1693 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001694 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001695 Expected<llvm::BitstreamEntry> MaybeEntry =
1696 Stream.advanceSkippingSubblocks(Flags);
1697 if (!MaybeEntry) {
1698 Error(MaybeEntry.takeError());
1699 return Macro;
1700 }
1701 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001702
Chris Lattnerefa77172013-01-20 00:00:22 +00001703 switch (Entry.Kind) {
1704 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1705 case llvm::BitstreamEntry::Error:
1706 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001707 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001708 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001709 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001710 case llvm::BitstreamEntry::Record:
1711 // The interesting case.
1712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 }
1714
1715 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001717 PreprocessorRecordTypes RecType;
1718 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1719 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1720 else {
1721 Error(MaybeRecType.takeError());
1722 return Macro;
1723 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001725 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001726 case PP_MACRO_DIRECTIVE_HISTORY:
1727 return Macro;
1728
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 case PP_MACRO_OBJECT_LIKE:
1730 case PP_MACRO_FUNCTION_LIKE: {
1731 // If we already have a macro, that means that we've hit the end
1732 // of the definition of the macro we were looking for. We're
1733 // done.
1734 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001735 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001736
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001737 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001738 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001739 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001740 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001742 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001743
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1745 // Decode function-like macro info.
1746 bool isC99VarArgs = Record[NextIndex++];
1747 bool isGNUVarArgs = Record[NextIndex++];
1748 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001749 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001750 unsigned NumArgs = Record[NextIndex++];
1751 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001752 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001753
1754 // Install function-like macro info.
1755 MI->setIsFunctionLike();
1756 if (isC99VarArgs) MI->setIsC99Varargs();
1757 if (isGNUVarArgs) MI->setIsGNUVarargs();
1758 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001759 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 }
1761
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 // Remember that we saw this macro last so that we add the tokens that
1763 // form its body to it.
1764 Macro = MI;
1765
1766 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1767 Record[NextIndex]) {
1768 // We have a macro definition. Register the association
1769 PreprocessedEntityID
1770 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1771 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001772 PreprocessingRecord::PPEntityID PPID =
1773 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001774 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001775 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001776 if (PPDef)
1777 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001778 }
1779
1780 ++NumMacrosRead;
1781 break;
1782 }
1783
1784 case PP_TOKEN: {
1785 // If we see a TOKEN before a PP_MACRO_*, then the file is
1786 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001787 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001788
John McCallf413f5e2013-05-03 00:10:13 +00001789 unsigned Idx = 0;
1790 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 Macro->AddTokenToBody(Tok);
1792 break;
1793 }
1794 }
1795 }
1796}
1797
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001798PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001799ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1800 unsigned LocalID) const {
1801 if (!M.ModuleOffsetMap.empty())
1802 ReadModuleOffsetMap(M);
1803
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001804 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001806 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001808
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 return LocalID + I->second;
1810}
1811
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001812unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1813 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001814}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001815
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001816HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001817HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001818 internal_key_type ikey = {FE->getSize(),
1819 M.HasTimestamps ? FE->getModificationTime() : 0,
1820 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001821 return ikey;
1822}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001823
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001824bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001825 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001826 return false;
1827
Mehdi Amini004b9c72016-10-10 22:52:47 +00001828 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001829 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001830
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001832 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001833 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001834 if (!Key.Imported) {
1835 if (auto File = FileMgr.getFile(Key.Filename))
1836 return *File;
1837 return nullptr;
1838 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001839
1840 std::string Resolved = Key.Filename;
1841 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001842 if (auto File = FileMgr.getFile(Resolved))
1843 return *File;
1844 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001845 };
1846
1847 const FileEntry *FEA = GetFile(a);
1848 const FileEntry *FEB = GetFile(b);
1849 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001850}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001851
Guy Benyei11169dd2012-12-18 14:30:41 +00001852std::pair<unsigned, unsigned>
1853HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001854 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001855
Vedant Kumar48b4f762018-04-14 01:40:48 +00001856 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1857 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001858 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001859}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001860
1861HeaderFileInfoTrait::internal_key_type
1862HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001863 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001864
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001865 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001866 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1867 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001868 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001869 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001870 return ikey;
1871}
1872
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001873HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001874HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001876 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001877
1878 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 HeaderFileInfo HFI;
1880 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001881 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001882 HFI.isImport |= (Flags >> 5) & 0x01;
1883 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1884 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001886 // FIXME: Find a better way to handle this. Maybe just store a
1887 // "has been included" flag?
1888 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1889 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001890 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1891 M, endian::readNext<uint32_t, little, unaligned>(d));
1892 if (unsigned FrameworkOffset =
1893 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001894 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 // since 0 is used as an indicator for "no framework name".
1896 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1897 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1898 }
Richard Smith386bb072015-08-18 23:42:23 +00001899
1900 assert((End - d) % 4 == 0 &&
1901 "Wrong data length in HeaderFileInfo deserialization");
1902 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001903 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001904 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1905 LocalSMID >>= 2;
1906
1907 // This header is part of a module. Associate it with the module to enable
1908 // implicit module import.
1909 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1910 Module *Mod = Reader.getSubmodule(GlobalSMID);
1911 FileManager &FileMgr = Reader.getFileManager();
1912 ModuleMap &ModMap =
1913 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1914
1915 std::string Filename = key.Filename;
1916 if (key.Imported)
1917 Reader.ResolveImportedPath(M, Filename);
1918 // FIXME: This is not always the right filename-as-written, but we're not
1919 // going to use this information to rebuild the module, so it doesn't make
1920 // a lot of difference.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001921 Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001922 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1923 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001924 }
1925
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 // This HeaderFileInfo was externally loaded.
1927 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001928 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 return HFI;
1930}
1931
Richard Smithd7329392015-04-21 21:46:32 +00001932void ASTReader::addPendingMacro(IdentifierInfo *II,
1933 ModuleFile *M,
1934 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001935 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1936 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001937}
1938
1939void ASTReader::ReadDefinedMacros() {
1940 // Note that we are loading defined macros.
1941 Deserializing Macros(this);
1942
Vedant Kumar48b4f762018-04-14 01:40:48 +00001943 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001944 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001945
1946 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001947 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001948 continue;
1949
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001950 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001951 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1952 Error(std::move(Err));
1953 return;
1954 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001955
1956 RecordData Record;
1957 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001958 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1959 if (!MaybeE) {
1960 Error(MaybeE.takeError());
1961 return;
1962 }
1963 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001964
Chris Lattnere7b154b2013-01-19 21:39:22 +00001965 switch (E.Kind) {
1966 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1967 case llvm::BitstreamEntry::Error:
1968 Error("malformed block record in AST file");
1969 return;
1970 case llvm::BitstreamEntry::EndBlock:
1971 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001972
JF Bastien0e828952019-06-26 19:50:12 +00001973 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001974 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001975 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1976 if (!MaybeRecord) {
1977 Error(MaybeRecord.takeError());
1978 return;
1979 }
1980 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001981 default: // Default behavior: ignore.
1982 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001983
Chris Lattnere7b154b2013-01-19 21:39:22 +00001984 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001985 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001986 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001987 if (II->isOutOfDate())
1988 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001989 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001990 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001991
Chris Lattnere7b154b2013-01-19 21:39:22 +00001992 case PP_TOKEN:
1993 // Ignore tokens.
1994 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 break;
1997 }
JF Bastien0e828952019-06-26 19:50:12 +00001998 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002000 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 }
2002}
2003
2004namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002005
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002006 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 class IdentifierLookupVisitor {
2008 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002009 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002011 unsigned &NumIdentifierLookups;
2012 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002013 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002014
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002016 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2017 unsigned &NumIdentifierLookups,
2018 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002019 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2020 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002021 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002022 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002023
2024 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002025 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002026 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002028
Vedant Kumar48b4f762018-04-14 01:40:48 +00002029 ASTIdentifierLookupTable *IdTable
2030 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 if (!IdTable)
2032 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002033
2034 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002035 Found);
2036 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002037 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002038 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 if (Pos == IdTable->end())
2040 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002041
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 // Dereferencing the iterator has the effect of building the
2043 // IdentifierInfo node and populating it with the various
2044 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002045 ++NumIdentifierLookupHits;
2046 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 return true;
2048 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002050 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 // files.
2052 IdentifierInfo *getIdentifierInfo() const { return Found; }
2053 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002054
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002055} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002056
2057void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2058 // Note that we are loading an identifier.
2059 Deserializing AnIdentifier(this);
2060
2061 unsigned PriorGeneration = 0;
2062 if (getContext().getLangOpts().Modules)
2063 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002064
2065 // If there is a global index, look there first to determine which modules
2066 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002067 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002068 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002069 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002070 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2071 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002072 }
2073 }
2074
Douglas Gregor7211ac12013-01-25 23:32:03 +00002075 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002076 NumIdentifierLookups,
2077 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002078 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002079 markIdentifierUpToDate(&II);
2080}
2081
2082void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2083 if (!II)
2084 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002085
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 II->setOutOfDate(false);
2087
2088 // Update the generation for this identifier.
2089 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002090 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002091}
2092
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002093void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2094 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002095 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002096
2097 BitstreamCursor &Cursor = M.MacroCursor;
2098 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002099 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2100 Error(std::move(Err));
2101 return;
2102 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002103
Richard Smith713369b2015-04-23 20:40:50 +00002104 struct ModuleMacroRecord {
2105 SubmoduleID SubModID;
2106 MacroInfo *MI;
2107 SmallVector<SubmoduleID, 8> Overrides;
2108 };
2109 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002110
Richard Smithd7329392015-04-21 21:46:32 +00002111 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2112 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2113 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002114 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002115 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002116 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002117 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002118 if (!MaybeEntry) {
2119 Error(MaybeEntry.takeError());
2120 return;
2121 }
2122 llvm::BitstreamEntry Entry = MaybeEntry.get();
2123
Richard Smithd7329392015-04-21 21:46:32 +00002124 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2125 Error("malformed block record in AST file");
2126 return;
2127 }
2128
2129 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002130 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2131 if (!MaybePP) {
2132 Error(MaybePP.takeError());
2133 return;
2134 }
2135 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002136 case PP_MACRO_DIRECTIVE_HISTORY:
2137 break;
2138
2139 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002140 ModuleMacros.push_back(ModuleMacroRecord());
2141 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002142 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2143 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002144 for (int I = 2, N = Record.size(); I != N; ++I)
2145 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002146 continue;
2147 }
2148
2149 default:
2150 Error("malformed block record in AST file");
2151 return;
2152 }
2153
2154 // We found the macro directive history; that's the last record
2155 // for this macro.
2156 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002157 }
2158
Richard Smithd7329392015-04-21 21:46:32 +00002159 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002160 {
2161 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002162 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002163 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002164 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002165 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002166 Module *Mod = getSubmodule(ModID);
2167 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002168 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002169 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002170 }
2171
2172 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002173 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002174 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002175 }
2176 }
2177
2178 // Don't read the directive history for a module; we don't have anywhere
2179 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002180 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002181 return;
2182
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002183 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002184 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002185 unsigned Idx = 0, N = Record.size();
2186 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002187 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002188 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002189 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002190 switch (K) {
2191 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002192 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002193 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002194 break;
2195 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002196 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002197 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002198 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002199 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002200 bool isPublic = Record[Idx++];
2201 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2202 break;
2203 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002204
2205 if (!Latest)
2206 Latest = MD;
2207 if (Earliest)
2208 Earliest->setPrevious(MD);
2209 Earliest = MD;
2210 }
2211
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002212 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002213 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002214}
2215
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002216ASTReader::InputFileInfo
2217ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002218 // Go find this input file.
2219 BitstreamCursor &Cursor = F.InputFilesCursor;
2220 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002221 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2222 // FIXME this drops errors on the floor.
2223 consumeError(std::move(Err));
2224 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002225
JF Bastien0e828952019-06-26 19:50:12 +00002226 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2227 if (!MaybeCode) {
2228 // FIXME this drops errors on the floor.
2229 consumeError(MaybeCode.takeError());
2230 }
2231 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002232 RecordData Record;
2233 StringRef Blob;
2234
JF Bastien0e828952019-06-26 19:50:12 +00002235 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2236 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2237 "invalid record type for input file");
2238 else {
2239 // FIXME this drops errors on the floor.
2240 consumeError(Maybe.takeError());
2241 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002242
2243 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002244 InputFileInfo R;
2245 R.StoredSize = static_cast<off_t>(Record[1]);
2246 R.StoredTime = static_cast<time_t>(Record[2]);
2247 R.Overridden = static_cast<bool>(Record[3]);
2248 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002249 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002250 R.Filename = Blob;
2251 ResolveImportedPath(F, R.Filename);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002252
2253 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2254 if (!MaybeEntry) // FIXME this drops errors on the floor.
2255 consumeError(MaybeEntry.takeError());
2256 llvm::BitstreamEntry Entry = MaybeEntry.get();
2257 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2258 "expected record type for input file hash");
2259
2260 Record.clear();
2261 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2262 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2263 "invalid record type for input file hash");
2264 else {
2265 // FIXME this drops errors on the floor.
2266 consumeError(Maybe.takeError());
2267 }
2268 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2269 static_cast<uint64_t>(Record[0]);
Hans Wennborg73945142014-03-14 17:45:06 +00002270 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002271}
2272
Manman Renc8c94152016-10-21 23:35:03 +00002273static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002274InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 // If this ID is bogus, just return an empty input file.
2276 if (ID == 0 || ID > F.InputFilesLoaded.size())
2277 return InputFile();
2278
2279 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002280 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 return F.InputFilesLoaded[ID-1];
2282
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002283 if (F.InputFilesLoaded[ID-1].isNotFound())
2284 return InputFile();
2285
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002287 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002289 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2290 // FIXME this drops errors on the floor.
2291 consumeError(std::move(Err));
2292 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002293
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002294 InputFileInfo FI = readInputFileInfo(F, ID);
2295 off_t StoredSize = FI.StoredSize;
2296 time_t StoredTime = FI.StoredTime;
2297 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002298 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002299 StringRef Filename = FI.Filename;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002300 uint64_t StoredContentHash = FI.ContentHash;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002301
Harlan Haskins8d323d12019-08-01 21:31:56 +00002302 const FileEntry *File = nullptr;
2303 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2304 File = *FE;
2305
Ben Langmuir198c1682014-03-07 07:27:49 +00002306 // If we didn't find the file, resolve it relative to the
2307 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002308 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2309 F.OriginalDir != F.BaseDirectory) {
2310 std::string Resolved = resolveFileRelativeToOriginalDir(
2311 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002312 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002313 if (auto FE = FileMgr.getFile(Resolved))
2314 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002315 }
2316
2317 // For an overridden file, create a virtual file with the stored
2318 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002319 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002320 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002321
Craig Toppera13603a2014-05-22 05:54:18 +00002322 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002323 if (Complain) {
2324 std::string ErrorStr = "could not find file '";
2325 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002326 ErrorStr += "' referenced by AST file '";
2327 ErrorStr += F.FileName;
2328 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002329 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002331 // Record that we didn't find the file.
2332 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2333 return InputFile();
2334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002335
Ben Langmuir198c1682014-03-07 07:27:49 +00002336 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002337 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002338 // can lead to problems when lexing using the source locations from the
2339 // PCH.
2340 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002341 // FIXME: Reject if the overrides are different.
2342 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002343 if (Complain)
2344 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002345
2346 // After emitting the diagnostic, bypass the overriding file to recover
2347 // (this creates a separate FileEntry).
2348 File = SM.bypassFileContentsOverride(*File);
2349 if (!File) {
2350 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2351 return InputFile();
2352 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002353 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002354
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002355 enum ModificationType {
2356 Size,
2357 ModTime,
2358 Content,
2359 None,
2360 };
2361 auto HasInputFileChanged = [&]() {
2362 if (StoredSize != File->getSize())
2363 return ModificationType::Size;
2364 if (!DisableValidation && StoredTime &&
2365 StoredTime != File->getModificationTime()) {
2366 // In case the modification time changes but not the content,
2367 // accept the cached file as legit.
2368 if (ValidateASTInputFilesContent &&
2369 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2370 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2371 if (!MemBuffOrError) {
2372 if (!Complain)
2373 return ModificationType::ModTime;
2374 std::string ErrorStr = "could not get buffer for file '";
2375 ErrorStr += File->getName();
2376 ErrorStr += "'";
2377 Error(ErrorStr);
2378 return ModificationType::ModTime;
2379 }
Eric Christopher3be91692019-10-14 23:14:24 +00002380
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002381 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2382 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2383 return ModificationType::None;
2384 return ModificationType::Content;
2385 }
2386 return ModificationType::ModTime;
2387 }
2388 return ModificationType::None;
2389 };
2390
2391 bool IsOutOfDate = false;
2392 auto FileChange = HasInputFileChanged();
Ben Langmuir198c1682014-03-07 07:27:49 +00002393 // For an overridden file, there is nothing to validate.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002394 if (!Overridden && FileChange != ModificationType::None) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002395 if (Complain) {
2396 // Build a list of the PCH imports that got us here (in reverse).
2397 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002398 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002399 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002400
Ben Langmuir198c1682014-03-07 07:27:49 +00002401 // The top-level PCH is stale.
2402 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002403 unsigned DiagnosticKind =
2404 moduleKindForDiagnostic(ImportStack.back()->Kind);
Manman Renc8c94152016-10-21 23:35:03 +00002405 if (DiagnosticKind == 0)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002406 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2407 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002408 else if (DiagnosticKind == 1)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002409 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2410 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002411 else
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002412 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2413 (unsigned)FileChange);
Ben Langmuire82630d2014-01-17 00:19:09 +00002414
Ben Langmuir198c1682014-03-07 07:27:49 +00002415 // Print the import stack.
2416 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2417 Diag(diag::note_pch_required_by)
2418 << Filename << ImportStack[0]->FileName;
2419 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002420 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002421 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002422 }
2423
Ben Langmuir198c1682014-03-07 07:27:49 +00002424 if (!Diags.isDiagnosticInFlight())
2425 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 }
2427
Ben Langmuir198c1682014-03-07 07:27:49 +00002428 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002430 // FIXME: If the file is overridden and we've already opened it,
2431 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002432
Richard Smitha8cfffa2015-11-26 02:04:16 +00002433 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002434
2435 // Note that we've loaded this input file.
2436 F.InputFilesLoaded[ID-1] = IF;
2437 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002438}
2439
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002440/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002441/// is not an absolute path, add the system or module root to the beginning of
2442/// the file name.
2443void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2444 // Resolve relative to the base directory, if we have one.
2445 if (!M.BaseDirectory.empty())
2446 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002447}
2448
Richard Smith7ed1bc92014-12-05 22:42:13 +00002449void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2451 return;
2452
Richard Smith7ed1bc92014-12-05 22:42:13 +00002453 SmallString<128> Buffer;
2454 llvm::sys::path::append(Buffer, Prefix, Filename);
2455 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002456}
2457
Richard Smith0f99d6a2015-08-09 08:48:41 +00002458static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2459 switch (ARR) {
2460 case ASTReader::Failure: return true;
2461 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2462 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2463 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2464 case ASTReader::ConfigurationMismatch:
2465 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2466 case ASTReader::HadErrors: return true;
2467 case ASTReader::Success: return false;
2468 }
2469
2470 llvm_unreachable("unknown ASTReadResult");
2471}
2472
Richard Smith0516b182015-09-08 19:40:14 +00002473ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2474 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2475 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002476 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002477 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2478 // FIXME this drops errors on the floor.
2479 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002480 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002481 }
Richard Smith0516b182015-09-08 19:40:14 +00002482
2483 // Read all of the records in the options block.
2484 RecordData Record;
2485 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002486 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002487 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2488 if (!MaybeEntry) {
2489 // FIXME this drops errors on the floor.
2490 consumeError(MaybeEntry.takeError());
2491 return Failure;
2492 }
2493 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002494
Richard Smith0516b182015-09-08 19:40:14 +00002495 switch (Entry.Kind) {
2496 case llvm::BitstreamEntry::Error:
2497 case llvm::BitstreamEntry::SubBlock:
2498 return Failure;
2499
2500 case llvm::BitstreamEntry::EndBlock:
2501 return Result;
2502
2503 case llvm::BitstreamEntry::Record:
2504 // The interesting case.
2505 break;
2506 }
2507
2508 // Read and process a record.
2509 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002510 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2511 if (!MaybeRecordType) {
2512 // FIXME this drops errors on the floor.
2513 consumeError(MaybeRecordType.takeError());
2514 return Failure;
2515 }
2516 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002517 case LANGUAGE_OPTIONS: {
2518 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2519 if (ParseLanguageOptions(Record, Complain, Listener,
2520 AllowCompatibleConfigurationMismatch))
2521 Result = ConfigurationMismatch;
2522 break;
2523 }
2524
2525 case TARGET_OPTIONS: {
2526 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2527 if (ParseTargetOptions(Record, Complain, Listener,
2528 AllowCompatibleConfigurationMismatch))
2529 Result = ConfigurationMismatch;
2530 break;
2531 }
2532
Richard Smith0516b182015-09-08 19:40:14 +00002533 case FILE_SYSTEM_OPTIONS: {
2534 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2535 if (!AllowCompatibleConfigurationMismatch &&
2536 ParseFileSystemOptions(Record, Complain, Listener))
2537 Result = ConfigurationMismatch;
2538 break;
2539 }
2540
2541 case HEADER_SEARCH_OPTIONS: {
2542 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2543 if (!AllowCompatibleConfigurationMismatch &&
2544 ParseHeaderSearchOptions(Record, Complain, Listener))
2545 Result = ConfigurationMismatch;
2546 break;
2547 }
2548
2549 case PREPROCESSOR_OPTIONS:
2550 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2551 if (!AllowCompatibleConfigurationMismatch &&
2552 ParsePreprocessorOptions(Record, Complain, Listener,
2553 SuggestedPredefines))
2554 Result = ConfigurationMismatch;
2555 break;
2556 }
2557 }
2558}
2559
Guy Benyei11169dd2012-12-18 14:30:41 +00002560ASTReader::ASTReadResult
2561ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002562 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002563 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002565 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002566
JF Bastien0e828952019-06-26 19:50:12 +00002567 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2568 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 return Failure;
2570 }
2571
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002572 // Lambda to read the unhashed control block the first time it's called.
2573 //
2574 // For PCM files, the unhashed control block cannot be read until after the
2575 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2576 // need to look ahead before reading the IMPORTS record. For consistency,
2577 // this block is always read somehow (see BitstreamEntry::EndBlock).
2578 bool HasReadUnhashedControlBlock = false;
2579 auto readUnhashedControlBlockOnce = [&]() {
2580 if (!HasReadUnhashedControlBlock) {
2581 HasReadUnhashedControlBlock = true;
2582 if (ASTReadResult Result =
2583 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2584 return Result;
2585 }
2586 return Success;
2587 };
2588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 // Read all of the records and blocks in the control block.
2590 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002591 unsigned NumInputs = 0;
2592 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002593 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002594 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002595 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2596 if (!MaybeEntry) {
2597 Error(MaybeEntry.takeError());
2598 return Failure;
2599 }
2600 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002601
Chris Lattnere7b154b2013-01-19 21:39:22 +00002602 switch (Entry.Kind) {
2603 case llvm::BitstreamEntry::Error:
2604 Error("malformed block record in AST file");
2605 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002606 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002607 // Validate the module before returning. This call catches an AST with
2608 // no module name and no imports.
2609 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2610 return Result;
2611
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002612 // Validate input files.
2613 const HeaderSearchOptions &HSOpts =
2614 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002615
Richard Smitha1825302014-10-23 22:18:29 +00002616 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002617 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2618 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002619 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2620 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002622
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002623 // If we are reading a module, we will create a verification timestamp,
2624 // so we verify all input files. Otherwise, verify only user input
2625 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002626
2627 unsigned N = NumUserInputs;
2628 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002629 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002630 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002631 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002632 N = NumInputs;
2633
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002634 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002635 InputFile IF = getInputFile(F, I+1, Complain);
2636 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002638 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002640
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002641 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002642 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002643
Ben Langmuircb69b572014-03-07 06:40:32 +00002644 if (Listener && Listener->needsInputFileVisitation()) {
2645 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2646 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002647 for (unsigned I = 0; I < N; ++I) {
2648 bool IsSystem = I >= NumUserInputs;
2649 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002650 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002651 F.Kind == MK_ExplicitModule ||
2652 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002653 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002654 }
2655
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002656 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002657 }
2658
Chris Lattnere7b154b2013-01-19 21:39:22 +00002659 case llvm::BitstreamEntry::SubBlock:
2660 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 case INPUT_FILES_BLOCK_ID:
2662 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002663 if (llvm::Error Err = Stream.SkipBlock()) {
2664 Error(std::move(Err));
2665 return Failure;
2666 }
2667 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 Error("malformed block record in AST file");
2669 return Failure;
2670 }
2671 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002672
2673 case OPTIONS_BLOCK_ID:
2674 // If we're reading the first module for this group, check its options
2675 // are compatible with ours. For modules it imports, no further checking
2676 // is required, because we checked them when we built it.
2677 if (Listener && !ImportedBy) {
2678 // Should we allow the configuration of the module file to differ from
2679 // the configuration of the current translation unit in a compatible
2680 // way?
2681 //
2682 // FIXME: Allow this for files explicitly specified with -include-pch.
2683 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002684 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002685
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002686 ASTReadResult Result =
2687 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2688 AllowCompatibleConfigurationMismatch, *Listener,
2689 SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002690 if (Result == Failure) {
2691 Error("malformed block record in AST file");
2692 return Result;
2693 }
2694
Richard Smith8a308ec2015-11-05 00:54:55 +00002695 if (DisableValidation ||
2696 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2697 Result = Success;
2698
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002699 // If we can't load the module, exit early since we likely
2700 // will rebuild the module anyway. The stream may be in the
2701 // middle of a block.
2702 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002703 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002704 } else if (llvm::Error Err = Stream.SkipBlock()) {
2705 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002706 return Failure;
2707 }
2708 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002709
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 default:
JF Bastien0e828952019-06-26 19:50:12 +00002711 if (llvm::Error Err = Stream.SkipBlock()) {
2712 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002713 return Failure;
2714 }
2715 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002717
Chris Lattnere7b154b2013-01-19 21:39:22 +00002718 case llvm::BitstreamEntry::Record:
2719 // The interesting case.
2720 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 }
2722
2723 // Read and process a record.
2724 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002725 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002726 Expected<unsigned> MaybeRecordType =
2727 Stream.readRecord(Entry.ID, Record, &Blob);
2728 if (!MaybeRecordType) {
2729 Error(MaybeRecordType.takeError());
2730 return Failure;
2731 }
2732 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 case METADATA: {
2734 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2735 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002736 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2737 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 return VersionMismatch;
2739 }
2740
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002741 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2743 Diag(diag::err_pch_with_compiler_errors);
2744 return HadErrors;
2745 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002746 if (hasErrors) {
2747 Diags.ErrorOccurred = true;
2748 Diags.UncompilableErrorOccurred = true;
2749 Diags.UnrecoverableErrorOccurred = true;
2750 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002751
2752 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002753 // Relative paths in a relocatable PCH are relative to our sysroot.
2754 if (F.RelocatablePCH)
2755 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756
Richard Smithe75ee0f2015-08-17 07:13:32 +00002757 F.HasTimestamps = Record[5];
2758
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002759 F.PCHHasObjectFile = Record[6];
2760
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002762 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2764 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002765 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 return VersionMismatch;
2767 }
2768 break;
2769 }
2770
2771 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002772 // Validate the AST before processing any imports (otherwise, untangling
2773 // them can be error-prone and expensive). A module will have a name and
2774 // will already have been validated, but this catches the PCH case.
2775 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2776 return Result;
2777
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002778 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 unsigned Idx = 0, N = Record.size();
2780 while (Idx < N) {
2781 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002782 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 // The import location will be the local one for now; we will adjust
2784 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002785 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002787 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002788 off_t StoredSize = (off_t)Record[Idx++];
2789 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002790 ASTFileSignature StoredSignature = {
2791 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2792 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2793 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002794
2795 std::string ImportedName = ReadString(Record, Idx);
2796 std::string ImportedFile;
2797
2798 // For prebuilt and explicit modules first consult the file map for
2799 // an override. Note that here we don't search prebuilt module
2800 // directories, only the explicit name to file mappings. Also, we will
2801 // still verify the size/signature making sure it is essentially the
2802 // same file but perhaps in a different location.
2803 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2804 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2805 ImportedName, /*FileMapOnly*/ true);
2806
2807 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002808 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2809 // ModuleCache as when writing.
2810 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002811 else
2812 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002813
Richard Smith0f99d6a2015-08-09 08:48:41 +00002814 // If our client can't cope with us being out of date, we can't cope with
2815 // our dependency being missing.
2816 unsigned Capabilities = ClientLoadCapabilities;
2817 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2818 Capabilities &= ~ARR_Missing;
2819
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002821 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2822 Loaded, StoredSize, StoredModTime,
2823 StoredSignature, Capabilities);
2824
2825 // If we diagnosed a problem, produce a backtrace.
2826 if (isDiagnosedResult(Result, Capabilities))
2827 Diag(diag::note_module_file_imported_by)
2828 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2829
2830 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 case Failure: return Failure;
2832 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002833 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 case OutOfDate: return OutOfDate;
2835 case VersionMismatch: return VersionMismatch;
2836 case ConfigurationMismatch: return ConfigurationMismatch;
2837 case HadErrors: return HadErrors;
2838 case Success: break;
2839 }
2840 }
2841 break;
2842 }
2843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 case ORIGINAL_FILE:
2845 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002846 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002848 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 break;
2850
2851 case ORIGINAL_FILE_ID:
2852 F.OriginalSourceFileID = FileID::get(Record[0]);
2853 break;
2854
2855 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 break;
2858
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002859 case MODULE_NAME:
2860 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002861 Diag(diag::remark_module_import)
2862 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2863 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002864 if (Listener)
2865 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002866
2867 // Validate the AST as soon as we have a name so we can exit early on
2868 // failure.
2869 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2870 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002871
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002872 break;
2873
Richard Smith223d3f22014-12-06 03:21:08 +00002874 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002875 // Save the BaseDirectory as written in the PCM for computing the module
2876 // filename for the ModuleCache.
2877 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002878 assert(!F.ModuleName.empty() &&
2879 "MODULE_DIRECTORY found before MODULE_NAME");
2880 // If we've already loaded a module map file covering this module, we may
2881 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002882 Module *M = PP.getHeaderSearchInfo().lookupModule(
2883 F.ModuleName, /*AllowSearch*/ true,
2884 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002885 if (M && M->Directory) {
2886 // If we're implicitly loading a module, the base directory can't
2887 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002888 // Don't emit module relocation error if we have -fno-validate-pch
2889 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2890 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002891 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2892 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002893 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2894 Diag(diag::err_imported_module_relocated)
2895 << F.ModuleName << Blob << M->Directory->getName();
2896 return OutOfDate;
2897 }
2898 }
2899 F.BaseDirectory = M->Directory->getName();
2900 } else {
2901 F.BaseDirectory = Blob;
2902 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002903 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002904 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002905
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002906 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002907 if (ASTReadResult Result =
2908 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2909 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002910 break;
2911
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002912 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002913 NumInputs = Record[0];
2914 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002915 F.InputFileOffsets =
2916 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002917 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002918 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 break;
2920 }
2921 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002922}
2923
Ben Langmuir2c9af442014-04-10 17:57:43 +00002924ASTReader::ASTReadResult
2925ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002926 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927
JF Bastien0e828952019-06-26 19:50:12 +00002928 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2929 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002930 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 }
2932
2933 // Read all of the records and blocks for the AST file.
2934 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002935 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002936 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2937 if (!MaybeEntry) {
2938 Error(MaybeEntry.takeError());
2939 return Failure;
2940 }
2941 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002942
Chris Lattnere7b154b2013-01-19 21:39:22 +00002943 switch (Entry.Kind) {
2944 case llvm::BitstreamEntry::Error:
2945 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002946 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002947 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002948 // Outside of C++, we do not store a lookup map for the translation unit.
2949 // Instead, mark it as needing a lookup map to be built if this module
2950 // contains any declarations lexically within it (which it always does!).
2951 // This usually has no cost, since we very rarely need the lookup map for
2952 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002953 if (ASTContext *Ctx = ContextObj) {
2954 DeclContext *DC = Ctx->getTranslationUnitDecl();
2955 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2956 DC->setMustBuildLookupTable();
2957 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002958
Ben Langmuir2c9af442014-04-10 17:57:43 +00002959 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002960 case llvm::BitstreamEntry::SubBlock:
2961 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 case DECLTYPES_BLOCK_ID:
2963 // We lazily load the decls block, but we want to set up the
2964 // DeclsCursor cursor to point into it. Clone our current bitcode
2965 // cursor to it, enter the block and read the abbrevs in that block.
2966 // With the main cursor, we just skip over it.
2967 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002968 if (llvm::Error Err = Stream.SkipBlock()) {
2969 Error(std::move(Err));
2970 return Failure;
2971 }
2972 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002974 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 }
2976 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002977
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 case PREPROCESSOR_BLOCK_ID:
2979 F.MacroCursor = Stream;
2980 if (!PP.getExternalSource())
2981 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002982
JF Bastien0e828952019-06-26 19:50:12 +00002983 if (llvm::Error Err = Stream.SkipBlock()) {
2984 Error(std::move(Err));
2985 return Failure;
2986 }
2987 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002989 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 }
2991 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2992 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002993
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 case PREPROCESSOR_DETAIL_BLOCK_ID:
2995 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002996
2997 if (llvm::Error Err = Stream.SkipBlock()) {
2998 Error(std::move(Err));
2999 return Failure;
3000 }
3001 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00003003 Error("malformed preprocessor detail record in AST file");
3004 return Failure;
3005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00003007 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003008
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 if (!PP.getPreprocessingRecord())
3010 PP.createPreprocessingRecord();
3011 if (!PP.getPreprocessingRecord()->getExternalSource())
3012 PP.getPreprocessingRecord()->SetExternalSource(*this);
3013 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003014
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 case SOURCE_MANAGER_BLOCK_ID:
3016 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003017 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003019
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00003021 if (ASTReadResult Result =
3022 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003023 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003025
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003027 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003028
3029 if (llvm::Error Err = Stream.SkipBlock()) {
3030 Error(std::move(Err));
3031 return Failure;
3032 }
3033 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003035 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 }
3037 CommentsCursors.push_back(std::make_pair(C, &F));
3038 break;
3039 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003040
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 default:
JF Bastien0e828952019-06-26 19:50:12 +00003042 if (llvm::Error Err = Stream.SkipBlock()) {
3043 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00003044 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003045 }
3046 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 }
3048 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003049
Chris Lattnere7b154b2013-01-19 21:39:22 +00003050 case llvm::BitstreamEntry::Record:
3051 // The interesting case.
3052 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 }
3054
3055 // Read and process a record.
3056 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003057 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003058 Expected<unsigned> MaybeRecordType =
3059 Stream.readRecord(Entry.ID, Record, &Blob);
3060 if (!MaybeRecordType) {
3061 Error(MaybeRecordType.takeError());
3062 return Failure;
3063 }
3064 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003065
3066 // If we're not loading an AST context, we don't care about most records.
3067 if (!ContextObj) {
3068 switch (RecordType) {
3069 case IDENTIFIER_TABLE:
3070 case IDENTIFIER_OFFSET:
3071 case INTERESTING_IDENTIFIERS:
3072 case STATISTICS:
3073 case PP_CONDITIONAL_STACK:
3074 case PP_COUNTER_VALUE:
3075 case SOURCE_LOCATION_OFFSETS:
3076 case MODULE_OFFSET_MAP:
3077 case SOURCE_MANAGER_LINE_TABLE:
3078 case SOURCE_LOCATION_PRELOADS:
3079 case PPD_ENTITIES_OFFSETS:
3080 case HEADER_SEARCH_TABLE:
3081 case IMPORTED_MODULES:
3082 case MACRO_OFFSET:
3083 break;
3084 default:
3085 continue;
3086 }
3087 }
3088
3089 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 default: // Default behavior: ignore.
3091 break;
3092
3093 case TYPE_OFFSET: {
3094 if (F.LocalNumTypes != 0) {
3095 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003096 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003098 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 F.LocalNumTypes = Record[0];
3100 unsigned LocalBaseTypeIndex = Record[1];
3101 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003102
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 if (F.LocalNumTypes > 0) {
3104 // Introduce the global -> local mapping for types within this module.
3105 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003106
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 // Introduce the local -> global mapping for types within this module.
3108 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003109 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003111
3112 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 }
3114 break;
3115 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003116
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 case DECL_OFFSET: {
3118 if (F.LocalNumDecls != 0) {
3119 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003120 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003122 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 F.LocalNumDecls = Record[0];
3124 unsigned LocalBaseDeclID = Record[1];
3125 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003128 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 // module.
3130 GlobalDeclMap.insert(
3131 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003132
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 // Introduce the local -> global mapping for declarations within this
3134 // module.
3135 F.DeclRemap.insertOrReplace(
3136 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 // Introduce the global -> local mapping for declarations within this
3139 // module.
3140 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003141
Ben Langmuir52ca6782014-10-20 16:27:32 +00003142 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3143 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 break;
3145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003146
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003148 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003149 LexicalContents Contents(
3150 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3151 Blob.data()),
3152 static_cast<unsigned int>(Blob.size() / 4));
3153 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 TU->setHasExternalLexicalStorage(true);
3155 break;
3156 }
3157
3158 case UPDATE_VISIBLE: {
3159 unsigned Idx = 0;
3160 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003161 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003162 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003163 // If we've already loaded the decl, perform the updates when we finish
3164 // loading this block.
3165 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003166 PendingUpdateRecords.push_back(
3167 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 break;
3169 }
3170
3171 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003172 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003174 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3175 (const unsigned char *)F.IdentifierTableData + Record[0],
3176 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3177 (const unsigned char *)F.IdentifierTableData,
3178 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003179
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3181 }
3182 break;
3183
3184 case IDENTIFIER_OFFSET: {
3185 if (F.LocalNumIdentifiers != 0) {
3186 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003187 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003189 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 F.LocalNumIdentifiers = Record[0];
3191 unsigned LocalBaseIdentifierID = Record[1];
3192 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003193
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 if (F.LocalNumIdentifiers > 0) {
3195 // Introduce the global -> local mapping for identifiers within this
3196 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003197 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003199
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 // Introduce the local -> global mapping for identifiers within this
3201 // module.
3202 F.IdentifierRemap.insertOrReplace(
3203 std::make_pair(LocalBaseIdentifierID,
3204 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003205
Ben Langmuir52ca6782014-10-20 16:27:32 +00003206 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3207 + F.LocalNumIdentifiers);
3208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 break;
3210 }
3211
Richard Smith33e0f7e2015-07-22 02:08:40 +00003212 case INTERESTING_IDENTIFIERS:
3213 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3214 break;
3215
Ben Langmuir332aafe2014-01-31 01:06:56 +00003216 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003217 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3218 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003219 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003220 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 break;
3222
David Blaikie9ffe5a32017-01-30 05:00:26 +00003223 case MODULAR_CODEGEN_DECLS:
3224 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3225 // them (ie: if we're not codegenerating this module).
3226 if (F.Kind == MK_MainFile)
3227 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3228 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3229 break;
3230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003232 if (SpecialTypes.empty()) {
3233 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3234 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3235 break;
3236 }
3237
3238 if (SpecialTypes.size() != Record.size()) {
3239 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003240 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003241 }
3242
3243 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3244 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3245 if (!SpecialTypes[I])
3246 SpecialTypes[I] = ID;
3247 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3248 // merge step?
3249 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 break;
3251
3252 case STATISTICS:
3253 TotalNumStatements += Record[0];
3254 TotalNumMacros += Record[1];
3255 TotalLexicalDeclContexts += Record[2];
3256 TotalVisibleDeclContexts += Record[3];
3257 break;
3258
3259 case UNUSED_FILESCOPED_DECLS:
3260 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3261 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3262 break;
3263
3264 case DELEGATING_CTORS:
3265 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3266 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3267 break;
3268
3269 case WEAK_UNDECLARED_IDENTIFIERS:
3270 if (Record.size() % 4 != 0) {
3271 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003272 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003274
3275 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 // files. This isn't the way to do it :)
3277 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003278
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 // Translate the weak, undeclared identifiers into global IDs.
3280 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3281 WeakUndeclaredIdentifiers.push_back(
3282 getGlobalIdentifierID(F, Record[I++]));
3283 WeakUndeclaredIdentifiers.push_back(
3284 getGlobalIdentifierID(F, Record[I++]));
3285 WeakUndeclaredIdentifiers.push_back(
3286 ReadSourceLocation(F, Record, I).getRawEncoding());
3287 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3288 }
3289 break;
3290
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003292 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 F.LocalNumSelectors = Record[0];
3294 unsigned LocalBaseSelectorID = Record[1];
3295 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003296
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003298 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 // module.
3300 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003301
3302 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 // module.
3304 F.SelectorRemap.insertOrReplace(
3305 std::make_pair(LocalBaseSelectorID,
3306 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003307
3308 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003309 }
3310 break;
3311 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003312
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003314 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 if (Record[0])
3316 F.SelectorLookupTable
3317 = ASTSelectorLookupTable::Create(
3318 F.SelectorLookupTableData + Record[0],
3319 F.SelectorLookupTableData,
3320 ASTSelectorLookupTrait(*this, F));
3321 TotalNumMethodPoolEntries += Record[1];
3322 break;
3323
3324 case REFERENCED_SELECTOR_POOL:
3325 if (!Record.empty()) {
3326 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003327 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 Record[Idx++]));
3329 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3330 getRawEncoding());
3331 }
3332 }
3333 break;
3334
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003335 case PP_CONDITIONAL_STACK:
3336 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003337 unsigned Idx = 0, End = Record.size() - 1;
3338 bool ReachedEOFWhileSkipping = Record[Idx++];
3339 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3340 if (ReachedEOFWhileSkipping) {
3341 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3342 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3343 bool FoundNonSkipPortion = Record[Idx++];
3344 bool FoundElse = Record[Idx++];
3345 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3346 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3347 FoundElse, ElseLoc);
3348 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003349 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003350 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003351 auto Loc = ReadSourceLocation(F, Record, Idx);
3352 bool WasSkipping = Record[Idx++];
3353 bool FoundNonSkip = Record[Idx++];
3354 bool FoundElse = Record[Idx++];
3355 ConditionalStack.push_back(
3356 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3357 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003358 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003359 }
3360 break;
3361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 case PP_COUNTER_VALUE:
3363 if (!Record.empty() && Listener)
3364 Listener->ReadCounter(F, Record[0]);
3365 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003366
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003368 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 F.NumFileSortedDecls = Record[0];
3370 break;
3371
3372 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003373 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 F.LocalNumSLocEntries = Record[0];
3375 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003376 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003377 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003379 if (!F.SLocEntryBaseID) {
3380 Error("ran out of source locations");
3381 break;
3382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 // Make our entry in the range map. BaseID is negative and growing, so
3384 // we invert it. Because we invert it, though, we need the other end of
3385 // the range.
3386 unsigned RangeStart =
3387 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3388 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3389 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3390
3391 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3392 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3393 GlobalSLocOffsetMap.insert(
3394 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3395 - SLocSpaceSize,&F));
3396
3397 // Initialize the remapping table.
3398 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003399 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003401 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003403
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 TotalNumSLocEntries += F.LocalNumSLocEntries;
3405 break;
3406 }
3407
Richard Smith37a93df2017-02-18 00:32:02 +00003408 case MODULE_OFFSET_MAP:
3409 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003411
3412 case SOURCE_MANAGER_LINE_TABLE:
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003413 if (ParseLineTable(F, Record)) {
3414 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003415 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 break;
3418
3419 case SOURCE_LOCATION_PRELOADS: {
3420 // Need to transform from the local view (1-based IDs) to the global view,
3421 // which is based off F.SLocEntryBaseID.
3422 if (!F.PreloadSLocEntries.empty()) {
3423 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003424 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003426
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 F.PreloadSLocEntries.swap(Record);
3428 break;
3429 }
3430
3431 case EXT_VECTOR_DECLS:
3432 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3433 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3434 break;
3435
3436 case VTABLE_USES:
3437 if (Record.size() % 3 != 0) {
3438 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003439 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003441
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 // Later tables overwrite earlier ones.
3443 // FIXME: Modules will have some trouble with this. This is clearly not
3444 // the right way to do this.
3445 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003446
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3448 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3449 VTableUses.push_back(
3450 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3451 VTableUses.push_back(Record[Idx++]);
3452 }
3453 break;
3454
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 case PENDING_IMPLICIT_INSTANTIATIONS:
3456 if (PendingInstantiations.size() % 2 != 0) {
3457 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003458 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 }
3460
3461 if (Record.size() % 2 != 0) {
3462 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003463 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 }
3465
3466 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3467 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3468 PendingInstantiations.push_back(
3469 ReadSourceLocation(F, Record, I).getRawEncoding());
3470 }
3471 break;
3472
3473 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003474 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003475 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003476 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003477 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3479 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3480 break;
3481
3482 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003483 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3484 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3485 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
3487 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003488
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 unsigned StartingID;
3490 if (!PP.getPreprocessingRecord())
3491 PP.createPreprocessingRecord();
3492 if (!PP.getPreprocessingRecord()->getExternalSource())
3493 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003494 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003496 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 F.BasePreprocessedEntityID = StartingID;
3498
3499 if (F.NumPreprocessedEntities > 0) {
3500 // Introduce the global -> local mapping for preprocessed entities in
3501 // this module.
3502 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003503
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 // Introduce the local -> global mapping for preprocessed entities in
3505 // this module.
3506 F.PreprocessedEntityRemap.insertOrReplace(
3507 std::make_pair(LocalBasePreprocessedEntityID,
3508 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3509 }
3510
3511 break;
3512 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003513
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003514 case PPD_SKIPPED_RANGES: {
3515 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3516 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3517 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3518
3519 if (!PP.getPreprocessingRecord())
3520 PP.createPreprocessingRecord();
3521 if (!PP.getPreprocessingRecord()->getExternalSource())
3522 PP.getPreprocessingRecord()->SetExternalSource(*this);
3523 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3524 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003525
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003526 if (F.NumPreprocessedSkippedRanges > 0)
3527 GlobalSkippedRangeMap.insert(
3528 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3529 break;
3530 }
3531
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003532 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 if (Record.size() % 2 != 0) {
3534 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003535 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003537 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3538 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3539 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3540
3541 // If we've already loaded the decl, perform the updates when we finish
3542 // loading this block.
3543 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003544 PendingUpdateRecords.push_back(
3545 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003546 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003548
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003549 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 if (F.LocalNumObjCCategoriesInMap != 0) {
3551 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003552 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003556 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 case OBJC_CATEGORIES:
3560 F.ObjCCategories.swap(Record);
3561 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003562
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 case CUDA_SPECIAL_DECL_REFS:
3564 // Later tables overwrite earlier ones.
3565 // FIXME: Modules will have trouble with this.
3566 CUDASpecialDeclRefs.clear();
3567 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3568 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3569 break;
3570
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003571 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003572 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 if (Record[0]) {
3575 F.HeaderFileInfoTable
3576 = HeaderFileInfoLookupTable::Create(
3577 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3578 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003579 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003581 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003582
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 PP.getHeaderSearchInfo().SetExternalSource(this);
3584 if (!PP.getHeaderSearchInfo().getExternalLookup())
3585 PP.getHeaderSearchInfo().SetExternalLookup(this);
3586 }
3587 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003588
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 case FP_PRAGMA_OPTIONS:
3590 // Later tables overwrite earlier ones.
3591 FPPragmaOptions.swap(Record);
3592 break;
3593
3594 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003595 for (unsigned I = 0, E = Record.size(); I != E; ) {
3596 auto Name = ReadString(Record, I);
3597 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003598 Opt.Supported = Record[I++] != 0;
3599 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003600 Opt.Avail = Record[I++];
3601 Opt.Core = Record[I++];
3602 }
3603 break;
3604
3605 case OPENCL_EXTENSION_TYPES:
3606 for (unsigned I = 0, E = Record.size(); I != E;) {
3607 auto TypeID = static_cast<::TypeID>(Record[I++]);
3608 auto *Type = GetType(TypeID).getTypePtr();
3609 auto NumExt = static_cast<unsigned>(Record[I++]);
3610 for (unsigned II = 0; II != NumExt; ++II) {
3611 auto Ext = ReadString(Record, I);
3612 OpenCLTypeExtMap[Type].insert(Ext);
3613 }
3614 }
3615 break;
3616
3617 case OPENCL_EXTENSION_DECLS:
3618 for (unsigned I = 0, E = Record.size(); I != E;) {
3619 auto DeclID = static_cast<::DeclID>(Record[I++]);
3620 auto *Decl = GetDecl(DeclID);
3621 auto NumExt = static_cast<unsigned>(Record[I++]);
3622 for (unsigned II = 0; II != NumExt; ++II) {
3623 auto Ext = ReadString(Record, I);
3624 OpenCLDeclExtMap[Decl].insert(Ext);
3625 }
3626 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 break;
3628
3629 case TENTATIVE_DEFINITIONS:
3630 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3631 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3632 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003633
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 case KNOWN_NAMESPACES:
3635 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3636 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3637 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003638
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003639 case UNDEFINED_BUT_USED:
3640 if (UndefinedButUsed.size() % 2 != 0) {
3641 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003642 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003643 }
3644
3645 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003646 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003647 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003648 }
3649 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003650 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3651 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003652 ReadSourceLocation(F, Record, I).getRawEncoding());
3653 }
3654 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003655
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003656 case DELETE_EXPRS_TO_ANALYZE:
3657 for (unsigned I = 0, N = Record.size(); I != N;) {
3658 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3659 const uint64_t Count = Record[I++];
3660 DelayedDeleteExprs.push_back(Count);
3661 for (uint64_t C = 0; C < Count; ++C) {
3662 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3663 bool IsArrayForm = Record[I++] == 1;
3664 DelayedDeleteExprs.push_back(IsArrayForm);
3665 }
3666 }
3667 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003668
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003669 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003670 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 // If we aren't loading a module (which has its own exports), make
3672 // all of the imported modules visible.
3673 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003674 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3675 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3676 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003677 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003678 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003679 if (DeserializationListener)
3680 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3681 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 }
3683 }
3684 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003685
Guy Benyei11169dd2012-12-18 14:30:41 +00003686 case MACRO_OFFSET: {
3687 if (F.LocalNumMacros != 0) {
3688 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003689 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003691 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 F.LocalNumMacros = Record[0];
3693 unsigned LocalBaseMacroID = Record[1];
3694 F.BaseMacroID = getTotalNumMacros();
3695
3696 if (F.LocalNumMacros > 0) {
3697 // Introduce the global -> local mapping for macros within this module.
3698 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3699
3700 // Introduce the local -> global mapping for macros within this module.
3701 F.MacroRemap.insertOrReplace(
3702 std::make_pair(LocalBaseMacroID,
3703 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003704
3705 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 }
3707 break;
3708 }
3709
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003710 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003711 LateParsedTemplates.append(Record.begin(), Record.end());
3712 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003713
3714 case OPTIMIZE_PRAGMA_OPTIONS:
3715 if (Record.size() != 1) {
3716 Error("invalid pragma optimize record");
3717 return Failure;
3718 }
3719 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3720 break;
Nico Weber72889432014-09-06 01:25:55 +00003721
Nico Weber779355f2016-03-02 23:22:00 +00003722 case MSSTRUCT_PRAGMA_OPTIONS:
3723 if (Record.size() != 1) {
3724 Error("invalid pragma ms_struct record");
3725 return Failure;
3726 }
3727 PragmaMSStructState = Record[0];
3728 break;
3729
Nico Weber42932312016-03-03 00:17:35 +00003730 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3731 if (Record.size() != 2) {
3732 Error("invalid pragma ms_struct record");
3733 return Failure;
3734 }
3735 PragmaMSPointersToMembersState = Record[0];
3736 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3737 break;
3738
Nico Weber72889432014-09-06 01:25:55 +00003739 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3740 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3741 UnusedLocalTypedefNameCandidates.push_back(
3742 getGlobalDeclID(F, Record[I]));
3743 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003744
3745 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3746 if (Record.size() != 1) {
3747 Error("invalid cuda pragma options record");
3748 return Failure;
3749 }
3750 ForceCUDAHostDeviceDepth = Record[0];
3751 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003752
3753 case PACK_PRAGMA_OPTIONS: {
3754 if (Record.size() < 3) {
3755 Error("invalid pragma pack record");
3756 return Failure;
3757 }
3758 PragmaPackCurrentValue = Record[0];
3759 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3760 unsigned NumStackEntries = Record[2];
3761 unsigned Idx = 3;
3762 // Reset the stack when importing a new module.
3763 PragmaPackStack.clear();
3764 for (unsigned I = 0; I < NumStackEntries; ++I) {
3765 PragmaPackStackEntry Entry;
3766 Entry.Value = Record[Idx++];
3767 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003768 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003769 PragmaPackStrings.push_back(ReadString(Record, Idx));
3770 Entry.SlotLabel = PragmaPackStrings.back();
3771 PragmaPackStack.push_back(Entry);
3772 }
3773 break;
3774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 }
3776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003777}
3778
Richard Smith37a93df2017-02-18 00:32:02 +00003779void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3780 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3781
3782 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003783 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003784 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3785 F.ModuleOffsetMap = StringRef();
3786
3787 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3788 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3789 F.SLocRemap.insert(std::make_pair(0U, 0));
3790 F.SLocRemap.insert(std::make_pair(2U, 1));
3791 }
3792
3793 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003794 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003795 RemapBuilder SLocRemap(F.SLocRemap);
3796 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3797 RemapBuilder MacroRemap(F.MacroRemap);
3798 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3799 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3800 RemapBuilder SelectorRemap(F.SelectorRemap);
3801 RemapBuilder DeclRemap(F.DeclRemap);
3802 RemapBuilder TypeRemap(F.TypeRemap);
3803
3804 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003805 // FIXME: Looking up dependency modules by filename is horrible. Let's
3806 // start fixing this with prebuilt and explicit modules and see how it
3807 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003808 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003809 ModuleKind Kind = static_cast<ModuleKind>(
3810 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003811 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3812 StringRef Name = StringRef((const char*)Data, Len);
3813 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003814 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3815 ? ModuleMgr.lookupByModuleName(Name)
3816 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003817 if (!OM) {
3818 std::string Msg =
3819 "SourceLocation remap refers to unknown module, cannot find ";
3820 Msg.append(Name);
3821 Error(Msg);
3822 return;
3823 }
3824
3825 uint32_t SLocOffset =
3826 endian::readNext<uint32_t, little, unaligned>(Data);
3827 uint32_t IdentifierIDOffset =
3828 endian::readNext<uint32_t, little, unaligned>(Data);
3829 uint32_t MacroIDOffset =
3830 endian::readNext<uint32_t, little, unaligned>(Data);
3831 uint32_t PreprocessedEntityIDOffset =
3832 endian::readNext<uint32_t, little, unaligned>(Data);
3833 uint32_t SubmoduleIDOffset =
3834 endian::readNext<uint32_t, little, unaligned>(Data);
3835 uint32_t SelectorIDOffset =
3836 endian::readNext<uint32_t, little, unaligned>(Data);
3837 uint32_t DeclIDOffset =
3838 endian::readNext<uint32_t, little, unaligned>(Data);
3839 uint32_t TypeIndexOffset =
3840 endian::readNext<uint32_t, little, unaligned>(Data);
3841
3842 uint32_t None = std::numeric_limits<uint32_t>::max();
3843
3844 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3845 RemapBuilder &Remap) {
3846 if (Offset != None)
3847 Remap.insert(std::make_pair(Offset,
3848 static_cast<int>(BaseOffset - Offset)));
3849 };
3850 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3851 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3852 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3853 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3854 PreprocessedEntityRemap);
3855 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3856 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3857 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3858 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3859
3860 // Global -> local mappings.
3861 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3862 }
3863}
3864
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003865ASTReader::ASTReadResult
3866ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3867 const ModuleFile *ImportedBy,
3868 unsigned ClientLoadCapabilities) {
3869 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003870 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003871
3872 // Try to resolve ModuleName in the current header search context and
3873 // verify that it is found in the same module map file as we saved. If the
3874 // top-level AST file is a main file, skip this check because there is no
3875 // usable header search context.
3876 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003877 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003878 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003879 // An implicitly-loaded module file should have its module listed in some
3880 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003881 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003882 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3883 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003884 // Don't emit module relocation error if we have -fno-validate-pch
3885 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003886 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003887 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003888 // This module was defined by an imported (explicit) module.
3889 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3890 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003891 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003892 // This module was built with a different module map.
3893 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003894 << F.ModuleName << F.FileName
3895 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3896 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003897 // In case it was imported by a PCH, there's a chance the user is
3898 // just missing to include the search path to the directory containing
3899 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003900 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003901 Diag(diag::note_imported_by_pch_module_not_found)
3902 << llvm::sys::path::parent_path(F.ModuleMapPath);
3903 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003904 }
3905 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003906 }
3907
Richard Smithe842a472014-10-22 02:05:46 +00003908 assert(M->Name == F.ModuleName && "found module with different name");
3909
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003910 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003911 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3912 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003913 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003914 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3915 "top-level import should be verified");
3916 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003917 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3918 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003919 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3920 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003921 return OutOfDate;
3922 }
3923
3924 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3925 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3926 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003927 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003928 auto F = FileMgr.getFile(Filename, false, false);
3929 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003930 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3931 Error("could not find file '" + Filename +"' referenced by AST file");
3932 return OutOfDate;
3933 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003934 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003935 }
3936
3937 // Check any additional module map files (e.g. module.private.modulemap)
3938 // that are not in the pcm.
3939 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003940 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003941 // Remove files that match
3942 // Note: SmallPtrSet::erase is really remove
3943 if (!AdditionalStoredMaps.erase(ModMap)) {
3944 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3945 Diag(diag::err_module_different_modmap)
3946 << F.ModuleName << /*new*/0 << ModMap->getName();
3947 return OutOfDate;
3948 }
3949 }
3950 }
3951
3952 // Check any additional module map files that are in the pcm, but not
3953 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003954 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003955 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3956 Diag(diag::err_module_different_modmap)
3957 << F.ModuleName << /*not new*/1 << ModMap->getName();
3958 return OutOfDate;
3959 }
3960 }
3961
3962 if (Listener)
3963 Listener->ReadModuleMapFile(F.ModuleMapPath);
3964 return Success;
3965}
3966
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003967/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003968static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3969 // Find the entry for this selector in the method pool.
3970 Sema::GlobalMethodPool::iterator Known
3971 = S.MethodPool.find(Method->getSelector());
3972 if (Known == S.MethodPool.end())
3973 return;
3974
3975 // Retrieve the appropriate method list.
3976 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3977 : Known->second.second;
3978 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003979 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003980 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003981 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003982 Found = true;
3983 } else {
3984 // Keep searching.
3985 continue;
3986 }
3987 }
3988
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003989 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003990 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003991 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003992 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003993 }
3994}
3995
Richard Smithde711422015-04-23 21:20:19 +00003996void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003997 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003998 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003999 bool wasHidden = D->isHidden();
4000 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00004001
Vedant Kumar48b4f762018-04-14 01:40:48 +00004002 if (wasHidden && SemaObj) {
4003 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004004 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004005 }
4006 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 }
4008}
4009
Richard Smith49f906a2014-03-01 00:08:04 +00004010void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004011 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004012 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004014 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004015 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004017 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004018
4019 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004020 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 // there is nothing more to do.
4022 continue;
4023 }
Richard Smith49f906a2014-03-01 00:08:04 +00004024
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 if (!Mod->isAvailable()) {
4026 // Modules that aren't available cannot be made visible.
4027 continue;
4028 }
4029
4030 // Update the module's name visibility.
4031 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004032
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 // If we've already deserialized any names from this module,
4034 // mark them as visible.
4035 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4036 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004037 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004039 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004040 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4041 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004043
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004045 SmallVector<Module *, 16> Exports;
4046 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004047 for (SmallVectorImpl<Module *>::iterator
4048 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4049 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004050 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004051 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004052 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 }
4054}
4055
Richard Smith6561f922016-09-12 21:06:40 +00004056/// We've merged the definition \p MergedDef into the existing definition
4057/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4058/// visible.
4059void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4060 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004061 if (Def->isHidden()) {
4062 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004063 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004064 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004065 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004066 getContext().mergeDefinitionIntoModule(
4067 Def, MergedDef->getImportedOwningModule(),
4068 /*NotifyListeners*/ false);
4069 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004070 }
Richard Smith6561f922016-09-12 21:06:40 +00004071 }
4072}
4073
Douglas Gregore060e572013-01-25 01:03:03 +00004074bool ASTReader::loadGlobalIndex() {
4075 if (GlobalIndex)
4076 return false;
4077
4078 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004079 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004080 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004081
Douglas Gregore060e572013-01-25 01:03:03 +00004082 // Try to load the global index.
4083 TriedLoadingGlobalIndex = true;
4084 StringRef ModuleCachePath
4085 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004086 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4087 GlobalModuleIndex::readIndex(ModuleCachePath);
4088 if (llvm::Error Err = std::move(Result.second)) {
4089 assert(!Result.first);
4090 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004091 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004092 }
Douglas Gregore060e572013-01-25 01:03:03 +00004093
4094 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004095 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004096 return false;
4097}
4098
4099bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004100 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004101 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4102}
4103
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004104static void updateModuleTimestamp(ModuleFile &MF) {
4105 // Overwrite the timestamp file contents so that file's mtime changes.
4106 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004107 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004108 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004109 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004110 return;
4111 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004112 OS.close();
4113 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004114}
4115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004116/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004117/// cursor into the start of the given block ID, returning false on success and
4118/// true on failure.
4119static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004120 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004121 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4122 if (!MaybeEntry) {
4123 // FIXME this drops errors on the floor.
4124 consumeError(MaybeEntry.takeError());
4125 return true;
4126 }
4127 llvm::BitstreamEntry Entry = MaybeEntry.get();
4128
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004129 switch (Entry.Kind) {
4130 case llvm::BitstreamEntry::Error:
4131 case llvm::BitstreamEntry::EndBlock:
4132 return true;
4133
4134 case llvm::BitstreamEntry::Record:
4135 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004136 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4137 break;
4138 else {
4139 // FIXME this drops errors on the floor.
4140 consumeError(Skipped.takeError());
4141 return true;
4142 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004143
4144 case llvm::BitstreamEntry::SubBlock:
4145 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004146 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4147 // FIXME this drops the error on the floor.
4148 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004149 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004150 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004151 // Found it!
4152 return false;
4153 }
4154
JF Bastien0e828952019-06-26 19:50:12 +00004155 if (llvm::Error Err = Cursor.SkipBlock()) {
4156 // FIXME this drops the error on the floor.
4157 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004158 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004159 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004160 }
4161 }
4162}
4163
Benjamin Kramer0772c422016-02-13 13:42:54 +00004164ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 ModuleKind Type,
4166 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004167 unsigned ClientLoadCapabilities,
4168 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004169 llvm::SaveAndRestore<SourceLocation>
4170 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4171
Richard Smithd1c46742014-04-30 02:24:17 +00004172 // Defer any pending actions until we get to the end of reading the AST file.
4173 Deserializing AnASTFile(this);
4174
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004176 unsigned PreviousGeneration = 0;
4177 if (ContextObj)
4178 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004179
4180 unsigned NumModules = ModuleMgr.size();
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004181 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4182 assert(ReadResult && "expected to return error");
Duncan P. N. Exon Smith8e9e4332019-11-10 10:31:03 -08004183 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004184 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004185 ? &PP.getHeaderSearchInfo().getModuleMap()
4186 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004187
4188 // If we find that any modules are unusable, the global index is going
4189 // to be out-of-date. Just remove it.
4190 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004191 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 return ReadResult;
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004193 };
4194
4195 SmallVector<ImportedModule, 4> Loaded;
4196 switch (ASTReadResult ReadResult =
4197 ReadASTCore(FileName, Type, ImportLoc,
4198 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4199 ASTFileSignature(), ClientLoadCapabilities)) {
4200 case Failure:
4201 case Missing:
4202 case OutOfDate:
4203 case VersionMismatch:
4204 case ConfigurationMismatch:
4205 case HadErrors:
4206 return removeModulesAndReturn(ReadResult);
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 case Success:
4208 break;
4209 }
4210
4211 // Here comes stuff that we only do once the entire chain is loaded.
4212
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004213 // Load the AST blocks of all of the modules that we loaded. We can still
4214 // hit errors parsing the ASTs at this point.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004215 for (ImportedModule &M : Loaded) {
4216 ModuleFile &F = *M.Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217
4218 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004219 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004220 return removeModulesAndReturn(Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00004221
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08004222 // The AST block should always have a definition for the main module.
4223 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4224 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4225 return removeModulesAndReturn(Failure);
4226 }
4227
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004228 // Read the extension blocks.
4229 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4230 if (ASTReadResult Result = ReadExtensionBlock(F))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004231 return removeModulesAndReturn(Result);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004232 }
4233
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004234 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 // bits of all files we've seen.
4236 F.GlobalBitOffset = TotalModulesSizeInBits;
4237 TotalModulesSizeInBits += F.SizeInBits;
4238 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004239 }
4240
4241 // Preload source locations and interesting indentifiers.
4242 for (ImportedModule &M : Loaded) {
4243 ModuleFile &F = *M.Mod;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004244
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004246 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4247 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 // Load it through the SourceManager and don't call ReadSLocEntry()
4249 // directly because the entry may have already been loaded in which case
4250 // calling ReadSLocEntry() directly would trigger an assertion in
4251 // SourceManager.
4252 SourceMgr.getLoadedSLocEntryByID(Index);
4253 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004254
Richard Smithea741482017-05-01 22:10:47 +00004255 // Map the original source file ID into the ID space of the current
4256 // compilation.
4257 if (F.OriginalSourceFileID.isValid()) {
4258 F.OriginalSourceFileID = FileID::get(
4259 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4260 }
4261
Richard Smith33e0f7e2015-07-22 02:08:40 +00004262 // Preload all the pending interesting identifiers by marking them out of
4263 // date.
4264 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004265 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004266 F.IdentifierTableData + Offset);
4267
4268 ASTIdentifierLookupTrait Trait(*this, F);
4269 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4270 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004271 auto &II = PP.getIdentifierTable().getOwn(Key);
4272 II.setOutOfDate(true);
4273
4274 // Mark this identifier as being from an AST file so that we can track
4275 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004276 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004277
4278 // Associate the ID with the identifier so that the writer can reuse it.
4279 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4280 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 }
4283
Douglas Gregor603cd862013-03-22 18:50:14 +00004284 // Setup the import locations and notify the module manager that we've
4285 // committed to these module files.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004286 for (ImportedModule &M : Loaded) {
4287 ModuleFile &F = *M.Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004288
4289 ModuleMgr.moduleFileAccepted(&F);
4290
4291 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004292 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004293 // FIXME: We assume that locations from PCH / preamble do not need
4294 // any translation.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004295 if (!M.ImportedBy)
4296 F.ImportLoc = M.ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 else
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004298 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 }
4300
Richard Smithdbafb6c2017-06-29 23:23:46 +00004301 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004302 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4303 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004304 // Mark all of the identifiers in the identifier table as being out of date,
4305 // so that various accessors know to check the loaded modules when the
4306 // identifier is used.
4307 //
4308 // For C++ modules, we don't need information on many identifiers (just
4309 // those that provide macros or are poisoned), so we mark all of
4310 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004311 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4312 IdEnd = PP.getIdentifierTable().end();
4313 Id != IdEnd; ++Id)
4314 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004315 }
Manman Rena0f31a02016-04-29 19:04:05 +00004316 // Mark selectors as out of date.
4317 for (auto Sel : SelectorGeneration)
4318 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004319
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004321 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4322 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4324 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004325
4326 switch (Unresolved.Kind) {
4327 case UnresolvedModuleRef::Conflict:
4328 if (ResolvedMod) {
4329 Module::Conflict Conflict;
4330 Conflict.Other = ResolvedMod;
4331 Conflict.Message = Unresolved.String.str();
4332 Unresolved.Mod->Conflicts.push_back(Conflict);
4333 }
4334 continue;
4335
4336 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004338 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004340
Douglas Gregorfb912652013-03-20 21:10:35 +00004341 case UnresolvedModuleRef::Export:
4342 if (ResolvedMod || Unresolved.IsWildcard)
4343 Unresolved.Mod->Exports.push_back(
4344 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4345 continue;
4346 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004348 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004349
Graydon Hoaree7196af2016-12-09 21:45:49 +00004350 if (Imported)
4351 Imported->append(ImportedModules.begin(),
4352 ImportedModules.end());
4353
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004354 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4355 // Might be unnecessary as use declarations are only used to build the
4356 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004357
Richard Smithdbafb6c2017-06-29 23:23:46 +00004358 if (ContextObj)
4359 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004360
Richard Smith3d8e97e2013-10-18 06:54:39 +00004361 if (SemaObj)
4362 UpdateSema();
4363
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 if (DeserializationListener)
4365 DeserializationListener->ReaderInitialized(this);
4366
4367 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004368 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 // If this AST file is a precompiled preamble, then set the
4370 // preamble file ID of the source manager to the file source file
4371 // from which the preamble was built.
4372 if (Type == MK_Preamble) {
4373 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4374 } else if (Type == MK_MainFile) {
4375 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4376 }
4377 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004378
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 // For any Objective-C class definitions we have already loaded, make sure
4380 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004381 if (ContextObj) {
4382 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4383 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4384 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004385 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004386 }
4387 }
Douglas Gregore060e572013-01-25 01:03:03 +00004388
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004389 if (PP.getHeaderSearchInfo()
4390 .getHeaderSearchOpts()
4391 .ModulesValidateOncePerBuildSession) {
4392 // Now we are certain that the module and all modules it depends on are
4393 // up to date. Create or update timestamp files for modules that are
4394 // located in the module cache (not for PCH files that could be anywhere
4395 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004396 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4397 ImportedModule &M = Loaded[I];
4398 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004399 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004400 }
4401 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004402 }
4403
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 return Success;
4405}
4406
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004407static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004408
JF Bastien0e828952019-06-26 19:50:12 +00004409/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4410static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4411 // FIXME checking magic headers is done in other places such as
4412 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4413 // always done the same. Unify it all with a helper.
4414 if (!Stream.canSkipToPos(4))
4415 return llvm::createStringError(std::errc::illegal_byte_sequence,
4416 "file too small to contain AST file magic");
4417 for (unsigned C : {'C', 'P', 'C', 'H'})
4418 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4419 if (Res.get() != C)
4420 return llvm::createStringError(
4421 std::errc::illegal_byte_sequence,
4422 "file doesn't start with AST file magic");
4423 } else
4424 return Res.takeError();
4425 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004426}
4427
Richard Smith0f99d6a2015-08-09 08:48:41 +00004428static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4429 switch (Kind) {
4430 case MK_PCH:
4431 return 0; // PCH
4432 case MK_ImplicitModule:
4433 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004434 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004435 return 1; // module
4436 case MK_MainFile:
4437 case MK_Preamble:
4438 return 2; // main source file
4439 }
4440 llvm_unreachable("unknown module kind");
4441}
4442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443ASTReader::ASTReadResult
4444ASTReader::ReadASTCore(StringRef FileName,
4445 ModuleKind Type,
4446 SourceLocation ImportLoc,
4447 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004448 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004449 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004450 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 unsigned ClientLoadCapabilities) {
4452 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004454 ModuleManager::AddModuleResult AddResult
4455 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004456 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004457 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004458 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004459
Douglas Gregor7029ce12013-03-19 00:28:20 +00004460 switch (AddResult) {
4461 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004462 Diag(diag::remark_module_import)
4463 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4464 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004465 return Success;
4466
4467 case ModuleManager::NewlyLoaded:
4468 // Load module file below.
4469 break;
4470
4471 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004472 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004473 // it.
4474 if (ClientLoadCapabilities & ARR_Missing)
4475 return Missing;
4476
4477 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004478 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004479 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004480 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004481 return Failure;
4482
4483 case ModuleManager::OutOfDate:
4484 // We couldn't load the module file because it is out-of-date. If the
4485 // client can handle out-of-date, return it.
4486 if (ClientLoadCapabilities & ARR_OutOfDate)
4487 return OutOfDate;
4488
4489 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004490 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004491 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004492 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 return Failure;
4494 }
4495
Douglas Gregor7029ce12013-03-19 00:28:20 +00004496 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004497
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004498 bool ShouldFinalizePCM = false;
4499 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4500 auto &MC = getModuleManager().getModuleCache();
4501 if (ShouldFinalizePCM)
4502 MC.finalizePCM(FileName);
4503 else
4504 MC.tryToDropPCM(FileName);
4505 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004507 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004508 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004509 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004510
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004512 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4513 Diag(diag::err_module_file_invalid)
4514 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 return Failure;
4516 }
4517
4518 // This is used for compatibility with older PCH formats.
4519 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004520 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004521 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4522 if (!MaybeEntry) {
4523 Error(MaybeEntry.takeError());
4524 return Failure;
4525 }
4526 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004527
Chris Lattnerefa77172013-01-20 00:00:22 +00004528 switch (Entry.Kind) {
4529 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004530 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004531 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 Error("invalid record at top-level of AST file");
4533 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004534
Chris Lattnerefa77172013-01-20 00:00:22 +00004535 case llvm::BitstreamEntry::SubBlock:
4536 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 }
4538
Chris Lattnerefa77172013-01-20 00:00:22 +00004539 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 case CONTROL_BLOCK_ID:
4541 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004542 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004544 // Check that we didn't try to load a non-module AST file as a module.
4545 //
4546 // FIXME: Should we also perform the converse check? Loading a module as
4547 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004548 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4549 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004550 F.ModuleName.empty()) {
4551 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4552 if (Result != OutOfDate ||
4553 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4554 Diag(diag::err_module_file_not_module) << FileName;
4555 return Result;
4556 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 break;
4558
4559 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004560 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 case OutOfDate: return OutOfDate;
4562 case VersionMismatch: return VersionMismatch;
4563 case ConfigurationMismatch: return ConfigurationMismatch;
4564 case HadErrors: return HadErrors;
4565 }
4566 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004567
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 case AST_BLOCK_ID:
4569 if (!HaveReadControlBlock) {
4570 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004571 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 return VersionMismatch;
4573 }
4574
4575 // Record that we've loaded this module.
4576 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004577 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 return Success;
4579
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004580 case UNHASHED_CONTROL_BLOCK_ID:
4581 // This block is handled using look-ahead during ReadControlBlock. We
4582 // shouldn't get here!
4583 Error("malformed block record in AST file");
4584 return Failure;
4585
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 default:
JF Bastien0e828952019-06-26 19:50:12 +00004587 if (llvm::Error Err = Stream.SkipBlock()) {
4588 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 return Failure;
4590 }
4591 break;
4592 }
4593 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004594
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004595 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004596}
4597
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004598ASTReader::ASTReadResult
4599ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4600 unsigned ClientLoadCapabilities) {
4601 const HeaderSearchOptions &HSOpts =
4602 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4603 bool AllowCompatibleConfigurationMismatch =
4604 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4605
4606 ASTReadResult Result = readUnhashedControlBlockImpl(
4607 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4608 Listener.get(),
4609 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4610
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004611 // If F was directly imported by another module, it's implicitly validated by
4612 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004613 if (DisableValidation || WasImportedBy ||
4614 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4615 return Success;
4616
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004617 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004618 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004619 return Failure;
4620 }
4621
4622 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004623 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004624 // with it; we can only load a single version of each module.
4625 //
4626 // This can happen when a module is imported in two contexts: in one, as a
4627 // user module; in another, as a system module (due to an import from
4628 // another module marked with the [system] flag). It usually indicates a
4629 // bug in the module map: this module should also be marked with [system].
4630 //
4631 // If -Wno-system-headers (the default), and the first import is as a
4632 // system module, then validation will fail during the as-user import,
4633 // since -Werror flags won't have been validated. However, it's reasonable
4634 // to treat this consistently as a system module.
4635 //
4636 // If -Wsystem-headers, the PCM on disk was built with
4637 // -Wno-system-headers, and the first import is as a user module, then
4638 // validation will fail during the as-system import since the PCM on disk
4639 // doesn't guarantee that -Werror was respected. However, the -Werror
4640 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004641 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004642 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4643 return Success;
4644 }
4645 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004646
4647 return Result;
4648}
4649
4650ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4651 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4652 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4653 bool ValidateDiagnosticOptions) {
4654 // Initialize a stream.
4655 BitstreamCursor Stream(StreamData);
4656
4657 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004658 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4659 // FIXME this drops the error on the floor.
4660 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004661 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004662 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004663
4664 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4665 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4666 return Failure;
4667
4668 // Read all of the records in the options block.
4669 RecordData Record;
4670 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004671 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004672 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4673 if (!MaybeEntry) {
4674 // FIXME this drops the error on the floor.
4675 consumeError(MaybeEntry.takeError());
4676 return Failure;
4677 }
4678 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004679
4680 switch (Entry.Kind) {
4681 case llvm::BitstreamEntry::Error:
4682 case llvm::BitstreamEntry::SubBlock:
4683 return Failure;
4684
4685 case llvm::BitstreamEntry::EndBlock:
4686 return Result;
4687
4688 case llvm::BitstreamEntry::Record:
4689 // The interesting case.
4690 break;
4691 }
4692
4693 // Read and process a record.
4694 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004695 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4696 if (!MaybeRecordType) {
4697 // FIXME this drops the error.
4698 return Failure;
4699 }
4700 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004701 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004702 if (F)
4703 std::copy(Record.begin(), Record.end(), F->Signature.data());
4704 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004705 case DIAGNOSTIC_OPTIONS: {
4706 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4707 if (Listener && ValidateDiagnosticOptions &&
4708 !AllowCompatibleConfigurationMismatch &&
4709 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004710 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004711 break;
4712 }
4713 case DIAG_PRAGMA_MAPPINGS:
4714 if (!F)
4715 break;
4716 if (F->PragmaDiagMappings.empty())
4717 F->PragmaDiagMappings.swap(Record);
4718 else
4719 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4720 Record.begin(), Record.end());
4721 break;
4722 }
4723 }
4724}
4725
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004726/// Parse a record and blob containing module file extension metadata.
4727static bool parseModuleFileExtensionMetadata(
4728 const SmallVectorImpl<uint64_t> &Record,
4729 StringRef Blob,
4730 ModuleFileExtensionMetadata &Metadata) {
4731 if (Record.size() < 4) return true;
4732
4733 Metadata.MajorVersion = Record[0];
4734 Metadata.MinorVersion = Record[1];
4735
4736 unsigned BlockNameLen = Record[2];
4737 unsigned UserInfoLen = Record[3];
4738
4739 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4740
4741 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4742 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4743 Blob.data() + BlockNameLen + UserInfoLen);
4744 return false;
4745}
4746
4747ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4748 BitstreamCursor &Stream = F.Stream;
4749
4750 RecordData Record;
4751 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004752 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4753 if (!MaybeEntry) {
4754 Error(MaybeEntry.takeError());
4755 return Failure;
4756 }
4757 llvm::BitstreamEntry Entry = MaybeEntry.get();
4758
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004759 switch (Entry.Kind) {
4760 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004761 if (llvm::Error Err = Stream.SkipBlock()) {
4762 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004763 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004764 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004765 continue;
4766
4767 case llvm::BitstreamEntry::EndBlock:
4768 return Success;
4769
4770 case llvm::BitstreamEntry::Error:
4771 return HadErrors;
4772
4773 case llvm::BitstreamEntry::Record:
4774 break;
4775 }
4776
4777 Record.clear();
4778 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004779 Expected<unsigned> MaybeRecCode =
4780 Stream.readRecord(Entry.ID, Record, &Blob);
4781 if (!MaybeRecCode) {
4782 Error(MaybeRecCode.takeError());
4783 return Failure;
4784 }
4785 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004786 case EXTENSION_METADATA: {
4787 ModuleFileExtensionMetadata Metadata;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004788 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4789 Error("malformed EXTENSION_METADATA in AST file");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004790 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004791 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004792
4793 // Find a module file extension with this block name.
4794 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4795 if (Known == ModuleFileExtensions.end()) break;
4796
4797 // Form a reader.
4798 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4799 F, Stream)) {
4800 F.ExtensionReaders.push_back(std::move(Reader));
4801 }
4802
4803 break;
4804 }
4805 }
4806 }
4807
4808 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004809}
4810
Richard Smitha7e2cc62015-05-01 01:53:09 +00004811void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004812 assert(ContextObj && "no context to initialize");
4813 ASTContext &Context = *ContextObj;
4814
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 // If there's a listener, notify them that we "read" the translation unit.
4816 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004817 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 Context.getTranslationUnitDecl());
4819
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 // FIXME: Find a better way to deal with collisions between these
4821 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004822
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 // Load the special types.
4824 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4825 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4826 if (!Context.CFConstantStringTypeDecl)
4827 Context.setCFConstantStringType(GetType(String));
4828 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004829
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4831 QualType FileType = GetType(File);
4832 if (FileType.isNull()) {
4833 Error("FILE type is NULL");
4834 return;
4835 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004836
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004838 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 Context.setFILEDecl(Typedef->getDecl());
4840 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004841 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 if (!Tag) {
4843 Error("Invalid FILE type in AST file");
4844 return;
4845 }
4846 Context.setFILEDecl(Tag->getDecl());
4847 }
4848 }
4849 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004850
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4852 QualType Jmp_bufType = GetType(Jmp_buf);
4853 if (Jmp_bufType.isNull()) {
4854 Error("jmp_buf type is NULL");
4855 return;
4856 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004857
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004859 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 Context.setjmp_bufDecl(Typedef->getDecl());
4861 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004862 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 if (!Tag) {
4864 Error("Invalid jmp_buf type in AST file");
4865 return;
4866 }
4867 Context.setjmp_bufDecl(Tag->getDecl());
4868 }
4869 }
4870 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004871
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4873 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4874 if (Sigjmp_bufType.isNull()) {
4875 Error("sigjmp_buf type is NULL");
4876 return;
4877 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004878
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004880 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 Context.setsigjmp_bufDecl(Typedef->getDecl());
4882 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004883 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 assert(Tag && "Invalid sigjmp_buf type in AST file");
4885 Context.setsigjmp_bufDecl(Tag->getDecl());
4886 }
4887 }
4888 }
4889
4890 if (unsigned ObjCIdRedef
4891 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4892 if (Context.ObjCIdRedefinitionType.isNull())
4893 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4894 }
4895
4896 if (unsigned ObjCClassRedef
4897 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4898 if (Context.ObjCClassRedefinitionType.isNull())
4899 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4900 }
4901
4902 if (unsigned ObjCSelRedef
4903 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4904 if (Context.ObjCSelRedefinitionType.isNull())
4905 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4906 }
4907
4908 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4909 QualType Ucontext_tType = GetType(Ucontext_t);
4910 if (Ucontext_tType.isNull()) {
4911 Error("ucontext_t type is NULL");
4912 return;
4913 }
4914
4915 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004916 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 Context.setucontext_tDecl(Typedef->getDecl());
4918 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004919 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 assert(Tag && "Invalid ucontext_t type in AST file");
4921 Context.setucontext_tDecl(Tag->getDecl());
4922 }
4923 }
4924 }
4925 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004926
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4928
4929 // If there were any CUDA special declarations, deserialize them.
4930 if (!CUDASpecialDeclRefs.empty()) {
4931 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4932 Context.setcudaConfigureCallDecl(
4933 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4934 }
Richard Smith56be7542014-03-21 00:33:59 +00004935
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004937 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004938 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004939 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004940 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004941 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004942 if (Import.ImportLoc.isValid())
4943 PP.makeModuleVisible(Imported, Import.ImportLoc);
4944 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004945 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 }
4947 ImportedModules.clear();
4948}
4949
4950void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004951 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004952}
4953
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004954/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004955/// else returns 0.
4956static ASTFileSignature readASTFileSignature(StringRef PCH) {
4957 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004958 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4959 // FIXME this drops the error on the floor.
4960 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004961 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004962 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004963
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004964 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4965 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004966 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004967
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004968 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004969 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004970 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004971 Expected<llvm::BitstreamEntry> MaybeEntry =
4972 Stream.advanceSkippingSubblocks();
4973 if (!MaybeEntry) {
4974 // FIXME this drops the error on the floor.
4975 consumeError(MaybeEntry.takeError());
4976 return ASTFileSignature();
4977 }
4978 llvm::BitstreamEntry Entry = MaybeEntry.get();
4979
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004980 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004981 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004982
4983 Record.clear();
4984 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004985 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4986 if (!MaybeRecord) {
4987 // FIXME this drops the error on the floor.
4988 consumeError(MaybeRecord.takeError());
4989 return ASTFileSignature();
4990 }
4991 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004992 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4993 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004994 }
4995}
4996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004997/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004998/// directly from the AST file, without actually loading the AST
4999/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005000std::string ASTReader::getOriginalSourceFile(
5001 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005002 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00005004 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00005006 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5007 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00005008 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 }
5010
5011 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00005012 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00005013
5014 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005015 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5016 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005017 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005019
Chris Lattnere7b154b2013-01-19 21:39:22 +00005020 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005021 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005022 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005023 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005024 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005025
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005026 // Scan for ORIGINAL_FILE inside the control block.
5027 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005028 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005029 Expected<llvm::BitstreamEntry> MaybeEntry =
5030 Stream.advanceSkippingSubblocks();
5031 if (!MaybeEntry) {
5032 // FIXME this drops errors on the floor.
5033 consumeError(MaybeEntry.takeError());
5034 return std::string();
5035 }
5036 llvm::BitstreamEntry Entry = MaybeEntry.get();
5037
Chris Lattnere7b154b2013-01-19 21:39:22 +00005038 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005039 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005040
Chris Lattnere7b154b2013-01-19 21:39:22 +00005041 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5042 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005043 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005045
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005047 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005048 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5049 if (!MaybeRecord) {
5050 // FIXME this drops the errors on the floor.
5051 consumeError(MaybeRecord.takeError());
5052 return std::string();
5053 }
5054 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005055 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005057}
5058
5059namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005060
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 class SimplePCHValidator : public ASTReaderListener {
5062 const LangOptions &ExistingLangOpts;
5063 const TargetOptions &ExistingTargetOpts;
5064 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005065 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005067
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 public:
5069 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5070 const TargetOptions &ExistingTargetOpts,
5071 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005072 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 FileManager &FileMgr)
5074 : ExistingLangOpts(ExistingLangOpts),
5075 ExistingTargetOpts(ExistingTargetOpts),
5076 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005077 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005078 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005079
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005080 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5081 bool AllowCompatibleDifferences) override {
5082 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5083 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005085
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005086 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5087 bool AllowCompatibleDifferences) override {
5088 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5089 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005091
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005092 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5093 StringRef SpecificModuleCachePath,
5094 bool Complain) override {
5095 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5096 ExistingModuleCachePath,
5097 nullptr, ExistingLangOpts);
5098 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005099
Craig Topper3e89dfe2014-03-13 02:13:41 +00005100 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5101 bool Complain,
5102 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005103 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005104 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 }
5106 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005107
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005108} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005109
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005110bool ASTReader::readASTFileControlBlock(
5111 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005112 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005113 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005114 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005116 // FIXME: This allows use of the VFS; we do not allow use of the
5117 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005118 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 if (!Buffer) {
5120 return true;
5121 }
5122
5123 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005124 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5125 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005126
5127 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005128 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5129 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005131 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005133 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005134 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005135 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005136
5137 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005138 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005139 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005140 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005141
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005143 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005144 bool DoneWithControlBlock = false;
5145 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005146 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5147 if (!MaybeEntry) {
5148 // FIXME this drops the error on the floor.
5149 consumeError(MaybeEntry.takeError());
5150 return true;
5151 }
5152 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005153
5154 switch (Entry.Kind) {
5155 case llvm::BitstreamEntry::SubBlock: {
5156 switch (Entry.ID) {
5157 case OPTIONS_BLOCK_ID: {
5158 std::string IgnoredSuggestedPredefines;
5159 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5160 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005161 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005162 return true;
5163 break;
5164 }
5165
5166 case INPUT_FILES_BLOCK_ID:
5167 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005168 if (llvm::Error Err = Stream.SkipBlock()) {
5169 // FIXME this drops the error on the floor.
5170 consumeError(std::move(Err));
5171 return true;
5172 }
5173 if (NeedsInputFiles &&
5174 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005175 return true;
5176 break;
5177
5178 default:
JF Bastien0e828952019-06-26 19:50:12 +00005179 if (llvm::Error Err = Stream.SkipBlock()) {
5180 // FIXME this drops the error on the floor.
5181 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005182 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005183 }
Richard Smith0516b182015-09-08 19:40:14 +00005184 break;
5185 }
5186
5187 continue;
5188 }
5189
5190 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005191 DoneWithControlBlock = true;
5192 break;
Richard Smith0516b182015-09-08 19:40:14 +00005193
5194 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005195 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005196
5197 case llvm::BitstreamEntry::Record:
5198 break;
5199 }
5200
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005201 if (DoneWithControlBlock) break;
5202
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005204 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005205 Expected<unsigned> MaybeRecCode =
5206 Stream.readRecord(Entry.ID, Record, &Blob);
5207 if (!MaybeRecCode) {
5208 // FIXME this drops the error.
5209 return Failure;
5210 }
5211 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005212 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005213 if (Record[0] != VERSION_MAJOR)
5214 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005215 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005216 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005217 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005218 case MODULE_NAME:
5219 Listener.ReadModuleName(Blob);
5220 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005221 case MODULE_DIRECTORY:
5222 ModuleDir = Blob;
5223 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005224 case MODULE_MAP_FILE: {
5225 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005226 auto Path = ReadString(Record, Idx);
5227 ResolveImportedPath(Path, ModuleDir);
5228 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005229 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005230 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005231 case INPUT_FILE_OFFSETS: {
5232 if (!NeedsInputFiles)
5233 break;
5234
5235 unsigned NumInputFiles = Record[0];
5236 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005237 const llvm::support::unaligned_uint64_t *InputFileOffs =
5238 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005239 for (unsigned I = 0; I != NumInputFiles; ++I) {
5240 // Go find this input file.
5241 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005242
5243 if (isSystemFile && !NeedsSystemInputFiles)
5244 break; // the rest are system input files
5245
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005246 BitstreamCursor &Cursor = InputFilesCursor;
5247 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005248 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5249 // FIXME this drops errors on the floor.
5250 consumeError(std::move(Err));
5251 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005252
JF Bastien0e828952019-06-26 19:50:12 +00005253 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5254 if (!MaybeCode) {
5255 // FIXME this drops errors on the floor.
5256 consumeError(MaybeCode.takeError());
5257 }
5258 unsigned Code = MaybeCode.get();
5259
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005260 RecordData Record;
5261 StringRef Blob;
5262 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005263 Expected<unsigned> MaybeRecordType =
5264 Cursor.readRecord(Code, Record, &Blob);
5265 if (!MaybeRecordType) {
5266 // FIXME this drops errors on the floor.
5267 consumeError(MaybeRecordType.takeError());
5268 }
5269 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005270 case INPUT_FILE_HASH:
5271 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005272 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005273 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005274 std::string Filename = Blob;
5275 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005276 shouldContinue = Listener.visitInputFile(
5277 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005278 break;
5279 }
5280 if (!shouldContinue)
5281 break;
5282 }
5283 break;
5284 }
5285
Richard Smithd4b230b2014-10-27 23:01:16 +00005286 case IMPORTS: {
5287 if (!NeedsImports)
5288 break;
5289
5290 unsigned Idx = 0, N = Record.size();
5291 while (Idx < N) {
5292 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005293 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5294 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005295 std::string Filename = ReadString(Record, Idx);
5296 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005297 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005298 }
5299 break;
5300 }
5301
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005302 default:
5303 // No other validation to perform.
5304 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 }
5306 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005307
5308 // Look for module file extension blocks, if requested.
5309 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005310 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005311 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5312 bool DoneWithExtensionBlock = false;
5313 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005314 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5315 if (!MaybeEntry) {
5316 // FIXME this drops the error.
5317 return true;
5318 }
5319 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005320
JF Bastien0e828952019-06-26 19:50:12 +00005321 switch (Entry.Kind) {
5322 case llvm::BitstreamEntry::SubBlock:
5323 if (llvm::Error Err = Stream.SkipBlock()) {
5324 // FIXME this drops the error on the floor.
5325 consumeError(std::move(Err));
5326 return true;
5327 }
5328 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005329
JF Bastien0e828952019-06-26 19:50:12 +00005330 case llvm::BitstreamEntry::EndBlock:
5331 DoneWithExtensionBlock = true;
5332 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005333
JF Bastien0e828952019-06-26 19:50:12 +00005334 case llvm::BitstreamEntry::Error:
5335 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005336
JF Bastien0e828952019-06-26 19:50:12 +00005337 case llvm::BitstreamEntry::Record:
5338 break;
5339 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005340
5341 Record.clear();
5342 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005343 Expected<unsigned> MaybeRecCode =
5344 Stream.readRecord(Entry.ID, Record, &Blob);
5345 if (!MaybeRecCode) {
5346 // FIXME this drops the error.
5347 return true;
5348 }
5349 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005350 case EXTENSION_METADATA: {
5351 ModuleFileExtensionMetadata Metadata;
5352 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5353 return true;
5354
5355 Listener.readModuleFileExtension(Metadata);
5356 break;
5357 }
5358 }
5359 }
5360 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005361 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005362 }
5363
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005364 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5365 if (readUnhashedControlBlockImpl(
5366 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5367 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5368 ValidateDiagnosticOptions) != Success)
5369 return true;
5370
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005371 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005372}
5373
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005374bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5375 const PCHContainerReader &PCHContainerRdr,
5376 const LangOptions &LangOpts,
5377 const TargetOptions &TargetOpts,
5378 const PreprocessorOptions &PPOpts,
5379 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005380 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5381 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005382 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005383 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005384 validator,
5385 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005386}
5387
Ben Langmuir2c9af442014-04-10 17:57:43 +00005388ASTReader::ASTReadResult
5389ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005391 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5392 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 }
5395
5396 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5397 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005398 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 RecordData Record;
5400 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005401 Expected<llvm::BitstreamEntry> MaybeEntry =
5402 F.Stream.advanceSkippingSubblocks();
5403 if (!MaybeEntry) {
5404 Error(MaybeEntry.takeError());
5405 return Failure;
5406 }
5407 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005408
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005409 switch (Entry.Kind) {
5410 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5411 case llvm::BitstreamEntry::Error:
5412 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005413 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005414 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005415 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005416 case llvm::BitstreamEntry::Record:
5417 // The interesting case.
5418 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005420
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005422 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005424 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5425 if (!MaybeKind) {
5426 Error(MaybeKind.takeError());
5427 return Failure;
5428 }
5429 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005430
5431 if ((Kind == SUBMODULE_METADATA) != First) {
5432 Error("submodule metadata record should be at beginning of block");
5433 return Failure;
5434 }
5435 First = false;
5436
5437 // Submodule information is only valid if we have a current module.
5438 // FIXME: Should we error on these cases?
5439 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5440 Kind != SUBMODULE_DEFINITION)
5441 continue;
5442
5443 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 default: // Default behavior: ignore.
5445 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005446
Richard Smith03478d92014-10-23 22:12:14 +00005447 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005448 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005450 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 }
Richard Smith03478d92014-10-23 22:12:14 +00005452
Chris Lattner0e6c9402013-01-20 02:38:54 +00005453 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005454 unsigned Idx = 0;
5455 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5456 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005457 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005458 bool IsFramework = Record[Idx++];
5459 bool IsExplicit = Record[Idx++];
5460 bool IsSystem = Record[Idx++];
5461 bool IsExternC = Record[Idx++];
5462 bool InferSubmodules = Record[Idx++];
5463 bool InferExplicitSubmodules = Record[Idx++];
5464 bool InferExportWildcard = Record[Idx++];
5465 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005466 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005467
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005468 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005469 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005471
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 // Retrieve this (sub)module from the module map, creating it if
5473 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005474 CurrentModule =
5475 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5476 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005477
5478 // FIXME: set the definition loc for CurrentModule, or call
5479 // ModMap.setInferredModuleAllowedBy()
5480
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5482 if (GlobalIndex >= SubmodulesLoaded.size() ||
5483 SubmodulesLoaded[GlobalIndex]) {
5484 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005485 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005486 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005487
Douglas Gregor7029ce12013-03-19 00:28:20 +00005488 if (!ParentModule) {
5489 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005490 // Don't emit module relocation error if we have -fno-validate-pch
5491 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5492 CurFile != F.File) {
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08005493 Error(diag::err_module_file_conflict,
5494 CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5495 F.File->getName());
Ben Langmuir2c9af442014-04-10 17:57:43 +00005496 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005497 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005498 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005499
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08005500 F.DidReadTopLevelSubmodule = true;
Douglas Gregor7029ce12013-03-19 00:28:20 +00005501 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005502 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005503 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005504
Richard Smithdd8b5332017-09-04 05:37:53 +00005505 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005506 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 CurrentModule->IsFromModuleFile = true;
5508 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005509 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 CurrentModule->InferSubmodules = InferSubmodules;
5511 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5512 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005513 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005514 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005515 if (DeserializationListener)
5516 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005517
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005519
Richard Smith8a3e39a2016-03-28 21:31:09 +00005520 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005521 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005522 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005523 CurrentModule->UnresolvedConflicts.clear();
5524 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005525
5526 // The module is available unless it's missing a requirement; relevant
5527 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5528 // Missing headers that were present when the module was built do not
5529 // make it unavailable -- if we got this far, this must be an explicitly
5530 // imported module file.
5531 CurrentModule->Requirements.clear();
5532 CurrentModule->MissingHeaders.clear();
5533 CurrentModule->IsMissingRequirement =
5534 ParentModule && ParentModule->IsMissingRequirement;
5535 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 break;
5537 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005538
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005540 std::string Filename = Blob;
5541 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005542 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005544 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5545 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005546 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5547 Error("mismatched umbrella headers in submodule");
5548 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 }
5550 }
5551 break;
5552 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005553
Richard Smith202210b2014-10-24 20:23:01 +00005554 case SUBMODULE_HEADER:
5555 case SUBMODULE_EXCLUDED_HEADER:
5556 case SUBMODULE_PRIVATE_HEADER:
5557 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005558 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5559 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005560 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005561
Richard Smith202210b2014-10-24 20:23:01 +00005562 case SUBMODULE_TEXTUAL_HEADER:
5563 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5564 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5565 // them here.
5566 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005567
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005568 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005569 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005570 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005571
5572 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005573 std::string Dirname = Blob;
5574 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005575 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005577 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5578 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005579 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5580 Error("mismatched umbrella directories in submodule");
5581 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 }
5583 }
5584 break;
5585 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005586
Guy Benyei11169dd2012-12-18 14:30:41 +00005587 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 F.BaseSubmoduleID = getTotalNumSubmodules();
5589 F.LocalNumSubmodules = Record[0];
5590 unsigned LocalBaseSubmoduleID = Record[1];
5591 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005592 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005593 // module.
5594 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005595
5596 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 // module.
5598 F.SubmoduleRemap.insertOrReplace(
5599 std::make_pair(LocalBaseSubmoduleID,
5600 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005601
Ben Langmuir52ca6782014-10-20 16:27:32 +00005602 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 break;
5605 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005606
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005607 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005609 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 Unresolved.File = &F;
5611 Unresolved.Mod = CurrentModule;
5612 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005613 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005615 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 }
5617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005618
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005619 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005621 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 Unresolved.File = &F;
5623 Unresolved.Mod = CurrentModule;
5624 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005625 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005627 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005629
5630 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005631 // the parsed, unresolved exports around.
5632 CurrentModule->UnresolvedExports.clear();
5633 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005634
5635 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005636 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5637 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005639
5640 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005641 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005642 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005643 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005644 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005645
5646 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005647 CurrentModule->ConfigMacros.push_back(Blob.str());
5648 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005649
5650 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005651 UnresolvedModuleRef Unresolved;
5652 Unresolved.File = &F;
5653 Unresolved.Mod = CurrentModule;
5654 Unresolved.ID = Record[0];
5655 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5656 Unresolved.IsWildcard = false;
5657 Unresolved.String = Blob;
5658 UnresolvedModuleRefs.push_back(Unresolved);
5659 break;
5660 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005661
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005662 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005663 if (!ContextObj)
5664 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005665 SmallVector<uint32_t, 16> Inits;
5666 for (auto &ID : Record)
5667 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005668 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005669 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005671
5672 case SUBMODULE_EXPORT_AS:
5673 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005674 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005675 break;
5676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 }
5678}
5679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005680/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005681/// structure.
5682///
5683/// This routine parses the language options from the AST file and then gives
5684/// them to the AST listener if one is set.
5685///
5686/// \returns true if the listener deems the file unacceptable, false otherwise.
5687bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5688 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005689 ASTReaderListener &Listener,
5690 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 LangOptions LangOpts;
5692 unsigned Idx = 0;
5693#define LANGOPT(Name, Bits, Default, Description) \
5694 LangOpts.Name = Record[Idx++];
5695#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5696 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5697#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005698#define SANITIZER(NAME, ID) \
5699 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005700#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005701
Ben Langmuircd98cb72015-06-23 18:20:18 +00005702 for (unsigned N = Record[Idx++]; N; --N)
5703 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5704
Vedant Kumar48b4f762018-04-14 01:40:48 +00005705 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5707 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005708
Ben Langmuird4a667a2015-06-23 18:20:23 +00005709 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005710
5711 // Comment options.
5712 for (unsigned N = Record[Idx++]; N; --N) {
5713 LangOpts.CommentOpts.BlockCommandNames.push_back(
5714 ReadString(Record, Idx));
5715 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005716 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005717
Samuel Antaoee8fb302016-01-06 13:42:12 +00005718 // OpenMP offloading options.
5719 for (unsigned N = Record[Idx++]; N; --N) {
5720 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5721 }
5722
5723 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5724
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005725 return Listener.ReadLanguageOptions(LangOpts, Complain,
5726 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727}
5728
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005729bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5730 ASTReaderListener &Listener,
5731 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 unsigned Idx = 0;
5733 TargetOptions TargetOpts;
5734 TargetOpts.Triple = ReadString(Record, Idx);
5735 TargetOpts.CPU = ReadString(Record, Idx);
5736 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737 for (unsigned N = Record[Idx++]; N; --N) {
5738 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5739 }
5740 for (unsigned N = Record[Idx++]; N; --N) {
5741 TargetOpts.Features.push_back(ReadString(Record, Idx));
5742 }
5743
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005744 return Listener.ReadTargetOptions(TargetOpts, Complain,
5745 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005746}
5747
5748bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5749 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005750 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005752#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005753#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005754 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005755#include "clang/Basic/DiagnosticOptions.def"
5756
Richard Smith3be1cb22014-08-07 00:24:21 +00005757 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005758 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005759 for (unsigned N = Record[Idx++]; N; --N)
5760 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005761
5762 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5763}
5764
5765bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5766 ASTReaderListener &Listener) {
5767 FileSystemOptions FSOpts;
5768 unsigned Idx = 0;
5769 FSOpts.WorkingDir = ReadString(Record, Idx);
5770 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5771}
5772
5773bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5774 bool Complain,
5775 ASTReaderListener &Listener) {
5776 HeaderSearchOptions HSOpts;
5777 unsigned Idx = 0;
5778 HSOpts.Sysroot = ReadString(Record, Idx);
5779
5780 // Include entries.
5781 for (unsigned N = Record[Idx++]; N; --N) {
5782 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005783 frontend::IncludeDirGroup Group
5784 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005785 bool IsFramework = Record[Idx++];
5786 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005787 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5788 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 }
5790
5791 // System header prefixes.
5792 for (unsigned N = Record[Idx++]; N; --N) {
5793 std::string Prefix = ReadString(Record, Idx);
5794 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005795 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 }
5797
5798 HSOpts.ResourceDir = ReadString(Record, Idx);
5799 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005800 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005802 HSOpts.ImplicitModuleMaps = Record[Idx++];
5803 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 HSOpts.UseBuiltinIncludes = Record[Idx++];
5805 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5806 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5807 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005808 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005809
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005810 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5811 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005812}
5813
5814bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5815 bool Complain,
5816 ASTReaderListener &Listener,
5817 std::string &SuggestedPredefines) {
5818 PreprocessorOptions PPOpts;
5819 unsigned Idx = 0;
5820
5821 // Macro definitions/undefs
5822 for (unsigned N = Record[Idx++]; N; --N) {
5823 std::string Macro = ReadString(Record, Idx);
5824 bool IsUndef = Record[Idx++];
5825 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5826 }
5827
5828 // Includes
5829 for (unsigned N = Record[Idx++]; N; --N) {
5830 PPOpts.Includes.push_back(ReadString(Record, Idx));
5831 }
5832
5833 // Macro Includes
5834 for (unsigned N = Record[Idx++]; N; --N) {
5835 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5836 }
5837
5838 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005839 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 PPOpts.ObjCXXARCStandardLibrary =
5842 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5843 SuggestedPredefines.clear();
5844 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5845 SuggestedPredefines);
5846}
5847
5848std::pair<ModuleFile *, unsigned>
5849ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5850 GlobalPreprocessedEntityMapType::iterator
5851 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005852 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 "Corrupted global preprocessed entity map");
5854 ModuleFile *M = I->second;
5855 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5856 return std::make_pair(M, LocalIndex);
5857}
5858
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005859llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005860ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5861 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5862 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5863 Mod.NumPreprocessedEntities);
5864
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005865 return llvm::make_range(PreprocessingRecord::iterator(),
5866 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005867}
5868
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005869llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005870ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005871 return llvm::make_range(
5872 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5873 ModuleDeclIterator(this, &Mod,
5874 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005875}
5876
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005877SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5878 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5879 assert(I != GlobalSkippedRangeMap.end() &&
5880 "Corrupted global skipped range map");
5881 ModuleFile *M = I->second;
5882 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5883 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5884 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5885 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5886 TranslateSourceLocation(*M, RawRange.getEnd()));
5887 assert(Range.isValid());
5888 return Range;
5889}
5890
Guy Benyei11169dd2012-12-18 14:30:41 +00005891PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5892 PreprocessedEntityID PPID = Index+1;
5893 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5894 ModuleFile &M = *PPInfo.first;
5895 unsigned LocalIndex = PPInfo.second;
5896 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5897
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 if (!PP.getPreprocessingRecord()) {
5899 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005900 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005902
5903 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005904 if (llvm::Error Err =
5905 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5906 Error(std::move(Err));
5907 return nullptr;
5908 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005909
JF Bastien0e828952019-06-26 19:50:12 +00005910 Expected<llvm::BitstreamEntry> MaybeEntry =
5911 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5912 if (!MaybeEntry) {
5913 Error(MaybeEntry.takeError());
5914 return nullptr;
5915 }
5916 llvm::BitstreamEntry Entry = MaybeEntry.get();
5917
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005918 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005919 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005920
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005922 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5923 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005924 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005925 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005927 Expected<unsigned> MaybeRecType =
5928 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5929 if (!MaybeRecType) {
5930 Error(MaybeRecType.takeError());
5931 return nullptr;
5932 }
5933 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 case PPD_MACRO_EXPANSION: {
5935 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005936 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005937 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 if (isBuiltin)
5939 Name = getLocalIdentifier(M, Record[1]);
5940 else {
Richard Smith66a81862015-05-04 02:25:31 +00005941 PreprocessedEntityID GlobalID =
5942 getGlobalPreprocessedEntityID(M, Record[1]);
5943 Def = cast<MacroDefinitionRecord>(
5944 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005945 }
5946
5947 MacroExpansion *ME;
5948 if (isBuiltin)
5949 ME = new (PPRec) MacroExpansion(Name, Range);
5950 else
5951 ME = new (PPRec) MacroExpansion(Def, Range);
5952
5953 return ME;
5954 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005955
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 case PPD_MACRO_DEFINITION: {
5957 // Decode the identifier info and then check again; if the macro is
5958 // still defined and associated with the identifier,
5959 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005960 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005961
5962 if (DeserializationListener)
5963 DeserializationListener->MacroDefinitionRead(PPID, MD);
5964
5965 return MD;
5966 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005967
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005969 const char *FullFileNameStart = Blob.data() + Record[0];
5970 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005971 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005973 if (auto FE = PP.getFileManager().getFile(FullFileName))
5974 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005977 InclusionDirective::InclusionKind Kind
5978 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5979 InclusionDirective *ID
5980 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005981 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 Record[1], Record[3],
5983 File,
5984 Range);
5985 return ID;
5986 }
5987 }
5988
5989 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5990}
5991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005992/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005993/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005994///
5995/// \param SLocMapI points at a chunk of a module that contains no
5996/// preprocessed entities or the entities it contains are not the ones we are
5997/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005998PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5999 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6000 ++SLocMapI;
6001 for (GlobalSLocOffsetMapType::const_iterator
6002 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6003 ModuleFile &M = *SLocMapI->second;
6004 if (M.NumPreprocessedEntities)
6005 return M.BasePreprocessedEntityID;
6006 }
6007
6008 return getTotalNumPreprocessedEntities();
6009}
6010
6011namespace {
6012
Guy Benyei11169dd2012-12-18 14:30:41 +00006013struct PPEntityComp {
6014 const ASTReader &Reader;
6015 ModuleFile &M;
6016
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006017 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006018
6019 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6020 SourceLocation LHS = getLoc(L);
6021 SourceLocation RHS = getLoc(R);
6022 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6023 }
6024
6025 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6026 SourceLocation LHS = getLoc(L);
6027 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6028 }
6029
6030 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6031 SourceLocation RHS = getLoc(R);
6032 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6033 }
6034
6035 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006036 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 }
6038};
6039
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006040} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006041
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006042PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6043 bool EndsAfter) const {
6044 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 return getTotalNumPreprocessedEntities();
6046
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006047 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6048 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6050 "Corrupted global sloc offset map");
6051
6052 if (SLocMapI->second->NumPreprocessedEntities == 0)
6053 return findNextPreprocessedEntity(SLocMapI);
6054
6055 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006056
6057 using pp_iterator = const PPEntityOffset *;
6058
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6060 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6061
6062 size_t Count = M.NumPreprocessedEntities;
6063 size_t Half;
6064 pp_iterator First = pp_begin;
6065 pp_iterator PPI;
6066
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006067 if (EndsAfter) {
6068 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006069 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006070 } else {
6071 // Do a binary search manually instead of using std::lower_bound because
6072 // The end locations of entities may be unordered (when a macro expansion
6073 // is inside another macro argument), but for this case it is not important
6074 // whether we get the first macro expansion or its containing macro.
6075 while (Count > 0) {
6076 Half = Count / 2;
6077 PPI = First;
6078 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006079 if (SourceMgr.isBeforeInTranslationUnit(
6080 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006081 First = PPI;
6082 ++First;
6083 Count = Count - Half - 1;
6084 } else
6085 Count = Half;
6086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 }
6088
6089 if (PPI == pp_end)
6090 return findNextPreprocessedEntity(SLocMapI);
6091
6092 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6093}
6094
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006095/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006096/// preprocessed entities that \arg Range encompasses.
6097std::pair<unsigned, unsigned>
6098 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6099 if (Range.isInvalid())
6100 return std::make_pair(0,0);
6101 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6102
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006103 PreprocessedEntityID BeginID =
6104 findPreprocessedEntity(Range.getBegin(), false);
6105 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 return std::make_pair(BeginID, EndID);
6107}
6108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006109/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006110/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006111Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 FileID FID) {
6113 if (FID.isInvalid())
6114 return false;
6115
6116 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6117 ModuleFile &M = *PPInfo.first;
6118 unsigned LocalIndex = PPInfo.second;
6119 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006120
Richard Smithcb34bd32016-03-27 07:28:06 +00006121 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (Loc.isInvalid())
6123 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006124
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6126 return true;
6127 else
6128 return false;
6129}
6130
6131namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006133 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006136 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006137
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006139 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006140
6141 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006142 HeaderFileInfoLookupTable *Table
6143 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 if (!Table)
6145 return false;
6146
6147 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006148 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 if (Pos == Table->end())
6150 return false;
6151
Richard Smithbdf2d932015-07-30 03:37:16 +00006152 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return true;
6154 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006155
David Blaikie05785d12013-02-20 22:23:23 +00006156 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006158
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006159} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006160
6161HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006162 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006163 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006164 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 return HeaderFileInfo();
6168}
6169
6170void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006171 using DiagState = DiagnosticsEngine::DiagState;
6172 SmallVector<DiagState *, 32> DiagStates;
6173
Vedant Kumar48b4f762018-04-14 01:40:48 +00006174 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006176 auto &Record = F.PragmaDiagMappings;
6177 if (Record.empty())
6178 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006179
Richard Smithd230de22017-01-26 01:01:01 +00006180 DiagStates.clear();
6181
6182 auto ReadDiagState =
6183 [&](const DiagState &BasedOn, SourceLocation Loc,
6184 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6185 unsigned BackrefID = Record[Idx++];
6186 if (BackrefID != 0)
6187 return DiagStates[BackrefID - 1];
6188
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006190 Diag.DiagStates.push_back(BasedOn);
6191 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006193 unsigned Size = Record[Idx++];
6194 assert(Idx + Size * 2 <= Record.size() &&
6195 "Invalid data, not enough diag/map pairs");
6196 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006197 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006198 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006199 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006200 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6201 continue;
6202
6203 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6204
6205 // If this mapping was specified as a warning but the severity was
6206 // upgraded due to diagnostic settings, simulate the current diagnostic
6207 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006208 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6209 NewMapping.setSeverity(diag::Severity::Warning);
6210 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006211 }
6212
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006213 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006214 }
Richard Smithd230de22017-01-26 01:01:01 +00006215 return NewState;
6216 };
6217
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006218 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006219 DiagState *FirstState;
6220 if (F.Kind == MK_ImplicitModule) {
6221 // Implicitly-built modules are reused with different diagnostic
6222 // settings. Use the initial diagnostic state from Diag to simulate this
6223 // compilation's diagnostic settings.
6224 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6225 DiagStates.push_back(FirstState);
6226
6227 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006228 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006229 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006230 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006231 assert(Idx < Record.size() &&
6232 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006233 } else if (F.isModule()) {
6234 // For an explicit module, preserve the flags from the module build
6235 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6236 // -Wblah flags.
6237 unsigned Flags = Record[Idx++];
6238 DiagState Initial;
6239 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6240 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6241 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6242 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6243 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6244 Initial.ExtBehavior = (diag::Severity)Flags;
6245 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006246
Richard Smith6c2b5a82018-02-09 01:15:13 +00006247 assert(F.OriginalSourceFileID.isValid());
6248
Richard Smithe37391c2017-05-03 00:28:49 +00006249 // Set up the root buffer of the module to start with the initial
6250 // diagnostic state of the module itself, to cover files that contain no
6251 // explicit transitions (for which we did not serialize anything).
6252 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6253 .StateTransitions.push_back({FirstState, 0});
6254 } else {
6255 // For prefix ASTs, start with whatever the user configured on the
6256 // command line.
6257 Idx++; // Skip flags.
6258 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6259 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006260 }
Richard Smithd230de22017-01-26 01:01:01 +00006261
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006262 // Read the state transitions.
6263 unsigned NumLocations = Record[Idx++];
6264 while (NumLocations--) {
6265 assert(Idx < Record.size() &&
6266 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006267 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6268 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006269 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006270 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6271 unsigned Transitions = Record[Idx++];
6272
6273 // Note that we don't need to set up Parent/ParentOffset here, because
6274 // we won't be changing the diagnostic state within imported FileIDs
6275 // (other than perhaps appending to the main source file, which has no
6276 // parent).
6277 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6278 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6279 for (unsigned I = 0; I != Transitions; ++I) {
6280 unsigned Offset = Record[Idx++];
6281 auto *State =
6282 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6283 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 }
6285 }
Richard Smithd230de22017-01-26 01:01:01 +00006286
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006287 // Read the final state.
6288 assert(Idx < Record.size() &&
6289 "Invalid data, missing final pragma diagnostic state");
6290 SourceLocation CurStateLoc =
6291 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6292 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6293
6294 if (!F.isModule()) {
6295 Diag.DiagStatesByLoc.CurDiagState = CurState;
6296 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6297
6298 // Preserve the property that the imaginary root file describes the
6299 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006300 FileID NullFile;
6301 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006302 if (T.empty())
6303 T.push_back({CurState, 0});
6304 else
6305 T[0].State = CurState;
6306 }
6307
Richard Smithd230de22017-01-26 01:01:01 +00006308 // Don't try to read these mappings again.
6309 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 }
6311}
6312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006313/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006314ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6315 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6316 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6317 ModuleFile *M = I->second;
6318 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6319}
6320
John McCalld505e572019-12-13 21:54:44 -05006321static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6322 switch (code) {
6323#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6324 case TYPE_##CODE_ID: return Type::CLASS_ID;
6325#include "clang/Serialization/TypeBitCodes.def"
6326 default: return llvm::None;
6327 }
John McCall3ce3d232019-12-13 03:37:23 -05006328}
6329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006330/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006331///
6332/// The index is the type ID, shifted and minus the number of predefs. This
6333/// routine actually reads the record corresponding to the type at the given
6334/// location. It is a helper routine for GetType, which deals with reading type
6335/// IDs.
6336QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006337 assert(ContextObj && "reading type with no AST context");
6338 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006340 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006341
6342 // Keep track of where we are in the stream, then jump back there
6343 // after reading this type.
6344 SavedStreamPosition SavedPosition(DeclsCursor);
6345
6346 ReadingKindTracker ReadingKind(Read_Type, *this);
6347
6348 // Note that we are loading a type record.
6349 Deserializing AType(this);
6350
JF Bastien0e828952019-06-26 19:50:12 +00006351 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6352 Error(std::move(Err));
6353 return QualType();
6354 }
John McCall3ce3d232019-12-13 03:37:23 -05006355 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6356 if (!RawCode) {
6357 Error(RawCode.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006358 return QualType();
6359 }
JF Bastien0e828952019-06-26 19:50:12 +00006360
John McCall3ce3d232019-12-13 03:37:23 -05006361 ASTRecordReader Record(*this, *Loc.F);
6362 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6363 if (!Code) {
6364 Error(Code.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006365 return QualType();
6366 }
John McCalld505e572019-12-13 21:54:44 -05006367 if (Code.get() == TYPE_EXT_QUAL) {
6368 QualType baseType = Record.readQualType();
6369 Qualifiers quals = Record.readQualifiers();
6370 return Context.getQualifiedType(baseType, quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 }
6372
John McCalld505e572019-12-13 21:54:44 -05006373 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6374 if (!maybeClass) {
6375 Error("Unexpected code for type");
6376 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 }
6378
John McCalld505e572019-12-13 21:54:44 -05006379 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6380 return TypeReader.read(*maybeClass);
Richard Smith564417a2014-03-20 21:47:22 +00006381}
6382
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006383namespace clang {
6384
6385class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
John McCall3ce3d232019-12-13 03:37:23 -05006386 ASTRecordReader &Reader;
Guy Benyei11169dd2012-12-18 14:30:41 +00006387
John McCall3ce3d232019-12-13 03:37:23 -05006388 SourceLocation readSourceLocation() {
6389 return Reader.readSourceLocation();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006390 }
6391
6392 TypeSourceInfo *GetTypeSourceInfo() {
John McCall3ce3d232019-12-13 03:37:23 -05006393 return Reader.readTypeSourceInfo();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006394 }
6395
6396 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
John McCall3ce3d232019-12-13 03:37:23 -05006397 return Reader.readNestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 }
6399
Richard Smithe43e2b32018-08-20 21:47:29 +00006400 Attr *ReadAttr() {
John McCall3ce3d232019-12-13 03:37:23 -05006401 return Reader.readAttr();
Richard Smithe43e2b32018-08-20 21:47:29 +00006402 }
6403
Guy Benyei11169dd2012-12-18 14:30:41 +00006404public:
John McCall3ce3d232019-12-13 03:37:23 -05006405 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006406
6407 // We want compile-time assurance that we've enumerated all of
6408 // these, so unfortunately we have to declare them first, then
6409 // define them out-of-line.
6410#define ABSTRACT_TYPELOC(CLASS, PARENT)
6411#define TYPELOC(CLASS, PARENT) \
6412 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6413#include "clang/AST/TypeLocNodes.def"
6414
6415 void VisitFunctionTypeLoc(FunctionTypeLoc);
6416 void VisitArrayTypeLoc(ArrayTypeLoc);
6417};
6418
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006419} // namespace clang
6420
Guy Benyei11169dd2012-12-18 14:30:41 +00006421void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6422 // nothing to do
6423}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006424
Guy Benyei11169dd2012-12-18 14:30:41 +00006425void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006426 TL.setBuiltinLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 if (TL.needsExtraLocalData()) {
John McCall3ce3d232019-12-13 03:37:23 -05006428 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6429 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6430 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6431 TL.setModeAttr(Reader.readInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 }
6433}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006434
Guy Benyei11169dd2012-12-18 14:30:41 +00006435void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006436 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006437}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006440 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006441}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006442
Reid Kleckner8a365022013-06-24 17:51:48 +00006443void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6444 // nothing to do
6445}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006446
Reid Kleckner0503a872013-12-05 01:23:43 +00006447void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6448 // nothing to do
6449}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006450
Leonard Chanc72aaf62019-05-07 03:20:17 +00006451void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006452 TL.setExpansionLoc(readSourceLocation());
Leonard Chanc72aaf62019-05-07 03:20:17 +00006453}
6454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006456 TL.setCaretLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006457}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006460 TL.setAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006464 TL.setAmpAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006465}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006466
Guy Benyei11169dd2012-12-18 14:30:41 +00006467void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006468 TL.setStarLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006469 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006470}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006471
Guy Benyei11169dd2012-12-18 14:30:41 +00006472void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006473 TL.setLBracketLoc(readSourceLocation());
6474 TL.setRBracketLoc(readSourceLocation());
6475 if (Reader.readBool())
6476 TL.setSizeExpr(Reader.readExpr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 else
Craig Toppera13603a2014-05-22 05:54:18 +00006478 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006479}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006480
Guy Benyei11169dd2012-12-18 14:30:41 +00006481void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6482 VisitArrayTypeLoc(TL);
6483}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006484
Guy Benyei11169dd2012-12-18 14:30:41 +00006485void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6486 VisitArrayTypeLoc(TL);
6487}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006488
Guy Benyei11169dd2012-12-18 14:30:41 +00006489void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6490 VisitArrayTypeLoc(TL);
6491}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006492
Guy Benyei11169dd2012-12-18 14:30:41 +00006493void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6494 DependentSizedArrayTypeLoc TL) {
6495 VisitArrayTypeLoc(TL);
6496}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006497
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006498void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6499 DependentAddressSpaceTypeLoc TL) {
6500
John McCall3ce3d232019-12-13 03:37:23 -05006501 TL.setAttrNameLoc(readSourceLocation());
6502 TL.setAttrOperandParensRange(Reader.readSourceRange());
6503 TL.setAttrExprOperand(Reader.readExpr());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006504}
6505
Guy Benyei11169dd2012-12-18 14:30:41 +00006506void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6507 DependentSizedExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006508 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006509}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006510
Guy Benyei11169dd2012-12-18 14:30:41 +00006511void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006512 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006513}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006514
Erich Keanef702b022018-07-13 19:46:04 +00006515void TypeLocReader::VisitDependentVectorTypeLoc(
6516 DependentVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006517 TL.setNameLoc(readSourceLocation());
Erich Keanef702b022018-07-13 19:46:04 +00006518}
6519
Guy Benyei11169dd2012-12-18 14:30:41 +00006520void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006521 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006522}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006523
Guy Benyei11169dd2012-12-18 14:30:41 +00006524void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006525 TL.setLocalRangeBegin(readSourceLocation());
6526 TL.setLParenLoc(readSourceLocation());
6527 TL.setRParenLoc(readSourceLocation());
6528 TL.setExceptionSpecRange(Reader.readSourceRange());
6529 TL.setLocalRangeEnd(readSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006530 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
John McCall3ce3d232019-12-13 03:37:23 -05006531 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 }
6533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6536 VisitFunctionTypeLoc(TL);
6537}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006538
Guy Benyei11169dd2012-12-18 14:30:41 +00006539void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6540 VisitFunctionTypeLoc(TL);
6541}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006542
Guy Benyei11169dd2012-12-18 14:30:41 +00006543void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006544 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006545}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006546
Guy Benyei11169dd2012-12-18 14:30:41 +00006547void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006548 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006549}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006550
Guy Benyei11169dd2012-12-18 14:30:41 +00006551void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006552 TL.setTypeofLoc(readSourceLocation());
6553 TL.setLParenLoc(readSourceLocation());
6554 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006558 TL.setTypeofLoc(readSourceLocation());
6559 TL.setLParenLoc(readSourceLocation());
6560 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006561 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006562}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006563
Guy Benyei11169dd2012-12-18 14:30:41 +00006564void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006565 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006566}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006567
Guy Benyei11169dd2012-12-18 14:30:41 +00006568void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006569 TL.setKWLoc(readSourceLocation());
6570 TL.setLParenLoc(readSourceLocation());
6571 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006572 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006573}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006574
Guy Benyei11169dd2012-12-18 14:30:41 +00006575void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006576 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006577}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006578
Richard Smith600b5262017-01-26 20:40:47 +00006579void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6580 DeducedTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006581 TL.setTemplateNameLoc(readSourceLocation());
Richard Smith600b5262017-01-26 20:40:47 +00006582}
6583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006585 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006586}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006587
Guy Benyei11169dd2012-12-18 14:30:41 +00006588void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006589 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006590}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006593 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006594}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006597 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006598}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6601 SubstTemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006602 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006603}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006604
Guy Benyei11169dd2012-12-18 14:30:41 +00006605void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6606 SubstTemplateTypeParmPackTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006607 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006608}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006609
Guy Benyei11169dd2012-12-18 14:30:41 +00006610void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6611 TemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006612 TL.setTemplateKeywordLoc(readSourceLocation());
6613 TL.setTemplateNameLoc(readSourceLocation());
6614 TL.setLAngleLoc(readSourceLocation());
6615 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006616 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006617 TL.setArgLocInfo(
6618 i,
John McCall3ce3d232019-12-13 03:37:23 -05006619 Reader.readTemplateArgumentLocInfo(
6620 TL.getTypePtr()->getArg(i).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006621}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006624 TL.setLParenLoc(readSourceLocation());
6625 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006626}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006627
Guy Benyei11169dd2012-12-18 14:30:41 +00006628void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006629 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006630 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006631}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006634 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006635}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006636
Guy Benyei11169dd2012-12-18 14:30:41 +00006637void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006638 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006639 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006640 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006641}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6644 DependentTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006645 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006646 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006647 TL.setTemplateKeywordLoc(readSourceLocation());
6648 TL.setTemplateNameLoc(readSourceLocation());
6649 TL.setLAngleLoc(readSourceLocation());
6650 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006652 TL.setArgLocInfo(
6653 I,
John McCall3ce3d232019-12-13 03:37:23 -05006654 Reader.readTemplateArgumentLocInfo(
6655 TL.getTypePtr()->getArg(I).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006657
Guy Benyei11169dd2012-12-18 14:30:41 +00006658void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006659 TL.setEllipsisLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006660}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006661
Guy Benyei11169dd2012-12-18 14:30:41 +00006662void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006663 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006664}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006665
Manman Rene6be26c2016-09-13 17:25:08 +00006666void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6667 if (TL.getNumProtocols()) {
John McCall3ce3d232019-12-13 03:37:23 -05006668 TL.setProtocolLAngleLoc(readSourceLocation());
6669 TL.setProtocolRAngleLoc(readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006670 }
6671 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006672 TL.setProtocolLoc(i, readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006673}
6674
Guy Benyei11169dd2012-12-18 14:30:41 +00006675void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006676 TL.setHasBaseTypeAsWritten(Reader.readBool());
6677 TL.setTypeArgsLAngleLoc(readSourceLocation());
6678 TL.setTypeArgsRAngleLoc(readSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006679 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006680 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
John McCall3ce3d232019-12-13 03:37:23 -05006681 TL.setProtocolLAngleLoc(readSourceLocation());
6682 TL.setProtocolRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006684 TL.setProtocolLoc(i, readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006685}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006686
Guy Benyei11169dd2012-12-18 14:30:41 +00006687void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006688 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006689}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006690
Guy Benyei11169dd2012-12-18 14:30:41 +00006691void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006692 TL.setKWLoc(readSourceLocation());
6693 TL.setLParenLoc(readSourceLocation());
6694 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006695}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006696
Xiuli Pan9c14e282016-01-09 12:53:17 +00006697void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006698 TL.setKWLoc(readSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006699}
Guy Benyei11169dd2012-12-18 14:30:41 +00006700
John McCall3ce3d232019-12-13 03:37:23 -05006701void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6702 TypeLocReader TLR(*this);
Richard Smithc23d7342018-06-29 20:46:25 +00006703 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6704 TLR.Visit(TL);
6705}
6706
John McCall3ce3d232019-12-13 03:37:23 -05006707TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6708 QualType InfoTy = readType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006710 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006711
6712 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
John McCall3ce3d232019-12-13 03:37:23 -05006713 readTypeLoc(TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 return TInfo;
6715}
6716
6717QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006718 assert(ContextObj && "reading type with no AST context");
6719 ASTContext &Context = *ContextObj;
6720
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 unsigned FastQuals = ID & Qualifiers::FastMask;
6722 unsigned Index = ID >> Qualifiers::FastWidth;
6723
6724 if (Index < NUM_PREDEF_TYPE_IDS) {
6725 QualType T;
6726 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006727 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006728 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006729 case PREDEF_TYPE_VOID_ID:
6730 T = Context.VoidTy;
6731 break;
6732 case PREDEF_TYPE_BOOL_ID:
6733 T = Context.BoolTy;
6734 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006735 case PREDEF_TYPE_CHAR_U_ID:
6736 case PREDEF_TYPE_CHAR_S_ID:
6737 // FIXME: Check that the signedness of CharTy is correct!
6738 T = Context.CharTy;
6739 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006740 case PREDEF_TYPE_UCHAR_ID:
6741 T = Context.UnsignedCharTy;
6742 break;
6743 case PREDEF_TYPE_USHORT_ID:
6744 T = Context.UnsignedShortTy;
6745 break;
6746 case PREDEF_TYPE_UINT_ID:
6747 T = Context.UnsignedIntTy;
6748 break;
6749 case PREDEF_TYPE_ULONG_ID:
6750 T = Context.UnsignedLongTy;
6751 break;
6752 case PREDEF_TYPE_ULONGLONG_ID:
6753 T = Context.UnsignedLongLongTy;
6754 break;
6755 case PREDEF_TYPE_UINT128_ID:
6756 T = Context.UnsignedInt128Ty;
6757 break;
6758 case PREDEF_TYPE_SCHAR_ID:
6759 T = Context.SignedCharTy;
6760 break;
6761 case PREDEF_TYPE_WCHAR_ID:
6762 T = Context.WCharTy;
6763 break;
6764 case PREDEF_TYPE_SHORT_ID:
6765 T = Context.ShortTy;
6766 break;
6767 case PREDEF_TYPE_INT_ID:
6768 T = Context.IntTy;
6769 break;
6770 case PREDEF_TYPE_LONG_ID:
6771 T = Context.LongTy;
6772 break;
6773 case PREDEF_TYPE_LONGLONG_ID:
6774 T = Context.LongLongTy;
6775 break;
6776 case PREDEF_TYPE_INT128_ID:
6777 T = Context.Int128Ty;
6778 break;
6779 case PREDEF_TYPE_HALF_ID:
6780 T = Context.HalfTy;
6781 break;
6782 case PREDEF_TYPE_FLOAT_ID:
6783 T = Context.FloatTy;
6784 break;
6785 case PREDEF_TYPE_DOUBLE_ID:
6786 T = Context.DoubleTy;
6787 break;
6788 case PREDEF_TYPE_LONGDOUBLE_ID:
6789 T = Context.LongDoubleTy;
6790 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006791 case PREDEF_TYPE_SHORT_ACCUM_ID:
6792 T = Context.ShortAccumTy;
6793 break;
6794 case PREDEF_TYPE_ACCUM_ID:
6795 T = Context.AccumTy;
6796 break;
6797 case PREDEF_TYPE_LONG_ACCUM_ID:
6798 T = Context.LongAccumTy;
6799 break;
6800 case PREDEF_TYPE_USHORT_ACCUM_ID:
6801 T = Context.UnsignedShortAccumTy;
6802 break;
6803 case PREDEF_TYPE_UACCUM_ID:
6804 T = Context.UnsignedAccumTy;
6805 break;
6806 case PREDEF_TYPE_ULONG_ACCUM_ID:
6807 T = Context.UnsignedLongAccumTy;
6808 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006809 case PREDEF_TYPE_SHORT_FRACT_ID:
6810 T = Context.ShortFractTy;
6811 break;
6812 case PREDEF_TYPE_FRACT_ID:
6813 T = Context.FractTy;
6814 break;
6815 case PREDEF_TYPE_LONG_FRACT_ID:
6816 T = Context.LongFractTy;
6817 break;
6818 case PREDEF_TYPE_USHORT_FRACT_ID:
6819 T = Context.UnsignedShortFractTy;
6820 break;
6821 case PREDEF_TYPE_UFRACT_ID:
6822 T = Context.UnsignedFractTy;
6823 break;
6824 case PREDEF_TYPE_ULONG_FRACT_ID:
6825 T = Context.UnsignedLongFractTy;
6826 break;
6827 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6828 T = Context.SatShortAccumTy;
6829 break;
6830 case PREDEF_TYPE_SAT_ACCUM_ID:
6831 T = Context.SatAccumTy;
6832 break;
6833 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6834 T = Context.SatLongAccumTy;
6835 break;
6836 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6837 T = Context.SatUnsignedShortAccumTy;
6838 break;
6839 case PREDEF_TYPE_SAT_UACCUM_ID:
6840 T = Context.SatUnsignedAccumTy;
6841 break;
6842 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6843 T = Context.SatUnsignedLongAccumTy;
6844 break;
6845 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6846 T = Context.SatShortFractTy;
6847 break;
6848 case PREDEF_TYPE_SAT_FRACT_ID:
6849 T = Context.SatFractTy;
6850 break;
6851 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6852 T = Context.SatLongFractTy;
6853 break;
6854 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6855 T = Context.SatUnsignedShortFractTy;
6856 break;
6857 case PREDEF_TYPE_SAT_UFRACT_ID:
6858 T = Context.SatUnsignedFractTy;
6859 break;
6860 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6861 T = Context.SatUnsignedLongFractTy;
6862 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006863 case PREDEF_TYPE_FLOAT16_ID:
6864 T = Context.Float16Ty;
6865 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006866 case PREDEF_TYPE_FLOAT128_ID:
6867 T = Context.Float128Ty;
6868 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006869 case PREDEF_TYPE_OVERLOAD_ID:
6870 T = Context.OverloadTy;
6871 break;
6872 case PREDEF_TYPE_BOUND_MEMBER:
6873 T = Context.BoundMemberTy;
6874 break;
6875 case PREDEF_TYPE_PSEUDO_OBJECT:
6876 T = Context.PseudoObjectTy;
6877 break;
6878 case PREDEF_TYPE_DEPENDENT_ID:
6879 T = Context.DependentTy;
6880 break;
6881 case PREDEF_TYPE_UNKNOWN_ANY:
6882 T = Context.UnknownAnyTy;
6883 break;
6884 case PREDEF_TYPE_NULLPTR_ID:
6885 T = Context.NullPtrTy;
6886 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006887 case PREDEF_TYPE_CHAR8_ID:
6888 T = Context.Char8Ty;
6889 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006890 case PREDEF_TYPE_CHAR16_ID:
6891 T = Context.Char16Ty;
6892 break;
6893 case PREDEF_TYPE_CHAR32_ID:
6894 T = Context.Char32Ty;
6895 break;
6896 case PREDEF_TYPE_OBJC_ID:
6897 T = Context.ObjCBuiltinIdTy;
6898 break;
6899 case PREDEF_TYPE_OBJC_CLASS:
6900 T = Context.ObjCBuiltinClassTy;
6901 break;
6902 case PREDEF_TYPE_OBJC_SEL:
6903 T = Context.ObjCBuiltinSelTy;
6904 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006905#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6906 case PREDEF_TYPE_##Id##_ID: \
6907 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006908 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006909#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006910#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6911 case PREDEF_TYPE_##Id##_ID: \
6912 T = Context.Id##Ty; \
6913 break;
6914#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006915 case PREDEF_TYPE_SAMPLER_ID:
6916 T = Context.OCLSamplerTy;
6917 break;
6918 case PREDEF_TYPE_EVENT_ID:
6919 T = Context.OCLEventTy;
6920 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006921 case PREDEF_TYPE_CLK_EVENT_ID:
6922 T = Context.OCLClkEventTy;
6923 break;
6924 case PREDEF_TYPE_QUEUE_ID:
6925 T = Context.OCLQueueTy;
6926 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006927 case PREDEF_TYPE_RESERVE_ID_ID:
6928 T = Context.OCLReserveIDTy;
6929 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006930 case PREDEF_TYPE_AUTO_DEDUCT:
6931 T = Context.getAutoDeductType();
6932 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006933 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6934 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6937 T = Context.ARCUnbridgedCastTy;
6938 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 case PREDEF_TYPE_BUILTIN_FN:
6940 T = Context.BuiltinFnTy;
6941 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006942 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6943 T = Context.OMPArraySectionTy;
6944 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006945#define SVE_TYPE(Name, Id, SingletonId) \
6946 case PREDEF_TYPE_##Id##_ID: \
6947 T = Context.SingletonId; \
6948 break;
6949#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 }
6951
6952 assert(!T.isNull() && "Unknown predefined type");
6953 return T.withFastQualifiers(FastQuals);
6954 }
6955
6956 Index -= NUM_PREDEF_TYPE_IDS;
6957 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6958 if (TypesLoaded[Index].isNull()) {
6959 TypesLoaded[Index] = readTypeRecord(Index);
6960 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006961 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006962
6963 TypesLoaded[Index]->setFromAST();
6964 if (DeserializationListener)
6965 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6966 TypesLoaded[Index]);
6967 }
6968
6969 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6970}
6971
6972QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6973 return GetType(getGlobalTypeID(F, LocalID));
6974}
6975
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006976serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006977ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6978 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6979 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006980
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6982 return LocalID;
6983
Richard Smith37a93df2017-02-18 00:32:02 +00006984 if (!F.ModuleOffsetMap.empty())
6985 ReadModuleOffsetMap(F);
6986
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6988 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6989 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006990
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 unsigned GlobalIndex = LocalIndex + I->second;
6992 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6993}
6994
6995TemplateArgumentLocInfo
John McCall3ce3d232019-12-13 03:37:23 -05006996ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 switch (Kind) {
6998 case TemplateArgument::Expression:
John McCall3ce3d232019-12-13 03:37:23 -05006999 return readExpr();
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 case TemplateArgument::Type:
John McCall3ce3d232019-12-13 03:37:23 -05007001 return readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 case TemplateArgument::Template: {
John McCall3ce3d232019-12-13 03:37:23 -05007003 NestedNameSpecifierLoc QualifierLoc =
7004 readNestedNameSpecifierLoc();
7005 SourceLocation TemplateNameLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7007 SourceLocation());
7008 }
7009 case TemplateArgument::TemplateExpansion: {
John McCall3ce3d232019-12-13 03:37:23 -05007010 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7011 SourceLocation TemplateNameLoc = readSourceLocation();
7012 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007013 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 EllipsisLoc);
7015 }
7016 case TemplateArgument::Null:
7017 case TemplateArgument::Integral:
7018 case TemplateArgument::Declaration:
7019 case TemplateArgument::NullPtr:
7020 case TemplateArgument::Pack:
7021 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007022 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 }
7024 llvm_unreachable("unexpected template argument loc");
7025}
7026
John McCall3ce3d232019-12-13 03:37:23 -05007027TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7028 TemplateArgument Arg = readTemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00007029
7030 if (Arg.getKind() == TemplateArgument::Expression) {
John McCall3ce3d232019-12-13 03:37:23 -05007031 if (readBool()) // bool InfoHasSameExpr.
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7033 }
John McCall3ce3d232019-12-13 03:37:23 -05007034 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00007035}
7036
John McCall3ce3d232019-12-13 03:37:23 -05007037const ASTTemplateArgumentListInfo *
7038ASTRecordReader::readASTTemplateArgumentListInfo() {
7039 SourceLocation LAngleLoc = readSourceLocation();
7040 SourceLocation RAngleLoc = readSourceLocation();
7041 unsigned NumArgsAsWritten = readInt();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007042 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7043 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05007044 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007045 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7046}
7047
Guy Benyei11169dd2012-12-18 14:30:41 +00007048Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7049 return GetDecl(ID);
7050}
7051
Richard Smith053f6c62014-05-16 23:01:30 +00007052void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007053 if (NumCurrentElementsDeserializing) {
7054 // We arrange to not care about the complete redeclaration chain while we're
7055 // deserializing. Just remember that the AST has marked this one as complete
7056 // but that it's not actually complete yet, so we know we still need to
7057 // complete it later.
7058 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7059 return;
7060 }
7061
Richard Smith053f6c62014-05-16 23:01:30 +00007062 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7063
Richard Smith053f6c62014-05-16 23:01:30 +00007064 // If this is a named declaration, complete it by looking it up
7065 // within its context.
7066 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007067 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007068 // all mergeable entities within it.
7069 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7070 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7071 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007072 if (!getContext().getLangOpts().CPlusPlus &&
7073 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007074 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007075 // the identifier instead. (For C++ modules, we don't store decls
7076 // in the serialized identifier table, so we do the lookup in the TU.)
7077 auto *II = Name.getAsIdentifierInfo();
7078 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007079 if (II->isOutOfDate())
7080 updateOutOfDateIdentifier(*II);
7081 } else
7082 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007083 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007084 // Find all declarations of this kind from the relevant context.
7085 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7086 auto *DC = cast<DeclContext>(DCDecl);
7087 SmallVector<Decl*, 8> Decls;
7088 FindExternalLexicalDecls(
7089 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7090 }
Richard Smith053f6c62014-05-16 23:01:30 +00007091 }
7092 }
Richard Smith50895422015-01-31 03:04:55 +00007093
7094 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7095 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7096 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7097 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7098 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7099 if (auto *Template = FD->getPrimaryTemplate())
7100 Template->LoadLazySpecializations();
7101 }
Richard Smith053f6c62014-05-16 23:01:30 +00007102}
7103
Richard Smithc2bb8182015-03-24 06:36:48 +00007104CXXCtorInitializer **
7105ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7106 RecordLocation Loc = getLocalBitOffset(Offset);
7107 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7108 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007109 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7110 Error(std::move(Err));
7111 return nullptr;
7112 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007113 ReadingKindTracker ReadingKind(Read_Decl, *this);
7114
JF Bastien0e828952019-06-26 19:50:12 +00007115 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7116 if (!MaybeCode) {
7117 Error(MaybeCode.takeError());
7118 return nullptr;
7119 }
7120 unsigned Code = MaybeCode.get();
7121
John McCall3ce3d232019-12-13 03:37:23 -05007122 ASTRecordReader Record(*this, *Loc.F);
7123 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007124 if (!MaybeRecCode) {
7125 Error(MaybeRecCode.takeError());
7126 return nullptr;
7127 }
7128 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007129 Error("malformed AST file: missing C++ ctor initializers");
7130 return nullptr;
7131 }
7132
John McCall3ce3d232019-12-13 03:37:23 -05007133 return Record.readCXXCtorInitializers();
Richard Smithc2bb8182015-03-24 06:36:48 +00007134}
7135
Guy Benyei11169dd2012-12-18 14:30:41 +00007136CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007137 assert(ContextObj && "reading base specifiers with no AST context");
7138 ASTContext &Context = *ContextObj;
7139
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007141 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007143 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7144 Error(std::move(Err));
7145 return nullptr;
7146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 ReadingKindTracker ReadingKind(Read_Decl, *this);
JF Bastien0e828952019-06-26 19:50:12 +00007148
7149 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7150 if (!MaybeCode) {
7151 Error(MaybeCode.takeError());
7152 return nullptr;
7153 }
7154 unsigned Code = MaybeCode.get();
7155
John McCall3ce3d232019-12-13 03:37:23 -05007156 ASTRecordReader Record(*this, *Loc.F);
7157 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007158 if (!MaybeRecCode) {
7159 Error(MaybeCode.takeError());
7160 return nullptr;
7161 }
7162 unsigned RecCode = MaybeRecCode.get();
7163
Guy Benyei11169dd2012-12-18 14:30:41 +00007164 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007165 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007166 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 }
7168
John McCall3ce3d232019-12-13 03:37:23 -05007169 unsigned NumBases = Record.readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007171 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 for (unsigned I = 0; I != NumBases; ++I)
John McCall3ce3d232019-12-13 03:37:23 -05007173 Bases[I] = Record.readCXXBaseSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 return Bases;
7175}
7176
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007177serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007178ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7179 if (LocalID < NUM_PREDEF_DECL_IDS)
7180 return LocalID;
7181
Richard Smith37a93df2017-02-18 00:32:02 +00007182 if (!F.ModuleOffsetMap.empty())
7183 ReadModuleOffsetMap(F);
7184
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7186 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7187 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007188
Guy Benyei11169dd2012-12-18 14:30:41 +00007189 return LocalID + I->second;
7190}
7191
7192bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7193 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007194 // Predefined decls aren't from any module.
7195 if (ID < NUM_PREDEF_DECL_IDS)
7196 return false;
7197
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007198 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007199 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007200}
7201
Douglas Gregor9f782892013-01-21 15:25:38 +00007202ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007204 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007205 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7206 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7207 return I->second;
7208}
7209
7210SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7211 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007212 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007213
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7215
7216 if (Index > DeclsLoaded.size()) {
7217 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007218 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007220
Guy Benyei11169dd2012-12-18 14:30:41 +00007221 if (Decl *D = DeclsLoaded[Index])
7222 return D->getLocation();
7223
Richard Smithcb34bd32016-03-27 07:28:06 +00007224 SourceLocation Loc;
7225 DeclCursorForID(ID, Loc);
7226 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007227}
7228
Richard Smithfe620d22015-03-05 23:24:12 +00007229static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7230 switch (ID) {
7231 case PREDEF_DECL_NULL_ID:
7232 return nullptr;
7233
7234 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7235 return Context.getTranslationUnitDecl();
7236
7237 case PREDEF_DECL_OBJC_ID_ID:
7238 return Context.getObjCIdDecl();
7239
7240 case PREDEF_DECL_OBJC_SEL_ID:
7241 return Context.getObjCSelDecl();
7242
7243 case PREDEF_DECL_OBJC_CLASS_ID:
7244 return Context.getObjCClassDecl();
7245
7246 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7247 return Context.getObjCProtocolDecl();
7248
7249 case PREDEF_DECL_INT_128_ID:
7250 return Context.getInt128Decl();
7251
7252 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7253 return Context.getUInt128Decl();
7254
7255 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7256 return Context.getObjCInstanceTypeDecl();
7257
7258 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7259 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007260
Richard Smith9b88a4c2015-07-27 05:40:23 +00007261 case PREDEF_DECL_VA_LIST_TAG:
7262 return Context.getVaListTagDecl();
7263
Charles Davisc7d5c942015-09-17 20:55:33 +00007264 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7265 return Context.getBuiltinMSVaListDecl();
7266
Richard Smithf19e1272015-03-07 00:04:49 +00007267 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7268 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007269
7270 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7271 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007272
7273 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7274 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007275
7276 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7277 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007278
7279 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7280 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007281 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007282 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007283}
7284
Richard Smithcd45dbc2014-04-19 03:48:30 +00007285Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007286 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007287 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007288 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007289 if (D) {
7290 // Track that we have merged the declaration with ID \p ID into the
7291 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007292 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007293 if (Merged.empty())
7294 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 }
Richard Smithfe620d22015-03-05 23:24:12 +00007296 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007298
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7300
7301 if (Index >= DeclsLoaded.size()) {
7302 assert(0 && "declaration ID out-of-range for AST file");
7303 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007304 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007305 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007306
7307 return DeclsLoaded[Index];
7308}
7309
7310Decl *ASTReader::GetDecl(DeclID ID) {
7311 if (ID < NUM_PREDEF_DECL_IDS)
7312 return GetExistingDecl(ID);
7313
7314 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7315
7316 if (Index >= DeclsLoaded.size()) {
7317 assert(0 && "declaration ID out-of-range for AST file");
7318 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007319 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007320 }
7321
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 if (!DeclsLoaded[Index]) {
7323 ReadDeclRecord(ID);
7324 if (DeserializationListener)
7325 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7326 }
7327
7328 return DeclsLoaded[Index];
7329}
7330
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007331DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 DeclID GlobalID) {
7333 if (GlobalID < NUM_PREDEF_DECL_IDS)
7334 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007335
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7337 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7338 ModuleFile *Owner = I->second;
7339
7340 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7341 = M.GlobalToLocalDeclIDs.find(Owner);
7342 if (Pos == M.GlobalToLocalDeclIDs.end())
7343 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007344
Guy Benyei11169dd2012-12-18 14:30:41 +00007345 return GlobalID - Owner->BaseDeclID + Pos->second;
7346}
7347
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007348serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007349 const RecordData &Record,
7350 unsigned &Idx) {
7351 if (Idx >= Record.size()) {
7352 Error("Corrupted AST file");
7353 return 0;
7354 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007355
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 return getGlobalDeclID(F, Record[Idx++]);
7357}
7358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007359/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007360///
7361/// This operation will read a new statement from the external
7362/// source each time it is called, and is meant to be used via a
7363/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7364Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7365 // Switch case IDs are per Decl.
7366 ClearSwitchCaseIDs();
7367
7368 // Offset here is a global offset across the entire chain.
7369 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007370 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7371 Error(std::move(Err));
7372 return nullptr;
7373 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007374 assert(NumCurrentElementsDeserializing == 0 &&
7375 "should not be called while already deserializing");
7376 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 return ReadStmtFromStream(*Loc.F);
7378}
7379
Richard Smith3cb15722015-08-05 22:41:45 +00007380void ASTReader::FindExternalLexicalDecls(
7381 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7382 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007383 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7384
Richard Smith9ccdd932015-08-06 22:14:12 +00007385 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007386 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7387 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7388 auto K = (Decl::Kind)+LexicalDecls[I];
7389 if (!IsKindWeWant(K))
7390 continue;
7391
7392 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7393
7394 // Don't add predefined declarations to the lexical context more
7395 // than once.
7396 if (ID < NUM_PREDEF_DECL_IDS) {
7397 if (PredefsVisited[ID])
7398 continue;
7399
7400 PredefsVisited[ID] = true;
7401 }
7402
7403 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007404 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007405 if (!DC->isDeclInLexicalTraversal(D))
7406 Decls.push_back(D);
7407 }
7408 }
7409 };
7410
7411 if (isa<TranslationUnitDecl>(DC)) {
7412 for (auto Lexical : TULexicalDecls)
7413 Visit(Lexical.first, Lexical.second);
7414 } else {
7415 auto I = LexicalDecls.find(DC);
7416 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007417 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007418 }
7419
Guy Benyei11169dd2012-12-18 14:30:41 +00007420 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007421}
7422
7423namespace {
7424
7425class DeclIDComp {
7426 ASTReader &Reader;
7427 ModuleFile &Mod;
7428
7429public:
7430 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7431
7432 bool operator()(LocalDeclID L, LocalDeclID R) const {
7433 SourceLocation LHS = getLocation(L);
7434 SourceLocation RHS = getLocation(R);
7435 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7436 }
7437
7438 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7439 SourceLocation RHS = getLocation(R);
7440 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7441 }
7442
7443 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7444 SourceLocation LHS = getLocation(L);
7445 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7446 }
7447
7448 SourceLocation getLocation(LocalDeclID ID) const {
7449 return Reader.getSourceManager().getFileLoc(
7450 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7451 }
7452};
7453
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007454} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007455
7456void ASTReader::FindFileRegionDecls(FileID File,
7457 unsigned Offset, unsigned Length,
7458 SmallVectorImpl<Decl *> &Decls) {
7459 SourceManager &SM = getSourceManager();
7460
7461 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7462 if (I == FileDeclIDs.end())
7463 return;
7464
7465 FileDeclsInfo &DInfo = I->second;
7466 if (DInfo.Decls.empty())
7467 return;
7468
7469 SourceLocation
7470 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7471 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7472
7473 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007474 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7475 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 if (BeginIt != DInfo.Decls.begin())
7477 --BeginIt;
7478
7479 // If we are pointing at a top-level decl inside an objc container, we need
7480 // to backtrack until we find it otherwise we will fail to report that the
7481 // region overlaps with an objc container.
7482 while (BeginIt != DInfo.Decls.begin() &&
7483 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7484 ->isTopLevelDeclInObjCContainer())
7485 --BeginIt;
7486
Fangrui Song7264a472019-07-03 08:13:17 +00007487 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7488 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 if (EndIt != DInfo.Decls.end())
7490 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007491
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 for (ArrayRef<serialization::LocalDeclID>::iterator
7493 DIt = BeginIt; DIt != EndIt; ++DIt)
7494 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7495}
7496
Richard Smith9ce12e32013-02-07 03:30:24 +00007497bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007498ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7499 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007500 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007501 "DeclContext has no visible decls in storage");
7502 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007503 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007504
Richard Smithd88a7f12015-09-01 20:35:42 +00007505 auto It = Lookups.find(DC);
7506 if (It == Lookups.end())
7507 return false;
7508
Richard Smith8c913ec2014-08-14 02:21:01 +00007509 Deserializing LookupResults(this);
7510
Richard Smithd88a7f12015-09-01 20:35:42 +00007511 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007513 for (DeclID ID : It->second.Table.find(Name)) {
7514 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007515 if (ND->getDeclName() == Name)
7516 Decls.push_back(ND);
7517 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007518
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 ++NumVisibleDeclContextsRead;
7520 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007521 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007522}
7523
Guy Benyei11169dd2012-12-18 14:30:41 +00007524void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7525 if (!DC->hasExternalVisibleStorage())
7526 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007527
7528 auto It = Lookups.find(DC);
7529 assert(It != Lookups.end() &&
7530 "have external visible storage but no lookup tables");
7531
Craig Topper79be4cd2013-07-05 04:33:53 +00007532 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007533
Vedant Kumar48b4f762018-04-14 01:40:48 +00007534 for (DeclID ID : It->second.Table.findAll()) {
7535 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007536 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 }
7538
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 ++NumVisibleDeclContextsRead;
7540
Vedant Kumar48b4f762018-04-14 01:40:48 +00007541 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7542 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7543 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7545}
7546
Richard Smithd88a7f12015-09-01 20:35:42 +00007547const serialization::reader::DeclContextLookupTable *
7548ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7549 auto I = Lookups.find(Primary);
7550 return I == Lookups.end() ? nullptr : &I->second;
7551}
7552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007553/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007554/// before receiving the implementation, and codegen depends on this.
7555/// We simulate this by deserializing and passing to consumer the methods of the
7556/// implementation before passing the deserialized implementation decl.
7557static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7558 ASTConsumer *Consumer) {
7559 assert(ImplD && Consumer);
7560
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007561 for (auto *I : ImplD->methods())
7562 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007563
7564 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7565}
7566
Guy Benyei11169dd2012-12-18 14:30:41 +00007567void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007568 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 PassObjCImplDeclToConsumer(ImplD, Consumer);
7570 else
7571 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7572}
7573
7574void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7575 this->Consumer = Consumer;
7576
Richard Smith9e2341d2015-03-23 03:25:59 +00007577 if (Consumer)
7578 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007579
7580 if (DeserializationListener)
7581 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007582}
7583
7584void ASTReader::PrintStats() {
7585 std::fprintf(stderr, "*** AST File Statistics:\n");
7586
7587 unsigned NumTypesLoaded
7588 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7589 QualType());
7590 unsigned NumDeclsLoaded
7591 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007592 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 unsigned NumIdentifiersLoaded
7594 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7595 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007596 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 unsigned NumMacrosLoaded
7598 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7599 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007600 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007601 unsigned NumSelectorsLoaded
7602 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7603 SelectorsLoaded.end(),
7604 Selector());
7605
7606 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7607 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7608 NumSLocEntriesRead, TotalNumSLocEntries,
7609 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7610 if (!TypesLoaded.empty())
7611 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7612 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7613 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7614 if (!DeclsLoaded.empty())
7615 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7616 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7617 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7618 if (!IdentifiersLoaded.empty())
7619 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7620 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7621 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7622 if (!MacrosLoaded.empty())
7623 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7624 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7625 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7626 if (!SelectorsLoaded.empty())
7627 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7628 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7629 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7630 if (TotalNumStatements)
7631 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7632 NumStatementsRead, TotalNumStatements,
7633 ((float)NumStatementsRead/TotalNumStatements * 100));
7634 if (TotalNumMacros)
7635 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7636 NumMacrosRead, TotalNumMacros,
7637 ((float)NumMacrosRead/TotalNumMacros * 100));
7638 if (TotalLexicalDeclContexts)
7639 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7640 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7641 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7642 * 100));
7643 if (TotalVisibleDeclContexts)
7644 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7645 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7646 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7647 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007648 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7650 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7651 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7652 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007653 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007654 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7655 NumMethodPoolHits, NumMethodPoolLookups,
7656 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007657 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007658 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7659 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7660 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7661 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007662 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007663 std::fprintf(stderr,
7664 " %u / %u identifier table lookups succeeded (%f%%)\n",
7665 NumIdentifierLookupHits, NumIdentifierLookups,
7666 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007667
Douglas Gregore060e572013-01-25 01:03:03 +00007668 if (GlobalIndex) {
7669 std::fprintf(stderr, "\n");
7670 GlobalIndex->printStats();
7671 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007672
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 std::fprintf(stderr, "\n");
7674 dump();
7675 std::fprintf(stderr, "\n");
7676}
7677
7678template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007679LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007680dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007681 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 InitialCapacity> &Map) {
7683 if (Map.begin() == Map.end())
7684 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007685
Vedant Kumar48b4f762018-04-14 01:40:48 +00007686 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7687
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007689 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7690 I != IEnd; ++I) {
7691 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7692 << "\n";
7693 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007694}
7695
Yaron Kerencdae9412016-01-29 19:38:18 +00007696LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007697 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7698 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7699 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7700 dumpModuleIDMap("Global type map", GlobalTypeMap);
7701 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7702 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7703 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7704 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7705 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007706 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007708
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007710 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007711 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007712}
7713
7714/// Return the amount of memory used by memory buffers, breaking down
7715/// by heap-backed versus mmap'ed memory.
7716void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007717 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007718 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 size_t bytes = buf->getBufferSize();
7720 switch (buf->getBufferKind()) {
7721 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7722 sizes.malloc_bytes += bytes;
7723 break;
7724 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7725 sizes.mmap_bytes += bytes;
7726 break;
7727 }
7728 }
7729 }
7730}
7731
7732void ASTReader::InitializeSema(Sema &S) {
7733 SemaObj = &S;
7734 S.addExternalSource(this);
7735
7736 // Makes sure any declarations that were deserialized "too early"
7737 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007738 for (uint64_t ID : PreloadedDeclIDs) {
7739 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007740 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007742 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007743
Richard Smith3d8e97e2013-10-18 06:54:39 +00007744 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 if (!FPPragmaOptions.empty()) {
7746 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007747 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 }
7749
Yaxun Liu5b746652016-12-18 05:18:55 +00007750 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7751 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7752 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007753
7754 UpdateSema();
7755}
7756
7757void ASTReader::UpdateSema() {
7758 assert(SemaObj && "no Sema to update");
7759
7760 // Load the offsets of the declarations that Sema references.
7761 // They will be lazily deserialized when needed.
7762 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007763 assert(SemaDeclRefs.size() % 3 == 0);
7764 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007765 if (!SemaObj->StdNamespace)
7766 SemaObj->StdNamespace = SemaDeclRefs[I];
7767 if (!SemaObj->StdBadAlloc)
7768 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007769 if (!SemaObj->StdAlignValT)
7770 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007771 }
7772 SemaDeclRefs.clear();
7773 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007774
Nico Weber779355f2016-03-02 23:22:00 +00007775 // Update the state of pragmas. Use the same API as if we had encountered the
7776 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007777 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007778 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007779 if (PragmaMSStructState != -1)
7780 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007781 if (PointersToMembersPragmaLocation.isValid()) {
7782 SemaObj->ActOnPragmaMSPointersToMembers(
7783 (LangOptions::PragmaMSPointersToMembersKind)
7784 PragmaMSPointersToMembersState,
7785 PointersToMembersPragmaLocation);
7786 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007787 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007788
7789 if (PragmaPackCurrentValue) {
7790 // The bottom of the stack might have a default value. It must be adjusted
7791 // to the current value to ensure that the packing state is preserved after
7792 // popping entries that were included/imported from a PCH/module.
7793 bool DropFirst = false;
7794 if (!PragmaPackStack.empty() &&
7795 PragmaPackStack.front().Location.isInvalid()) {
7796 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7797 "Expected a default alignment value");
7798 SemaObj->PackStack.Stack.emplace_back(
7799 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007800 SemaObj->PackStack.CurrentPragmaLocation,
7801 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007802 DropFirst = true;
7803 }
7804 for (const auto &Entry :
7805 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7806 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007807 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007808 if (PragmaPackCurrentLocation.isInvalid()) {
7809 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7810 "Expected a default alignment value");
7811 // Keep the current values.
7812 } else {
7813 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7814 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7815 }
7816 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007817}
7818
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007819IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 // Note that we are loading an identifier.
7821 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007822
Douglas Gregor7211ac12013-01-25 23:32:03 +00007823 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007824 NumIdentifierLookups,
7825 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007826
7827 // We don't need to do identifier table lookups in C++ modules (we preload
7828 // all interesting declarations, and don't need to use the scope for name
7829 // lookups). Perform the lookup in PCH files, though, since we don't build
7830 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007831 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007832 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007833 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007834 break;
7835 } else {
7836 // If there is a global index, look there first to determine which modules
7837 // provably do not have any results for this identifier.
7838 GlobalModuleIndex::HitSet Hits;
7839 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7840 if (!loadGlobalIndex()) {
7841 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7842 HitsPtr = &Hits;
7843 }
7844 }
7845
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007846 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007847 }
7848
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 IdentifierInfo *II = Visitor.getIdentifierInfo();
7850 markIdentifierUpToDate(II);
7851 return II;
7852}
7853
7854namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007855
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007856 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 /// identifiers stored within a set of AST files.
7858 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007859 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 const ASTReader &Reader;
7861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007862 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007863 /// the AST reader.
7864 unsigned Index;
7865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007866 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 /// of the current AST file.
7868 ASTIdentifierLookupTable::key_iterator Current;
7869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007870 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 /// the current AST file.
7872 ASTIdentifierLookupTable::key_iterator End;
7873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007874 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007875 bool SkipModules;
7876
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007878 explicit ASTIdentifierIterator(const ASTReader &Reader,
7879 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007880
Craig Topper3e89dfe2014-03-13 02:13:41 +00007881 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007883
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007884} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007885
Ben Langmuir537c5b52016-05-04 00:53:13 +00007886ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7887 bool SkipModules)
7888 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007889}
7890
7891StringRef ASTIdentifierIterator::Next() {
7892 while (Current == End) {
7893 // If we have exhausted all of our AST files, we're done.
7894 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007895 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007896
7897 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007898 ModuleFile &F = Reader.ModuleMgr[Index];
7899 if (SkipModules && F.isModule())
7900 continue;
7901
Vedant Kumar48b4f762018-04-14 01:40:48 +00007902 ASTIdentifierLookupTable *IdTable =
7903 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 Current = IdTable->key_begin();
7905 End = IdTable->key_end();
7906 }
7907
7908 // We have any identifiers remaining in the current AST file; return
7909 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007910 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007911 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007912 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007913}
7914
Ben Langmuir537c5b52016-05-04 00:53:13 +00007915namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007916
Ben Langmuir537c5b52016-05-04 00:53:13 +00007917/// A utility for appending two IdentifierIterators.
7918class ChainedIdentifierIterator : public IdentifierIterator {
7919 std::unique_ptr<IdentifierIterator> Current;
7920 std::unique_ptr<IdentifierIterator> Queued;
7921
7922public:
7923 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7924 std::unique_ptr<IdentifierIterator> Second)
7925 : Current(std::move(First)), Queued(std::move(Second)) {}
7926
7927 StringRef Next() override {
7928 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007929 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007930
7931 StringRef result = Current->Next();
7932 if (!result.empty())
7933 return result;
7934
7935 // Try the queued iterator, which may itself be empty.
7936 Current.reset();
7937 std::swap(Current, Queued);
7938 return Next();
7939 }
7940};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007941
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007942} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007943
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007944IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007945 if (!loadGlobalIndex()) {
7946 std::unique_ptr<IdentifierIterator> ReaderIter(
7947 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7948 std::unique_ptr<IdentifierIterator> ModulesIter(
7949 GlobalIndex->createIdentifierIterator());
7950 return new ChainedIdentifierIterator(std::move(ReaderIter),
7951 std::move(ModulesIter));
7952 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007953
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 return new ASTIdentifierIterator(*this);
7955}
7956
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007957namespace clang {
7958namespace serialization {
7959
Guy Benyei11169dd2012-12-18 14:30:41 +00007960 class ReadMethodPoolVisitor {
7961 ASTReader &Reader;
7962 Selector Sel;
7963 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007964 unsigned InstanceBits = 0;
7965 unsigned FactoryBits = 0;
7966 bool InstanceHasMoreThanOneDecl = false;
7967 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007968 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7969 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007970
7971 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007972 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007973 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007974 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007975
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007976 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 if (!M.SelectorLookupTable)
7978 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007979
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007981 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 return true;
7983
Richard Smithbdf2d932015-07-30 03:37:16 +00007984 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007985 ASTSelectorLookupTable *PoolTable
7986 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007987 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 if (Pos == PoolTable->end())
7989 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007990
Richard Smithbdf2d932015-07-30 03:37:16 +00007991 ++Reader.NumMethodPoolTableHits;
7992 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 // FIXME: Not quite happy with the statistics here. We probably should
7994 // disable this tracking when called via LoadSelector.
7995 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007996 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007998 if (Reader.DeserializationListener)
7999 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008000
Richard Smithbdf2d932015-07-30 03:37:16 +00008001 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8002 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8003 InstanceBits = Data.InstanceBits;
8004 FactoryBits = Data.FactoryBits;
8005 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8006 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 return true;
8008 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008009
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008010 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008011 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8012 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 }
8014
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008015 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008016 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 return FactoryMethods;
8018 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008019
8020 unsigned getInstanceBits() const { return InstanceBits; }
8021 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008022
Nico Weberff4b35e2014-12-27 22:14:15 +00008023 bool instanceHasMoreThanOneDecl() const {
8024 return InstanceHasMoreThanOneDecl;
8025 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008026
Nico Weberff4b35e2014-12-27 22:14:15 +00008027 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008029
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008030} // namespace serialization
8031} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008033/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008034static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8035 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008036 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8037 S.addMethodToGlobalList(&List, Methods[I]);
8038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008039}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008040
Guy Benyei11169dd2012-12-18 14:30:41 +00008041void ASTReader::ReadMethodPool(Selector Sel) {
8042 // Get the selector generation and update it to the current generation.
8043 unsigned &Generation = SelectorGeneration[Sel];
8044 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008045 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008046 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008047
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008049 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008051 ModuleMgr.visit(Visitor);
8052
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008054 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008056
8057 ++NumMethodPoolHits;
8058
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 if (!getSema())
8060 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008061
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 Sema &S = *getSema();
8063 Sema::GlobalMethodPool::iterator Pos
8064 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008065
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008066 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008067 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008068 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008069 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008070
8071 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8072 // when building a module we keep every method individually and may need to
8073 // update hasMoreThanOneDecl as we add the methods.
8074 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8075 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008076}
8077
Manman Rena0f31a02016-04-29 19:04:05 +00008078void ASTReader::updateOutOfDateSelector(Selector Sel) {
8079 if (SelectorOutOfDate[Sel])
8080 ReadMethodPool(Sel);
8081}
8082
Guy Benyei11169dd2012-12-18 14:30:41 +00008083void ASTReader::ReadKnownNamespaces(
8084 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8085 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008086
Vedant Kumar48b4f762018-04-14 01:40:48 +00008087 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8088 if (NamespaceDecl *Namespace
8089 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008092}
8093
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008094void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008095 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008096 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008097 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008098 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008099 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008100 Undefined.insert(std::make_pair(D, Loc));
8101 }
8102}
Nick Lewycky8334af82013-01-26 00:35:08 +00008103
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008104void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8105 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8106 Exprs) {
8107 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008108 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008109 uint64_t Count = DelayedDeleteExprs[Idx++];
8110 for (uint64_t C = 0; C < Count; ++C) {
8111 SourceLocation DeleteLoc =
8112 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8113 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8114 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8115 }
8116 }
8117}
8118
Guy Benyei11169dd2012-12-18 14:30:41 +00008119void ASTReader::ReadTentativeDefinitions(
8120 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008121 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8122 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 if (Var)
8124 TentativeDefs.push_back(Var);
8125 }
8126 TentativeDefinitions.clear();
8127}
8128
8129void ASTReader::ReadUnusedFileScopedDecls(
8130 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008131 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8132 DeclaratorDecl *D
8133 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 if (D)
8135 Decls.push_back(D);
8136 }
8137 UnusedFileScopedDecls.clear();
8138}
8139
8140void ASTReader::ReadDelegatingConstructors(
8141 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008142 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8143 CXXConstructorDecl *D
8144 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 if (D)
8146 Decls.push_back(D);
8147 }
8148 DelegatingCtorDecls.clear();
8149}
8150
8151void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008152 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8153 TypedefNameDecl *D
8154 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 if (D)
8156 Decls.push_back(D);
8157 }
8158 ExtVectorDecls.clear();
8159}
8160
Nico Weber72889432014-09-06 01:25:55 +00008161void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8162 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008163 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8164 ++I) {
8165 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8166 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008167 if (D)
8168 Decls.insert(D);
8169 }
8170 UnusedLocalTypedefNameCandidates.clear();
8171}
8172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008174 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 if (ReferencedSelectorsData.empty())
8176 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008177
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 // If there are @selector references added them to its pool. This is for
8179 // implementation of -Wselector.
8180 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8181 unsigned I = 0;
8182 while (I < DataSize) {
8183 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8184 SourceLocation SelLoc
8185 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8186 Sels.push_back(std::make_pair(Sel, SelLoc));
8187 }
8188 ReferencedSelectorsData.clear();
8189}
8190
8191void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008192 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008193 if (WeakUndeclaredIdentifiers.empty())
8194 return;
8195
8196 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008197 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008199 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8201 SourceLocation Loc
8202 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8203 bool Used = WeakUndeclaredIdentifiers[I++];
8204 WeakInfo WI(AliasId, Loc);
8205 WI.setUsed(Used);
8206 WeakIDs.push_back(std::make_pair(WeakId, WI));
8207 }
8208 WeakUndeclaredIdentifiers.clear();
8209}
8210
8211void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8212 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8213 ExternalVTableUse VT;
8214 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8215 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8216 VT.DefinitionRequired = VTableUses[Idx++];
8217 VTables.push_back(VT);
8218 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008219
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 VTableUses.clear();
8221}
8222
8223void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008224 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008226 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 SourceLocation Loc
8228 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8229
8230 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 PendingInstantiations.clear();
8233}
8234
Richard Smithe40f2ba2013-08-07 21:41:30 +00008235void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008236 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8237 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008238 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8239 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008240 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008241
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008242 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008243 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8244
8245 ModuleFile *F = getOwningModuleFile(LT->D);
8246 assert(F && "No module");
8247
8248 unsigned TokN = LateParsedTemplates[Idx++];
8249 LT->Toks.reserve(TokN);
8250 for (unsigned T = 0; T < TokN; ++T)
8251 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8252
Justin Lebar28f09c52016-10-10 16:26:08 +00008253 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008254 }
8255
8256 LateParsedTemplates.clear();
8257}
8258
Guy Benyei11169dd2012-12-18 14:30:41 +00008259void ASTReader::LoadSelector(Selector Sel) {
8260 // It would be complicated to avoid reading the methods anyway. So don't.
8261 ReadMethodPool(Sel);
8262}
8263
8264void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8265 assert(ID && "Non-zero identifier ID required");
8266 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8267 IdentifiersLoaded[ID - 1] = II;
8268 if (DeserializationListener)
8269 DeserializationListener->IdentifierRead(ID, II);
8270}
8271
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008272/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008273/// identifier.
8274///
8275/// If the AST reader is currently in a state where the given declaration IDs
8276/// cannot safely be resolved, they are queued until it is safe to resolve
8277/// them.
8278///
8279/// \param II an IdentifierInfo that refers to one or more globally-visible
8280/// declarations.
8281///
8282/// \param DeclIDs the set of declaration IDs with the name @p II that are
8283/// visible at global scope.
8284///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008285/// \param Decls if non-null, this vector will be populated with the set of
8286/// deserialized declarations. These declarations will not be pushed into
8287/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008288void
8289ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8290 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008291 SmallVectorImpl<Decl *> *Decls) {
8292 if (NumCurrentElementsDeserializing && !Decls) {
8293 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 return;
8295 }
8296
Vedant Kumar48b4f762018-04-14 01:40:48 +00008297 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008298 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 // Queue this declaration so that it will be added to the
8300 // translation unit scope and identifier's declaration chain
8301 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008302 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008303 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008305
Vedant Kumar48b4f762018-04-14 01:40:48 +00008306 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008307
8308 // If we're simply supposed to record the declarations, do so now.
8309 if (Decls) {
8310 Decls->push_back(D);
8311 continue;
8312 }
8313
8314 // Introduce this declaration into the translation-unit scope
8315 // and add it to the declaration chain for this identifier, so
8316 // that (unqualified) name lookup will find it.
8317 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008318 }
8319}
8320
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008321IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008323 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008324
8325 if (IdentifiersLoaded.empty()) {
8326 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008327 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008328 }
8329
8330 ID -= 1;
8331 if (!IdentifiersLoaded[ID]) {
8332 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8333 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8334 ModuleFile *M = I->second;
8335 unsigned Index = ID - M->BaseIdentifierID;
8336 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8337
8338 // All of the strings in the AST file are preceded by a 16-bit length.
8339 // Extract that 16-bit length to avoid having to execute strlen().
8340 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8341 // unsigned integers. This is important to avoid integer overflow when
8342 // we cast them to 'unsigned'.
8343 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8344 unsigned StrLen = (((unsigned) StrLenPtr[0])
8345 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008346 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8347 IdentifiersLoaded[ID] = &II;
8348 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008350 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008351 }
8352
8353 return IdentifiersLoaded[ID];
8354}
8355
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008356IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8357 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008358}
8359
8360IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8361 if (LocalID < NUM_PREDEF_IDENT_IDS)
8362 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008363
Richard Smith37a93df2017-02-18 00:32:02 +00008364 if (!M.ModuleOffsetMap.empty())
8365 ReadModuleOffsetMap(M);
8366
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8368 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008369 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008371
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 return LocalID + I->second;
8373}
8374
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008375MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008377 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008378
8379 if (MacrosLoaded.empty()) {
8380 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008381 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 }
8383
8384 ID -= NUM_PREDEF_MACRO_IDS;
8385 if (!MacrosLoaded[ID]) {
8386 GlobalMacroMapType::iterator I
8387 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8388 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8389 ModuleFile *M = I->second;
8390 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008391 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008392
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008393 if (DeserializationListener)
8394 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8395 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008396 }
8397
8398 return MacrosLoaded[ID];
8399}
8400
8401MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8402 if (LocalID < NUM_PREDEF_MACRO_IDS)
8403 return LocalID;
8404
Richard Smith37a93df2017-02-18 00:32:02 +00008405 if (!M.ModuleOffsetMap.empty())
8406 ReadModuleOffsetMap(M);
8407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8409 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8410 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8411
8412 return LocalID + I->second;
8413}
8414
8415serialization::SubmoduleID
8416ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8417 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8418 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008419
Richard Smith37a93df2017-02-18 00:32:02 +00008420 if (!M.ModuleOffsetMap.empty())
8421 ReadModuleOffsetMap(M);
8422
Guy Benyei11169dd2012-12-18 14:30:41 +00008423 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8424 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008425 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008426 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008427
Guy Benyei11169dd2012-12-18 14:30:41 +00008428 return LocalID + I->second;
8429}
8430
8431Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8432 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8433 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008434 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008435 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008436
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 if (GlobalID > SubmodulesLoaded.size()) {
8438 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008439 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008441
Guy Benyei11169dd2012-12-18 14:30:41 +00008442 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8443}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008444
8445Module *ASTReader::getModule(unsigned ID) {
8446 return getSubmodule(ID);
8447}
8448
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008449bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8450 ModuleFile *MF = getOwningModuleFile(D);
8451 return MF && MF->PCHHasObjectFile;
8452}
8453
Richard Smithd88a7f12015-09-01 20:35:42 +00008454ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8455 if (ID & 1) {
8456 // It's a module, look it up by submodule ID.
8457 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8458 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8459 } else {
8460 // It's a prefix (preamble, PCH, ...). Look it up by index.
8461 unsigned IndexFromEnd = ID >> 1;
8462 assert(IndexFromEnd && "got reference to unknown module file");
8463 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8464 }
8465}
8466
8467unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8468 if (!F)
8469 return 1;
8470
8471 // For a file representing a module, use the submodule ID of the top-level
8472 // module as the file ID. For any other kind of file, the number of such
8473 // files loaded beforehand will be the same on reload.
8474 // FIXME: Is this true even if we have an explicit module file and a PCH?
8475 if (F->isModule())
8476 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8477
8478 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008479 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008480 assert(I != PCHModules.end() && "emitting reference to unknown file");
8481 return (I - PCHModules.end()) << 1;
8482}
8483
Adrian Prantl15bcf702015-06-30 17:39:43 +00008484llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8485ASTReader::getSourceDescriptor(unsigned ID) {
8486 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008487 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008488
8489 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008490 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008491 const auto &PCHChain = ModuleMgr.pch_modules();
8492 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008493 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008494 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008495 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8496 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8497 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008498 }
8499 return None;
8500}
8501
David Blaikie1ac9c982017-04-11 21:13:37 +00008502ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008503 auto I = DefinitionSource.find(FD);
8504 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008505 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008506 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008507}
8508
Guy Benyei11169dd2012-12-18 14:30:41 +00008509Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8510 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8511}
8512
8513Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8514 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008515 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008516
8517 if (ID > SelectorsLoaded.size()) {
8518 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008519 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008520 }
8521
Craig Toppera13603a2014-05-22 05:54:18 +00008522 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008523 // Load this selector from the selector table.
8524 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8525 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8526 ModuleFile &M = *I->second;
8527 ASTSelectorLookupTrait Trait(*this, M);
8528 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8529 SelectorsLoaded[ID - 1] =
8530 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8531 if (DeserializationListener)
8532 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8533 }
8534
8535 return SelectorsLoaded[ID - 1];
8536}
8537
8538Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8539 return DecodeSelector(ID);
8540}
8541
8542uint32_t ASTReader::GetNumExternalSelectors() {
8543 // ID 0 (the null selector) is considered an external selector.
8544 return getTotalNumSelectors() + 1;
8545}
8546
8547serialization::SelectorID
8548ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8549 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8550 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008551
Richard Smith37a93df2017-02-18 00:32:02 +00008552 if (!M.ModuleOffsetMap.empty())
8553 ReadModuleOffsetMap(M);
8554
Guy Benyei11169dd2012-12-18 14:30:41 +00008555 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8556 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008557 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008559
Guy Benyei11169dd2012-12-18 14:30:41 +00008560 return LocalID + I->second;
8561}
8562
John McCall3ce3d232019-12-13 03:37:23 -05008563DeclarationNameLoc
8564ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8565 DeclarationNameLoc DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008566 switch (Name.getNameKind()) {
8567 case DeclarationName::CXXConstructorName:
8568 case DeclarationName::CXXDestructorName:
8569 case DeclarationName::CXXConversionFunctionName:
John McCall3ce3d232019-12-13 03:37:23 -05008570 DNLoc.NamedType.TInfo = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 break;
8572
8573 case DeclarationName::CXXOperatorName:
8574 DNLoc.CXXOperatorName.BeginOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008575 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008576 DNLoc.CXXOperatorName.EndOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008577 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 break;
8579
8580 case DeclarationName::CXXLiteralOperatorName:
8581 DNLoc.CXXLiteralOperatorName.OpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008582 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 break;
8584
8585 case DeclarationName::Identifier:
8586 case DeclarationName::ObjCZeroArgSelector:
8587 case DeclarationName::ObjCOneArgSelector:
8588 case DeclarationName::ObjCMultiArgSelector:
8589 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008590 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 break;
8592 }
John McCall3ce3d232019-12-13 03:37:23 -05008593 return DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008594}
8595
John McCall3ce3d232019-12-13 03:37:23 -05008596DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8597 DeclarationNameInfo NameInfo;
8598 NameInfo.setName(readDeclarationName());
8599 NameInfo.setLoc(readSourceLocation());
8600 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8601 return NameInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +00008602}
8603
John McCall3ce3d232019-12-13 03:37:23 -05008604void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8605 Info.QualifierLoc = readNestedNameSpecifierLoc();
8606 unsigned NumTPLists = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 Info.NumTemplParamLists = NumTPLists;
8608 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008609 Info.TemplParamLists =
8610 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008611 for (unsigned i = 0; i != NumTPLists; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05008612 Info.TemplParamLists[i] = readTemplateParameterList();
Guy Benyei11169dd2012-12-18 14:30:41 +00008613 }
8614}
8615
Guy Benyei11169dd2012-12-18 14:30:41 +00008616TemplateParameterList *
John McCall3ce3d232019-12-13 03:37:23 -05008617ASTRecordReader::readTemplateParameterList() {
8618 SourceLocation TemplateLoc = readSourceLocation();
8619 SourceLocation LAngleLoc = readSourceLocation();
8620 SourceLocation RAngleLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008621
John McCall3ce3d232019-12-13 03:37:23 -05008622 unsigned NumParams = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 SmallVector<NamedDecl *, 16> Params;
8624 Params.reserve(NumParams);
8625 while (NumParams--)
John McCall3ce3d232019-12-13 03:37:23 -05008626 Params.push_back(readDeclAs<NamedDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00008627
John McCall3ce3d232019-12-13 03:37:23 -05008628 bool HasRequiresClause = readBool();
8629 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
Saar Raz0330fba2019-10-15 18:44:06 +00008630
Richard Smithdbafb6c2017-06-29 23:23:46 +00008631 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00008632 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00008633 return TemplateParams;
8634}
8635
John McCall3ce3d232019-12-13 03:37:23 -05008636void ASTRecordReader::readTemplateArgumentList(
8637 SmallVectorImpl<TemplateArgument> &TemplArgs,
8638 bool Canonicalize) {
8639 unsigned NumTemplateArgs = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008640 TemplArgs.reserve(NumTemplateArgs);
8641 while (NumTemplateArgs--)
John McCall3ce3d232019-12-13 03:37:23 -05008642 TemplArgs.push_back(readTemplateArgument(Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008643}
8644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008645/// Read a UnresolvedSet structure.
John McCall3ce3d232019-12-13 03:37:23 -05008646void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8647 unsigned NumDecls = readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008648 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 while (NumDecls--) {
John McCall3ce3d232019-12-13 03:37:23 -05008650 DeclID ID = readDeclID();
8651 AccessSpecifier AS = (AccessSpecifier) readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008652 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008653 }
8654}
8655
8656CXXBaseSpecifier
John McCall3ce3d232019-12-13 03:37:23 -05008657ASTRecordReader::readCXXBaseSpecifier() {
8658 bool isVirtual = readBool();
8659 bool isBaseOfClass = readBool();
8660 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8661 bool inheritConstructors = readBool();
8662 TypeSourceInfo *TInfo = readTypeSourceInfo();
8663 SourceRange Range = readSourceRange();
8664 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008665 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008666 EllipsisLoc);
8667 Result.setInheritConstructors(inheritConstructors);
8668 return Result;
8669}
8670
Richard Smithc2bb8182015-03-24 06:36:48 +00008671CXXCtorInitializer **
John McCall3ce3d232019-12-13 03:37:23 -05008672ASTRecordReader::readCXXCtorInitializers() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008673 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008674 unsigned NumInitializers = readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008675 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008676 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008677 for (unsigned i = 0; i != NumInitializers; ++i) {
8678 TypeSourceInfo *TInfo = nullptr;
8679 bool IsBaseVirtual = false;
8680 FieldDecl *Member = nullptr;
8681 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008682
John McCall3ce3d232019-12-13 03:37:23 -05008683 CtorInitializerType Type = (CtorInitializerType) readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008684 switch (Type) {
8685 case CTOR_INITIALIZER_BASE:
John McCall3ce3d232019-12-13 03:37:23 -05008686 TInfo = readTypeSourceInfo();
8687 IsBaseVirtual = readBool();
Richard Smithc2bb8182015-03-24 06:36:48 +00008688 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008689
Richard Smithc2bb8182015-03-24 06:36:48 +00008690 case CTOR_INITIALIZER_DELEGATING:
John McCall3ce3d232019-12-13 03:37:23 -05008691 TInfo = readTypeSourceInfo();
Richard Smithc2bb8182015-03-24 06:36:48 +00008692 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008693
Richard Smithc2bb8182015-03-24 06:36:48 +00008694 case CTOR_INITIALIZER_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008695 Member = readDeclAs<FieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008696 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008697
Richard Smithc2bb8182015-03-24 06:36:48 +00008698 case CTOR_INITIALIZER_INDIRECT_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008699 IndirectMember = readDeclAs<IndirectFieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008700 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008701 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008702
John McCall3ce3d232019-12-13 03:37:23 -05008703 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8704 Expr *Init = readExpr();
8705 SourceLocation LParenLoc = readSourceLocation();
8706 SourceLocation RParenLoc = readSourceLocation();
Richard Smithc2bb8182015-03-24 06:36:48 +00008707
8708 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008709 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008710 BOMInit = new (Context)
8711 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8712 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008713 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008714 BOMInit = new (Context)
8715 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008716 else if (Member)
8717 BOMInit = new (Context)
8718 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8719 Init, RParenLoc);
8720 else
8721 BOMInit = new (Context)
8722 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8723 LParenLoc, Init, RParenLoc);
8724
John McCall3ce3d232019-12-13 03:37:23 -05008725 if (/*IsWritten*/readBool()) {
8726 unsigned SourceOrder = readInt();
Richard Smith30e304e2016-12-14 00:03:17 +00008727 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008728 }
8729
Richard Smithc2bb8182015-03-24 06:36:48 +00008730 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 }
8732
Richard Smithc2bb8182015-03-24 06:36:48 +00008733 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008734}
8735
Guy Benyei11169dd2012-12-18 14:30:41 +00008736NestedNameSpecifierLoc
John McCall3ce3d232019-12-13 03:37:23 -05008737ASTRecordReader::readNestedNameSpecifierLoc() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008738 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008739 unsigned N = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 NestedNameSpecifierLocBuilder Builder;
8741 for (unsigned I = 0; I != N; ++I) {
John McCalld505e572019-12-13 21:54:44 -05008742 auto Kind = readNestedNameSpecifierKind();
Guy Benyei11169dd2012-12-18 14:30:41 +00008743 switch (Kind) {
8744 case NestedNameSpecifier::Identifier: {
John McCall3ce3d232019-12-13 03:37:23 -05008745 IdentifierInfo *II = readIdentifier();
8746 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008747 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8748 break;
8749 }
8750
8751 case NestedNameSpecifier::Namespace: {
John McCall3ce3d232019-12-13 03:37:23 -05008752 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8753 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008754 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8755 break;
8756 }
8757
8758 case NestedNameSpecifier::NamespaceAlias: {
John McCall3ce3d232019-12-13 03:37:23 -05008759 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8760 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008761 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8762 break;
8763 }
8764
8765 case NestedNameSpecifier::TypeSpec:
8766 case NestedNameSpecifier::TypeSpecWithTemplate: {
John McCall3ce3d232019-12-13 03:37:23 -05008767 bool Template = readBool();
8768 TypeSourceInfo *T = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008769 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008770 return NestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -05008771 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008772
8773 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008774 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008775 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8776 T->getTypeLoc(), ColonColonLoc);
8777 break;
8778 }
8779
8780 case NestedNameSpecifier::Global: {
John McCall3ce3d232019-12-13 03:37:23 -05008781 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008782 Builder.MakeGlobal(Context, ColonColonLoc);
8783 break;
8784 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008785
8786 case NestedNameSpecifier::Super: {
John McCall3ce3d232019-12-13 03:37:23 -05008787 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8788 SourceRange Range = readSourceRange();
Nikola Smiljanic67860242014-09-26 00:28:20 +00008789 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8790 break;
8791 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008792 }
8793 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008794
Guy Benyei11169dd2012-12-18 14:30:41 +00008795 return Builder.getWithLocInContext(Context);
8796}
8797
8798SourceRange
8799ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8800 unsigned &Idx) {
8801 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8802 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8803 return SourceRange(beg, end);
8804}
8805
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008806static FixedPointSemantics
8807ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8808 unsigned &Idx) {
8809 unsigned Width = Record[Idx++];
8810 unsigned Scale = Record[Idx++];
8811 uint64_t Tmp = Record[Idx++];
8812 bool IsSigned = Tmp & 0x1;
8813 bool IsSaturated = Tmp & 0x2;
8814 bool HasUnsignedPadding = Tmp & 0x4;
8815 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8816 HasUnsignedPadding);
8817}
8818
John McCall3ce3d232019-12-13 03:37:23 -05008819static const llvm::fltSemantics &
8820readAPFloatSemantics(ASTRecordReader &reader) {
8821 return llvm::APFloatBase::EnumToSemantics(
8822 static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8823}
8824
8825APValue ASTRecordReader::readAPValue() {
8826 unsigned Kind = readInt();
John McCalld505e572019-12-13 21:54:44 -05008827 switch ((APValue::ValueKind) Kind) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008828 case APValue::None:
8829 return APValue();
8830 case APValue::Indeterminate:
8831 return APValue::IndeterminateValue();
8832 case APValue::Int:
John McCall3ce3d232019-12-13 03:37:23 -05008833 return APValue(readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008834 case APValue::Float: {
John McCall3ce3d232019-12-13 03:37:23 -05008835 const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8836 return APValue(readAPFloat(FloatSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008837 }
8838 case APValue::FixedPoint: {
8839 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
John McCall3ce3d232019-12-13 03:37:23 -05008840 return APValue(APFixedPoint(readAPInt(), FPSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008841 }
8842 case APValue::ComplexInt: {
John McCall3ce3d232019-12-13 03:37:23 -05008843 llvm::APSInt First = readAPSInt();
8844 return APValue(std::move(First), readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008845 }
8846 case APValue::ComplexFloat: {
John McCall3ce3d232019-12-13 03:37:23 -05008847 const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8848 llvm::APFloat First = readAPFloat(FloatSema1);
8849 const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8850 return APValue(std::move(First), readAPFloat(FloatSema2));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008851 }
8852 case APValue::LValue:
8853 case APValue::Vector:
8854 case APValue::Array:
8855 case APValue::Struct:
8856 case APValue::Union:
8857 case APValue::MemberPointer:
8858 case APValue::AddrLabelDiff:
8859 // TODO : Handle all these APValue::ValueKind.
8860 return APValue();
8861 }
8862 llvm_unreachable("Invalid APValue::ValueKind");
8863}
8864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008865/// Read a floating-point value
John McCall3ce3d232019-12-13 03:37:23 -05008866llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8867 return llvm::APFloat(Sem, readAPInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00008868}
8869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008870// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008871std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8872 unsigned Len = Record[Idx++];
8873 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8874 Idx += Len;
8875 return Result;
8876}
8877
Richard Smith7ed1bc92014-12-05 22:42:13 +00008878std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8879 unsigned &Idx) {
8880 std::string Filename = ReadString(Record, Idx);
8881 ResolveImportedPath(F, Filename);
8882 return Filename;
8883}
8884
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00008885std::string ASTReader::ReadPath(StringRef BaseDirectory,
8886 const RecordData &Record, unsigned &Idx) {
8887 std::string Filename = ReadString(Record, Idx);
8888 if (!BaseDirectory.empty())
8889 ResolveImportedPath(Filename, BaseDirectory);
8890 return Filename;
8891}
8892
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008893VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 unsigned &Idx) {
8895 unsigned Major = Record[Idx++];
8896 unsigned Minor = Record[Idx++];
8897 unsigned Subminor = Record[Idx++];
8898 if (Minor == 0)
8899 return VersionTuple(Major);
8900 if (Subminor == 0)
8901 return VersionTuple(Major, Minor - 1);
8902 return VersionTuple(Major, Minor - 1, Subminor - 1);
8903}
8904
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008905CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008906 const RecordData &Record,
8907 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008908 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008909 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008910}
8911
Richard Smith37a93df2017-02-18 00:32:02 +00008912DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008913 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008914}
8915
Richard Smith37a93df2017-02-18 00:32:02 +00008916DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008917 return Diags.Report(Loc, DiagID);
8918}
8919
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008920/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00008921/// preprocessor.
8922IdentifierTable &ASTReader::getIdentifierTable() {
8923 return PP.getIdentifierTable();
8924}
8925
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008926/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00008927/// statement.
8928void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008929 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008930 "Already have a SwitchCase with this ID");
8931 (*CurrSwitchCaseStmts)[ID] = SC;
8932}
8933
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008934/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00008935SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008936 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008937 return (*CurrSwitchCaseStmts)[ID];
8938}
8939
8940void ASTReader::ClearSwitchCaseIDs() {
8941 CurrSwitchCaseStmts->clear();
8942}
8943
8944void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008945 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008946 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008947 for (SmallVectorImpl<std::pair<BitstreamCursor,
8948 serialization::ModuleFile *>>::iterator
8949 I = CommentsCursors.begin(),
8950 E = CommentsCursors.end();
8951 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008952 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008953 BitstreamCursor &Cursor = I->first;
8954 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00008955 SavedStreamPosition SavedPosition(Cursor);
8956
8957 RecordData Record;
8958 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00008959 Expected<llvm::BitstreamEntry> MaybeEntry =
8960 Cursor.advanceSkippingSubblocks(
8961 BitstreamCursor::AF_DontPopBlockAtEnd);
8962 if (!MaybeEntry) {
8963 Error(MaybeEntry.takeError());
8964 return;
8965 }
8966 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008967
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008968 switch (Entry.Kind) {
8969 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8970 case llvm::BitstreamEntry::Error:
8971 Error("malformed block record in AST file");
8972 return;
8973 case llvm::BitstreamEntry::EndBlock:
8974 goto NextCursor;
8975 case llvm::BitstreamEntry::Record:
8976 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008977 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008978 }
8979
8980 // Read a record.
8981 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00008982 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
8983 if (!MaybeComment) {
8984 Error(MaybeComment.takeError());
8985 return;
8986 }
8987 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 case COMMENTS_RAW_COMMENT: {
8989 unsigned Idx = 0;
8990 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008991 RawComment::CommentKind Kind =
8992 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008993 bool IsTrailingComment = Record[Idx++];
8994 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008995 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00008996 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00008997 break;
8998 }
8999 }
9000 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009001 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009002 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9003 FileToOffsetToComment;
9004 for (RawComment *C : Comments) {
9005 SourceLocation CommentLoc = C->getBeginLoc();
9006 if (CommentLoc.isValid()) {
9007 std::pair<FileID, unsigned> Loc =
9008 SourceMgr.getDecomposedLoc(CommentLoc);
9009 if (Loc.first.isValid())
9010 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9011 }
9012 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009013 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009014}
9015
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009016void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9017 bool IncludeSystem, bool Complain,
9018 llvm::function_ref<void(const serialization::InputFile &IF,
9019 bool isSystem)> Visitor) {
9020 unsigned NumUserInputs = MF.NumUserInputFiles;
9021 unsigned NumInputs = MF.InputFilesLoaded.size();
9022 assert(NumUserInputs <= NumInputs);
9023 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9024 for (unsigned I = 0; I < N; ++I) {
9025 bool IsSystem = I >= NumUserInputs;
9026 InputFile IF = getInputFile(MF, I+1, Complain);
9027 Visitor(IF, IsSystem);
9028 }
9029}
9030
Richard Smithf3f84612017-06-29 02:19:42 +00009031void ASTReader::visitTopLevelModuleMaps(
9032 serialization::ModuleFile &MF,
9033 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9034 unsigned NumInputs = MF.InputFilesLoaded.size();
9035 for (unsigned I = 0; I < NumInputs; ++I) {
9036 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9037 if (IFI.TopLevelModuleMap)
9038 // FIXME: This unnecessarily re-reads the InputFileInfo.
9039 if (auto *FE = getInputFile(MF, I + 1).getFile())
9040 Visitor(FE);
9041 }
9042}
9043
Richard Smithcd45dbc2014-04-19 03:48:30 +00009044std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9045 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009046 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009047 return M->getFullModuleName();
9048
9049 // Otherwise, use the name of the top-level module the decl is within.
9050 if (ModuleFile *M = getOwningModuleFile(D))
9051 return M->ModuleName;
9052
9053 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009054 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009055}
9056
Guy Benyei11169dd2012-12-18 14:30:41 +00009057void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009058 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009059 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009060 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009061 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009062 // If any identifiers with corresponding top-level declarations have
9063 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009064 using TopLevelDeclsMap =
9065 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009066 TopLevelDeclsMap TopLevelDecls;
9067
Guy Benyei11169dd2012-12-18 14:30:41 +00009068 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009069 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009070 SmallVector<uint32_t, 4> DeclIDs =
9071 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009072 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009073
9074 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009075 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009076
Richard Smitha62d1982018-08-03 01:00:01 +00009077 // Load each function type that we deferred loading because it was a
9078 // deduced type that might refer to a local type declared within itself.
9079 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9080 auto *FD = PendingFunctionTypes[I].first;
9081 FD->setType(GetType(PendingFunctionTypes[I].second));
9082
9083 // If we gave a function a deduced return type, remember that we need to
9084 // propagate that along the redeclaration chain.
9085 auto *DT = FD->getReturnType()->getContainedDeducedType();
9086 if (DT && DT->isDeduced())
9087 PendingDeducedTypeUpdates.insert(
9088 {FD->getCanonicalDecl(), FD->getReturnType()});
9089 }
9090 PendingFunctionTypes.clear();
9091
Richard Smith851072e2014-05-19 20:59:20 +00009092 // For each decl chain that we wanted to complete while deserializing, mark
9093 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009094 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9095 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9096 }
Richard Smith851072e2014-05-19 20:59:20 +00009097 PendingIncompleteDeclChains.clear();
9098
Guy Benyei11169dd2012-12-18 14:30:41 +00009099 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009100 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009101 loadPendingDeclChain(PendingDeclChains[I].first,
9102 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009103 PendingDeclChains.clear();
9104
Douglas Gregor6168bd22013-02-18 15:53:43 +00009105 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009106 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9107 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9108 IdentifierInfo *II = TLD->first;
9109 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9110 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009111 }
9112 }
9113
Guy Benyei11169dd2012-12-18 14:30:41 +00009114 // Load any pending macro definitions.
9115 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009116 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9117 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9118 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9119 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009120 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009121 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009122 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009123 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009124 resolvePendingMacro(II, Info);
9125 }
9126 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009127 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009128 ++IDIdx) {
9129 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009130 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009131 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009132 }
9133 }
9134 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009135
9136 // Wire up the DeclContexts for Decls that we delayed setting until
9137 // recursive loading is completed.
9138 while (!PendingDeclContextInfos.empty()) {
9139 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9140 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009141 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9142 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009143 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9144 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009145
Richard Smithd1c46742014-04-30 02:24:17 +00009146 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009147 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009148 auto Update = PendingUpdateRecords.pop_back_val();
9149 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009150 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009152 }
Richard Smith8a639892015-01-24 01:07:20 +00009153
9154 // At this point, all update records for loaded decls are in place, so any
9155 // fake class definitions should have become real.
9156 assert(PendingFakeDefinitionData.empty() &&
9157 "faked up a class definition but never saw the real one");
9158
Guy Benyei11169dd2012-12-18 14:30:41 +00009159 // If we deserialized any C++ or Objective-C class definitions, any
9160 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009161 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009162 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009163 for (Decl *D : PendingDefinitions) {
9164 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9165 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009166 // Make sure that the TagType points at the definition.
9167 const_cast<TagType*>(TagT)->decl = TD;
9168 }
Richard Smith8ce51082015-03-11 01:44:51 +00009169
Vedant Kumar48b4f762018-04-14 01:40:48 +00009170 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009171 for (auto *R = getMostRecentExistingDecl(RD); R;
9172 R = R->getPreviousDecl()) {
9173 assert((R == D) ==
9174 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009175 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009176 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009177 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009178 }
9179
9180 continue;
9181 }
Richard Smith8ce51082015-03-11 01:44:51 +00009182
Vedant Kumar48b4f762018-04-14 01:40:48 +00009183 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009184 // Make sure that the ObjCInterfaceType points at the definition.
9185 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9186 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009187
9188 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9189 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9190
Guy Benyei11169dd2012-12-18 14:30:41 +00009191 continue;
9192 }
Richard Smith8ce51082015-03-11 01:44:51 +00009193
Vedant Kumar48b4f762018-04-14 01:40:48 +00009194 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009195 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9196 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9197
Guy Benyei11169dd2012-12-18 14:30:41 +00009198 continue;
9199 }
Richard Smith8ce51082015-03-11 01:44:51 +00009200
Vedant Kumar48b4f762018-04-14 01:40:48 +00009201 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009202 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9203 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009204 }
9205 PendingDefinitions.clear();
9206
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009207 // Load the bodies of any functions or methods we've encountered. We do
9208 // this now (delayed) so that we can be sure that the declaration chains
9209 // have been fully wired up (hasBody relies on this).
9210 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009211 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9212 PBEnd = PendingBodies.end();
9213 PB != PBEnd; ++PB) {
9214 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009215 // For a function defined inline within a class template, force the
9216 // canonical definition to be the one inside the canonical definition of
9217 // the template. This ensures that we instantiate from a correct view
9218 // of the template.
9219 //
9220 // Sadly we can't do this more generally: we can't be sure that all
9221 // copies of an arbitrary class definition will have the same members
9222 // defined (eg, some member functions may not be instantiated, and some
9223 // special members may or may not have been implicitly defined).
9224 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9225 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9226 continue;
9227
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009228 // FIXME: Check for =delete/=default?
9229 // FIXME: Complain about ODR violations here?
9230 const FunctionDecl *Defn = nullptr;
9231 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009232 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009233 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009234 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009235 mergeDefinitionVisibility(NonConstDefn, FD);
9236
9237 if (!FD->isLateTemplateParsed() &&
9238 !NonConstDefn->isLateTemplateParsed() &&
9239 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009240 if (!isa<CXXMethodDecl>(FD)) {
9241 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9242 } else if (FD->getLexicalParent()->isFileContext() &&
9243 NonConstDefn->getLexicalParent()->isFileContext()) {
9244 // Only diagnose out-of-line method definitions. If they are
9245 // in class definitions, then an error will be generated when
9246 // processing the class bodies.
9247 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9248 }
Richard Trieue6caa262017-12-23 00:41:01 +00009249 }
9250 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009251 continue;
9252 }
9253
Vedant Kumar48b4f762018-04-14 01:40:48 +00009254 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009255 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009256 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009257 }
9258 PendingBodies.clear();
9259
Richard Smith42413142015-05-15 20:05:43 +00009260 // Do some cleanup.
9261 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9262 getContext().deduplicateMergedDefinitonsFor(ND);
9263 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009264}
9265
9266void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009267 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009268 PendingFunctionOdrMergeFailures.empty() &&
9269 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009270 return;
9271
Richard Smitha0ce9c42014-07-29 23:23:27 +00009272 // Trigger the import of the full definition of each class that had any
9273 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009274 // These updates may in turn find and diagnose some ODR failures, so take
9275 // ownership of the set first.
9276 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9277 PendingOdrMergeFailures.clear();
9278 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009279 Merge.first->buildLookup();
9280 Merge.first->decls_begin();
9281 Merge.first->bases_begin();
9282 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009283 for (auto &RecordPair : Merge.second) {
9284 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009285 RD->decls_begin();
9286 RD->bases_begin();
9287 RD->vbases_begin();
9288 }
9289 }
9290
Richard Trieue6caa262017-12-23 00:41:01 +00009291 // Trigger the import of functions.
9292 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9293 PendingFunctionOdrMergeFailures.clear();
9294 for (auto &Merge : FunctionOdrMergeFailures) {
9295 Merge.first->buildLookup();
9296 Merge.first->decls_begin();
9297 Merge.first->getBody();
9298 for (auto &FD : Merge.second) {
9299 FD->buildLookup();
9300 FD->decls_begin();
9301 FD->getBody();
9302 }
9303 }
9304
Richard Trieuab4d7302018-07-25 22:52:05 +00009305 // Trigger the import of enums.
9306 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9307 PendingEnumOdrMergeFailures.clear();
9308 for (auto &Merge : EnumOdrMergeFailures) {
9309 Merge.first->decls_begin();
9310 for (auto &Enum : Merge.second) {
9311 Enum->decls_begin();
9312 }
9313 }
9314
Richard Smitha0ce9c42014-07-29 23:23:27 +00009315 // For each declaration from a merged context, check that the canonical
9316 // definition of that context also contains a declaration of the same
9317 // entity.
9318 //
9319 // Caution: this loop does things that might invalidate iterators into
9320 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9321 while (!PendingOdrMergeChecks.empty()) {
9322 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9323
9324 // FIXME: Skip over implicit declarations for now. This matters for things
9325 // like implicitly-declared special member functions. This isn't entirely
9326 // correct; we can end up with multiple unmerged declarations of the same
9327 // implicit entity.
9328 if (D->isImplicit())
9329 continue;
9330
9331 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009332
9333 bool Found = false;
9334 const Decl *DCanon = D->getCanonicalDecl();
9335
Richard Smith01bdb7a2014-08-28 05:44:07 +00009336 for (auto RI : D->redecls()) {
9337 if (RI->getLexicalDeclContext() == CanonDef) {
9338 Found = true;
9339 break;
9340 }
9341 }
9342 if (Found)
9343 continue;
9344
Richard Smith0f4e2c42015-08-06 04:23:48 +00009345 // Quick check failed, time to do the slow thing. Note, we can't just
9346 // look up the name of D in CanonDef here, because the member that is
9347 // in CanonDef might not be found by name lookup (it might have been
9348 // replaced by a more recent declaration in the lookup table), and we
9349 // can't necessarily find it in the redeclaration chain because it might
9350 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009351 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009352 for (auto *CanonMember : CanonDef->decls()) {
9353 if (CanonMember->getCanonicalDecl() == DCanon) {
9354 // This can happen if the declaration is merely mergeable and not
9355 // actually redeclarable (we looked for redeclarations earlier).
9356 //
9357 // FIXME: We should be able to detect this more efficiently, without
9358 // pulling in all of the members of CanonDef.
9359 Found = true;
9360 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009361 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009362 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9363 if (ND->getDeclName() == D->getDeclName())
9364 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009365 }
9366
9367 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009368 // The AST doesn't like TagDecls becoming invalid after they've been
9369 // completed. We only really need to mark FieldDecls as invalid here.
9370 if (!isa<TagDecl>(D))
9371 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009372
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009373 // Ensure we don't accidentally recursively enter deserialization while
9374 // we're producing our diagnostic.
9375 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009376
9377 std::string CanonDefModule =
9378 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9379 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9380 << D << getOwningModuleNameForDiagnostic(D)
9381 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9382
9383 if (Candidates.empty())
9384 Diag(cast<Decl>(CanonDef)->getLocation(),
9385 diag::note_module_odr_violation_no_possible_decls) << D;
9386 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009387 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9388 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009389 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009390 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009391 }
9392
9393 DiagnosedOdrMergeFailures.insert(CanonDef);
9394 }
9395 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009396
Richard Trieuab4d7302018-07-25 22:52:05 +00009397 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9398 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009399 return;
9400
9401 // Ensure we don't accidentally recursively enter deserialization while
9402 // we're producing our diagnostics.
9403 Deserializing RecursionGuard(this);
9404
Richard Trieue6caa262017-12-23 00:41:01 +00009405 // Common code for hashing helpers.
9406 ODRHash Hash;
9407 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9408 Hash.clear();
9409 Hash.AddQualType(Ty);
9410 return Hash.CalculateHash();
9411 };
9412
9413 auto ComputeODRHash = [&Hash](const Stmt *S) {
9414 assert(S);
9415 Hash.clear();
9416 Hash.AddStmt(S);
9417 return Hash.CalculateHash();
9418 };
9419
9420 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9421 assert(D);
9422 Hash.clear();
9423 Hash.AddSubDecl(D);
9424 return Hash.CalculateHash();
9425 };
9426
Richard Trieu7282d322018-04-25 00:31:15 +00009427 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9428 Hash.clear();
9429 Hash.AddTemplateArgument(TA);
9430 return Hash.CalculateHash();
9431 };
9432
Richard Trieu9359e8f2018-05-30 01:12:26 +00009433 auto ComputeTemplateParameterListODRHash =
9434 [&Hash](const TemplateParameterList *TPL) {
9435 assert(TPL);
9436 Hash.clear();
9437 Hash.AddTemplateParameterList(TPL);
9438 return Hash.CalculateHash();
9439 };
9440
Richard Smithcd45dbc2014-04-19 03:48:30 +00009441 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009442 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009443 // If we've already pointed out a specific problem with this class, don't
9444 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009445 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009446 continue;
9447
9448 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009449 CXXRecordDecl *FirstRecord = Merge.first;
9450 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009451 for (auto &RecordPair : Merge.second) {
9452 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009453 // Multiple different declarations got merged together; tell the user
9454 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009455 if (FirstRecord == SecondRecord)
9456 continue;
9457
9458 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009459
9460 auto *FirstDD = FirstRecord->DefinitionData;
9461 auto *SecondDD = RecordPair.second;
9462
9463 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9464
9465 // Diagnostics from DefinitionData are emitted here.
9466 if (FirstDD != SecondDD) {
9467 enum ODRDefinitionDataDifference {
9468 NumBases,
9469 NumVBases,
9470 BaseType,
9471 BaseVirtual,
9472 BaseAccess,
9473 };
9474 auto ODRDiagError = [FirstRecord, &FirstModule,
9475 this](SourceLocation Loc, SourceRange Range,
9476 ODRDefinitionDataDifference DiffType) {
9477 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9478 << FirstRecord << FirstModule.empty() << FirstModule << Range
9479 << DiffType;
9480 };
9481 auto ODRDiagNote = [&SecondModule,
9482 this](SourceLocation Loc, SourceRange Range,
9483 ODRDefinitionDataDifference DiffType) {
9484 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9485 << SecondModule << Range << DiffType;
9486 };
9487
Richard Trieue13eabe2017-09-30 02:19:17 +00009488 unsigned FirstNumBases = FirstDD->NumBases;
9489 unsigned FirstNumVBases = FirstDD->NumVBases;
9490 unsigned SecondNumBases = SecondDD->NumBases;
9491 unsigned SecondNumVBases = SecondDD->NumVBases;
9492
9493 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9494 unsigned NumBases = DD->NumBases;
9495 if (NumBases == 0) return SourceRange();
9496 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009497 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009498 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009499 };
9500
9501 if (FirstNumBases != SecondNumBases) {
9502 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9503 NumBases)
9504 << FirstNumBases;
9505 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9506 NumBases)
9507 << SecondNumBases;
9508 Diagnosed = true;
9509 break;
9510 }
9511
9512 if (FirstNumVBases != SecondNumVBases) {
9513 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9514 NumVBases)
9515 << FirstNumVBases;
9516 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9517 NumVBases)
9518 << SecondNumVBases;
9519 Diagnosed = true;
9520 break;
9521 }
9522
9523 auto FirstBases = FirstDD->bases();
9524 auto SecondBases = SecondDD->bases();
9525 unsigned i = 0;
9526 for (i = 0; i < FirstNumBases; ++i) {
9527 auto FirstBase = FirstBases[i];
9528 auto SecondBase = SecondBases[i];
9529 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9530 ComputeQualTypeODRHash(SecondBase.getType())) {
9531 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9532 BaseType)
9533 << (i + 1) << FirstBase.getType();
9534 ODRDiagNote(SecondRecord->getLocation(),
9535 SecondBase.getSourceRange(), BaseType)
9536 << (i + 1) << SecondBase.getType();
9537 break;
9538 }
9539
9540 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9541 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9542 BaseVirtual)
9543 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9544 ODRDiagNote(SecondRecord->getLocation(),
9545 SecondBase.getSourceRange(), BaseVirtual)
9546 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9547 break;
9548 }
9549
9550 if (FirstBase.getAccessSpecifierAsWritten() !=
9551 SecondBase.getAccessSpecifierAsWritten()) {
9552 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9553 BaseAccess)
9554 << (i + 1) << FirstBase.getType()
9555 << (int)FirstBase.getAccessSpecifierAsWritten();
9556 ODRDiagNote(SecondRecord->getLocation(),
9557 SecondBase.getSourceRange(), BaseAccess)
9558 << (i + 1) << SecondBase.getType()
9559 << (int)SecondBase.getAccessSpecifierAsWritten();
9560 break;
9561 }
9562 }
9563
9564 if (i != FirstNumBases) {
9565 Diagnosed = true;
9566 break;
9567 }
9568 }
9569
Richard Trieue7f7ed22017-02-22 01:11:25 +00009570 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009571
9572 const ClassTemplateDecl *FirstTemplate =
9573 FirstRecord->getDescribedClassTemplate();
9574 const ClassTemplateDecl *SecondTemplate =
9575 SecondRecord->getDescribedClassTemplate();
9576
9577 assert(!FirstTemplate == !SecondTemplate &&
9578 "Both pointers should be null or non-null");
9579
9580 enum ODRTemplateDifference {
9581 ParamEmptyName,
9582 ParamName,
9583 ParamSingleDefaultArgument,
9584 ParamDifferentDefaultArgument,
9585 };
9586
9587 if (FirstTemplate && SecondTemplate) {
9588 DeclHashes FirstTemplateHashes;
9589 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009590
9591 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009592 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9593 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009594 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009595 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009596 }
9597 };
9598
9599 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9600 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9601
9602 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9603 "Number of template parameters should be equal.");
9604
9605 auto FirstIt = FirstTemplateHashes.begin();
9606 auto FirstEnd = FirstTemplateHashes.end();
9607 auto SecondIt = SecondTemplateHashes.begin();
9608 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9609 if (FirstIt->second == SecondIt->second)
9610 continue;
9611
9612 auto ODRDiagError = [FirstRecord, &FirstModule,
9613 this](SourceLocation Loc, SourceRange Range,
9614 ODRTemplateDifference DiffType) {
9615 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9616 << FirstRecord << FirstModule.empty() << FirstModule << Range
9617 << DiffType;
9618 };
9619 auto ODRDiagNote = [&SecondModule,
9620 this](SourceLocation Loc, SourceRange Range,
9621 ODRTemplateDifference DiffType) {
9622 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9623 << SecondModule << Range << DiffType;
9624 };
9625
Vedant Kumar48b4f762018-04-14 01:40:48 +00009626 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9627 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009628
9629 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9630 "Parameter Decl's should be the same kind.");
9631
9632 DeclarationName FirstName = FirstDecl->getDeclName();
9633 DeclarationName SecondName = SecondDecl->getDeclName();
9634
9635 if (FirstName != SecondName) {
9636 const bool FirstNameEmpty =
9637 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9638 const bool SecondNameEmpty =
9639 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9640 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9641 "Both template parameters cannot be unnamed.");
9642 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9643 FirstNameEmpty ? ParamEmptyName : ParamName)
9644 << FirstName;
9645 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9646 SecondNameEmpty ? ParamEmptyName : ParamName)
9647 << SecondName;
9648 break;
9649 }
9650
9651 switch (FirstDecl->getKind()) {
9652 default:
9653 llvm_unreachable("Invalid template parameter type.");
9654 case Decl::TemplateTypeParm: {
9655 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9656 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9657 const bool HasFirstDefaultArgument =
9658 FirstParam->hasDefaultArgument() &&
9659 !FirstParam->defaultArgumentWasInherited();
9660 const bool HasSecondDefaultArgument =
9661 SecondParam->hasDefaultArgument() &&
9662 !SecondParam->defaultArgumentWasInherited();
9663
9664 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9665 ODRDiagError(FirstDecl->getLocation(),
9666 FirstDecl->getSourceRange(),
9667 ParamSingleDefaultArgument)
9668 << HasFirstDefaultArgument;
9669 ODRDiagNote(SecondDecl->getLocation(),
9670 SecondDecl->getSourceRange(),
9671 ParamSingleDefaultArgument)
9672 << HasSecondDefaultArgument;
9673 break;
9674 }
9675
9676 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9677 "Expecting default arguments.");
9678
9679 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9680 ParamDifferentDefaultArgument);
9681 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9682 ParamDifferentDefaultArgument);
9683
9684 break;
9685 }
9686 case Decl::NonTypeTemplateParm: {
9687 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9688 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9689 const bool HasFirstDefaultArgument =
9690 FirstParam->hasDefaultArgument() &&
9691 !FirstParam->defaultArgumentWasInherited();
9692 const bool HasSecondDefaultArgument =
9693 SecondParam->hasDefaultArgument() &&
9694 !SecondParam->defaultArgumentWasInherited();
9695
9696 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9697 ODRDiagError(FirstDecl->getLocation(),
9698 FirstDecl->getSourceRange(),
9699 ParamSingleDefaultArgument)
9700 << HasFirstDefaultArgument;
9701 ODRDiagNote(SecondDecl->getLocation(),
9702 SecondDecl->getSourceRange(),
9703 ParamSingleDefaultArgument)
9704 << HasSecondDefaultArgument;
9705 break;
9706 }
9707
9708 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9709 "Expecting default arguments.");
9710
9711 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9712 ParamDifferentDefaultArgument);
9713 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9714 ParamDifferentDefaultArgument);
9715
9716 break;
9717 }
9718 case Decl::TemplateTemplateParm: {
9719 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9720 const auto *SecondParam =
9721 cast<TemplateTemplateParmDecl>(SecondDecl);
9722 const bool HasFirstDefaultArgument =
9723 FirstParam->hasDefaultArgument() &&
9724 !FirstParam->defaultArgumentWasInherited();
9725 const bool HasSecondDefaultArgument =
9726 SecondParam->hasDefaultArgument() &&
9727 !SecondParam->defaultArgumentWasInherited();
9728
9729 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9730 ODRDiagError(FirstDecl->getLocation(),
9731 FirstDecl->getSourceRange(),
9732 ParamSingleDefaultArgument)
9733 << HasFirstDefaultArgument;
9734 ODRDiagNote(SecondDecl->getLocation(),
9735 SecondDecl->getSourceRange(),
9736 ParamSingleDefaultArgument)
9737 << HasSecondDefaultArgument;
9738 break;
9739 }
9740
9741 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9742 "Expecting default arguments.");
9743
9744 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9745 ParamDifferentDefaultArgument);
9746 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9747 ParamDifferentDefaultArgument);
9748
9749 break;
9750 }
9751 }
9752
9753 break;
9754 }
9755
9756 if (FirstIt != FirstEnd) {
9757 Diagnosed = true;
9758 break;
9759 }
9760 }
9761
Richard Trieue7f7ed22017-02-22 01:11:25 +00009762 DeclHashes FirstHashes;
9763 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009764
Richard Trieue6caa262017-12-23 00:41:01 +00009765 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9766 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009767 for (auto *D : Record->decls()) {
9768 // Due to decl merging, the first CXXRecordDecl is the parent of
9769 // Decls in both records.
9770 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9771 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009772 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009773 }
9774 };
9775 PopulateHashes(FirstHashes, FirstRecord);
9776 PopulateHashes(SecondHashes, SecondRecord);
9777
9778 // Used with err_module_odr_violation_mismatch_decl and
9779 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009780 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009781 enum {
9782 EndOfClass,
9783 PublicSpecifer,
9784 PrivateSpecifer,
9785 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009786 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009787 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009788 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009789 TypeAlias,
9790 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009791 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009792 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009793 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009794 Other
9795 } FirstDiffType = Other,
9796 SecondDiffType = Other;
9797
9798 auto DifferenceSelector = [](Decl *D) {
9799 assert(D && "valid Decl required");
9800 switch (D->getKind()) {
9801 default:
9802 return Other;
9803 case Decl::AccessSpec:
9804 switch (D->getAccess()) {
9805 case AS_public:
9806 return PublicSpecifer;
9807 case AS_private:
9808 return PrivateSpecifer;
9809 case AS_protected:
9810 return ProtectedSpecifer;
9811 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009812 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009813 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009814 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009815 case Decl::StaticAssert:
9816 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009817 case Decl::Field:
9818 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009819 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009820 case Decl::CXXConstructor:
9821 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009822 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009823 case Decl::TypeAlias:
9824 return TypeAlias;
9825 case Decl::Typedef:
9826 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009827 case Decl::Var:
9828 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009829 case Decl::Friend:
9830 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +00009831 case Decl::FunctionTemplate:
9832 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009833 }
9834 };
9835
9836 Decl *FirstDecl = nullptr;
9837 Decl *SecondDecl = nullptr;
9838 auto FirstIt = FirstHashes.begin();
9839 auto SecondIt = SecondHashes.begin();
9840
9841 // If there is a diagnoseable difference, FirstDiffType and
9842 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9843 // filled in if not EndOfClass.
9844 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009845 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9846 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009847 ++FirstIt;
9848 ++SecondIt;
9849 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009850 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009851
Richard Trieue7f7ed22017-02-22 01:11:25 +00009852 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9853 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9854
9855 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9856 SecondDiffType =
9857 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9858
9859 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009860 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009861
9862 if (FirstDiffType == Other || SecondDiffType == Other) {
9863 // Reaching this point means an unexpected Decl was encountered
9864 // or no difference was detected. This causes a generic error
9865 // message to be emitted.
9866 Diag(FirstRecord->getLocation(),
9867 diag::err_module_odr_violation_different_definitions)
9868 << FirstRecord << FirstModule.empty() << FirstModule;
9869
Richard Trieuca48d362017-06-21 01:43:13 +00009870 if (FirstDecl) {
9871 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9872 << FirstRecord << FirstDecl->getSourceRange();
9873 }
9874
Richard Trieue7f7ed22017-02-22 01:11:25 +00009875 Diag(SecondRecord->getLocation(),
9876 diag::note_module_odr_violation_different_definitions)
9877 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009878
9879 if (SecondDecl) {
9880 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9881 << SecondDecl->getSourceRange();
9882 }
9883
Richard Trieue7f7ed22017-02-22 01:11:25 +00009884 Diagnosed = true;
9885 break;
9886 }
9887
9888 if (FirstDiffType != SecondDiffType) {
9889 SourceLocation FirstLoc;
9890 SourceRange FirstRange;
9891 if (FirstDiffType == EndOfClass) {
9892 FirstLoc = FirstRecord->getBraceRange().getEnd();
9893 } else {
9894 FirstLoc = FirstIt->first->getLocation();
9895 FirstRange = FirstIt->first->getSourceRange();
9896 }
9897 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9898 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9899 << FirstDiffType;
9900
9901 SourceLocation SecondLoc;
9902 SourceRange SecondRange;
9903 if (SecondDiffType == EndOfClass) {
9904 SecondLoc = SecondRecord->getBraceRange().getEnd();
9905 } else {
9906 SecondLoc = SecondDecl->getLocation();
9907 SecondRange = SecondDecl->getSourceRange();
9908 }
9909 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9910 << SecondModule << SecondRange << SecondDiffType;
9911 Diagnosed = true;
9912 break;
9913 }
9914
Richard Trieu639d7b62017-02-22 22:22:42 +00009915 assert(FirstDiffType == SecondDiffType);
9916
9917 // Used with err_module_odr_violation_mismatch_decl_diff and
9918 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +00009919 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +00009920 StaticAssertCondition,
9921 StaticAssertMessage,
9922 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009923 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009924 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009925 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009926 FieldDifferentWidthBitField,
9927 FieldSingleMutable,
9928 FieldSingleInitializer,
9929 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009930 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009931 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009932 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +00009933 MethodVirtual,
9934 MethodStatic,
9935 MethodVolatile,
9936 MethodConst,
9937 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009938 MethodNumberParameters,
9939 MethodParameterType,
9940 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009941 MethodParameterSingleDefaultArgument,
9942 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +00009943 MethodNoTemplateArguments,
9944 MethodDifferentNumberTemplateArguments,
9945 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009946 MethodSingleBody,
9947 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +00009948 TypedefName,
9949 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009950 VarName,
9951 VarType,
9952 VarSingleInitializer,
9953 VarDifferentInitializer,
9954 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009955 FriendTypeFunction,
9956 FriendType,
9957 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009958 FunctionTemplateDifferentNumberParameters,
9959 FunctionTemplateParameterDifferentKind,
9960 FunctionTemplateParameterName,
9961 FunctionTemplateParameterSingleDefaultArgument,
9962 FunctionTemplateParameterDifferentDefaultArgument,
9963 FunctionTemplateParameterDifferentType,
9964 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +00009965 };
9966
9967 // These lambdas have the common portions of the ODR diagnostics. This
9968 // has the same return as Diag(), so addition parameters can be passed
9969 // in with operator<<
9970 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9971 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9972 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9973 << FirstRecord << FirstModule.empty() << FirstModule << Range
9974 << DiffType;
9975 };
9976 auto ODRDiagNote = [&SecondModule, this](
9977 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9978 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9979 << SecondModule << Range << DiffType;
9980 };
9981
Richard Trieu639d7b62017-02-22 22:22:42 +00009982 switch (FirstDiffType) {
9983 case Other:
9984 case EndOfClass:
9985 case PublicSpecifer:
9986 case PrivateSpecifer:
9987 case ProtectedSpecifer:
9988 llvm_unreachable("Invalid diff type");
9989
9990 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009991 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9992 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +00009993
9994 Expr *FirstExpr = FirstSA->getAssertExpr();
9995 Expr *SecondExpr = SecondSA->getAssertExpr();
9996 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9997 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9998 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009999 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010000 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010001 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10002 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010003 Diagnosed = true;
10004 break;
10005 }
10006
10007 StringLiteral *FirstStr = FirstSA->getMessage();
10008 StringLiteral *SecondStr = SecondSA->getMessage();
10009 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10010 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10011 SourceLocation FirstLoc, SecondLoc;
10012 SourceRange FirstRange, SecondRange;
10013 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010014 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010015 FirstRange = FirstStr->getSourceRange();
10016 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010017 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010018 FirstRange = FirstSA->getSourceRange();
10019 }
10020 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010021 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010022 SecondRange = SecondStr->getSourceRange();
10023 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010024 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010025 SecondRange = SecondSA->getSourceRange();
10026 }
10027 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10028 << (FirstStr == nullptr);
10029 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10030 << (SecondStr == nullptr);
10031 Diagnosed = true;
10032 break;
10033 }
10034
10035 if (FirstStr && SecondStr &&
10036 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010037 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010038 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010039 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010040 StaticAssertMessage);
10041 Diagnosed = true;
10042 break;
10043 }
10044 break;
10045 }
Richard Trieud0786092017-02-23 00:23:01 +000010046 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010047 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10048 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010049 IdentifierInfo *FirstII = FirstField->getIdentifier();
10050 IdentifierInfo *SecondII = SecondField->getIdentifier();
10051 if (FirstII->getName() != SecondII->getName()) {
10052 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10053 FieldName)
10054 << FirstII;
10055 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10056 FieldName)
10057 << SecondII;
10058
10059 Diagnosed = true;
10060 break;
10061 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010062
Richard Smithdbafb6c2017-06-29 23:23:46 +000010063 assert(getContext().hasSameType(FirstField->getType(),
10064 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010065
10066 QualType FirstType = FirstField->getType();
10067 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010068 if (ComputeQualTypeODRHash(FirstType) !=
10069 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010070 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10071 FieldTypeName)
10072 << FirstII << FirstType;
10073 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10074 FieldTypeName)
10075 << SecondII << SecondType;
10076
10077 Diagnosed = true;
10078 break;
10079 }
10080
Richard Trieu93772fc2017-02-24 20:59:28 +000010081 const bool IsFirstBitField = FirstField->isBitField();
10082 const bool IsSecondBitField = SecondField->isBitField();
10083 if (IsFirstBitField != IsSecondBitField) {
10084 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10085 FieldSingleBitField)
10086 << FirstII << IsFirstBitField;
10087 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10088 FieldSingleBitField)
10089 << SecondII << IsSecondBitField;
10090 Diagnosed = true;
10091 break;
10092 }
10093
10094 if (IsFirstBitField && IsSecondBitField) {
10095 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10096 FieldDifferentWidthBitField)
10097 << FirstII << FirstField->getBitWidth()->getSourceRange();
10098 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10099 FieldDifferentWidthBitField)
10100 << SecondII << SecondField->getBitWidth()->getSourceRange();
10101 Diagnosed = true;
10102 break;
10103 }
10104
Richard Trieu8d543e22017-02-24 23:35:37 +000010105 const bool IsFirstMutable = FirstField->isMutable();
10106 const bool IsSecondMutable = SecondField->isMutable();
10107 if (IsFirstMutable != IsSecondMutable) {
10108 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10109 FieldSingleMutable)
10110 << FirstII << IsFirstMutable;
10111 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10112 FieldSingleMutable)
10113 << SecondII << IsSecondMutable;
10114 Diagnosed = true;
10115 break;
10116 }
10117
10118 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10119 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10120 if ((!FirstInitializer && SecondInitializer) ||
10121 (FirstInitializer && !SecondInitializer)) {
10122 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10123 FieldSingleInitializer)
10124 << FirstII << (FirstInitializer != nullptr);
10125 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10126 FieldSingleInitializer)
10127 << SecondII << (SecondInitializer != nullptr);
10128 Diagnosed = true;
10129 break;
10130 }
10131
10132 if (FirstInitializer && SecondInitializer) {
10133 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10134 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10135 if (FirstInitHash != SecondInitHash) {
10136 ODRDiagError(FirstField->getLocation(),
10137 FirstField->getSourceRange(),
10138 FieldDifferentInitializers)
10139 << FirstII << FirstInitializer->getSourceRange();
10140 ODRDiagNote(SecondField->getLocation(),
10141 SecondField->getSourceRange(),
10142 FieldDifferentInitializers)
10143 << SecondII << SecondInitializer->getSourceRange();
10144 Diagnosed = true;
10145 break;
10146 }
10147 }
10148
Richard Trieud0786092017-02-23 00:23:01 +000010149 break;
10150 }
Richard Trieu48143742017-02-28 21:24:38 +000010151 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010152 enum {
10153 DiagMethod,
10154 DiagConstructor,
10155 DiagDestructor,
10156 } FirstMethodType,
10157 SecondMethodType;
10158 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10159 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10160 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10161 return DiagMethod;
10162 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010163 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10164 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010165 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10166 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010167 auto FirstName = FirstMethod->getDeclName();
10168 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010169 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010170 ODRDiagError(FirstMethod->getLocation(),
10171 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010172 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010173 ODRDiagNote(SecondMethod->getLocation(),
10174 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010175 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010176
10177 Diagnosed = true;
10178 break;
10179 }
10180
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010181 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10182 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010183 if (FirstDeleted != SecondDeleted) {
10184 ODRDiagError(FirstMethod->getLocation(),
10185 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010186 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010187
10188 ODRDiagNote(SecondMethod->getLocation(),
10189 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010190 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010191 Diagnosed = true;
10192 break;
10193 }
10194
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010195 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10196 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10197 if (FirstDefaulted != SecondDefaulted) {
10198 ODRDiagError(FirstMethod->getLocation(),
10199 FirstMethod->getSourceRange(), MethodDefaulted)
10200 << FirstMethodType << FirstName << FirstDefaulted;
10201
10202 ODRDiagNote(SecondMethod->getLocation(),
10203 SecondMethod->getSourceRange(), MethodDefaulted)
10204 << SecondMethodType << SecondName << SecondDefaulted;
10205 Diagnosed = true;
10206 break;
10207 }
10208
Richard Trieu583e2c12017-03-04 00:08:58 +000010209 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10210 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10211 const bool FirstPure = FirstMethod->isPure();
10212 const bool SecondPure = SecondMethod->isPure();
10213 if ((FirstVirtual || SecondVirtual) &&
10214 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10215 ODRDiagError(FirstMethod->getLocation(),
10216 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010217 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010218 ODRDiagNote(SecondMethod->getLocation(),
10219 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010220 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010221 Diagnosed = true;
10222 break;
10223 }
10224
10225 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10226 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10227 // class needs to be checked instead.
10228 const auto FirstStorage = FirstMethod->getStorageClass();
10229 const auto SecondStorage = SecondMethod->getStorageClass();
10230 const bool FirstStatic = FirstStorage == SC_Static;
10231 const bool SecondStatic = SecondStorage == SC_Static;
10232 if (FirstStatic != SecondStatic) {
10233 ODRDiagError(FirstMethod->getLocation(),
10234 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010235 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010236 ODRDiagNote(SecondMethod->getLocation(),
10237 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010238 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010239 Diagnosed = true;
10240 break;
10241 }
10242
10243 const bool FirstVolatile = FirstMethod->isVolatile();
10244 const bool SecondVolatile = SecondMethod->isVolatile();
10245 if (FirstVolatile != SecondVolatile) {
10246 ODRDiagError(FirstMethod->getLocation(),
10247 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010248 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010249 ODRDiagNote(SecondMethod->getLocation(),
10250 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010251 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010252 Diagnosed = true;
10253 break;
10254 }
10255
10256 const bool FirstConst = FirstMethod->isConst();
10257 const bool SecondConst = SecondMethod->isConst();
10258 if (FirstConst != SecondConst) {
10259 ODRDiagError(FirstMethod->getLocation(),
10260 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010261 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010262 ODRDiagNote(SecondMethod->getLocation(),
10263 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010264 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010265 Diagnosed = true;
10266 break;
10267 }
10268
10269 const bool FirstInline = FirstMethod->isInlineSpecified();
10270 const bool SecondInline = SecondMethod->isInlineSpecified();
10271 if (FirstInline != SecondInline) {
10272 ODRDiagError(FirstMethod->getLocation(),
10273 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010274 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010275 ODRDiagNote(SecondMethod->getLocation(),
10276 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010277 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010278 Diagnosed = true;
10279 break;
10280 }
10281
Richard Trieu02552272017-05-02 23:58:52 +000010282 const unsigned FirstNumParameters = FirstMethod->param_size();
10283 const unsigned SecondNumParameters = SecondMethod->param_size();
10284 if (FirstNumParameters != SecondNumParameters) {
10285 ODRDiagError(FirstMethod->getLocation(),
10286 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010287 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010288 ODRDiagNote(SecondMethod->getLocation(),
10289 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010290 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010291 Diagnosed = true;
10292 break;
10293 }
10294
10295 // Need this status boolean to know when break out of the switch.
10296 bool ParameterMismatch = false;
10297 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10298 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10299 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10300
10301 QualType FirstParamType = FirstParam->getType();
10302 QualType SecondParamType = SecondParam->getType();
10303 if (FirstParamType != SecondParamType &&
10304 ComputeQualTypeODRHash(FirstParamType) !=
10305 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010306 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010307 FirstParamType->getAs<DecayedType>()) {
10308 ODRDiagError(FirstMethod->getLocation(),
10309 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010310 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10311 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010312 } else {
10313 ODRDiagError(FirstMethod->getLocation(),
10314 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010315 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10316 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010317 }
10318
Vedant Kumar48b4f762018-04-14 01:40:48 +000010319 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010320 SecondParamType->getAs<DecayedType>()) {
10321 ODRDiagNote(SecondMethod->getLocation(),
10322 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010323 << SecondMethodType << SecondName << (I + 1)
10324 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010325 << ParamDecayedType->getOriginalType();
10326 } else {
10327 ODRDiagNote(SecondMethod->getLocation(),
10328 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010329 << SecondMethodType << SecondName << (I + 1)
10330 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010331 }
10332 ParameterMismatch = true;
10333 break;
10334 }
10335
10336 DeclarationName FirstParamName = FirstParam->getDeclName();
10337 DeclarationName SecondParamName = SecondParam->getDeclName();
10338 if (FirstParamName != SecondParamName) {
10339 ODRDiagError(FirstMethod->getLocation(),
10340 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010341 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010342 ODRDiagNote(SecondMethod->getLocation(),
10343 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010344 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010345 ParameterMismatch = true;
10346 break;
10347 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010348
10349 const Expr *FirstInit = FirstParam->getInit();
10350 const Expr *SecondInit = SecondParam->getInit();
10351 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10352 ODRDiagError(FirstMethod->getLocation(),
10353 FirstMethod->getSourceRange(),
10354 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010355 << FirstMethodType << FirstName << (I + 1)
10356 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010357 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10358 ODRDiagNote(SecondMethod->getLocation(),
10359 SecondMethod->getSourceRange(),
10360 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010361 << SecondMethodType << SecondName << (I + 1)
10362 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010363 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10364 ParameterMismatch = true;
10365 break;
10366 }
10367
10368 if (FirstInit && SecondInit &&
10369 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10370 ODRDiagError(FirstMethod->getLocation(),
10371 FirstMethod->getSourceRange(),
10372 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010373 << FirstMethodType << FirstName << (I + 1)
10374 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010375 ODRDiagNote(SecondMethod->getLocation(),
10376 SecondMethod->getSourceRange(),
10377 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010378 << SecondMethodType << SecondName << (I + 1)
10379 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010380 ParameterMismatch = true;
10381 break;
10382
10383 }
Richard Trieu02552272017-05-02 23:58:52 +000010384 }
10385
10386 if (ParameterMismatch) {
10387 Diagnosed = true;
10388 break;
10389 }
10390
Richard Trieu7282d322018-04-25 00:31:15 +000010391 const auto *FirstTemplateArgs =
10392 FirstMethod->getTemplateSpecializationArgs();
10393 const auto *SecondTemplateArgs =
10394 SecondMethod->getTemplateSpecializationArgs();
10395
10396 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10397 (!FirstTemplateArgs && SecondTemplateArgs)) {
10398 ODRDiagError(FirstMethod->getLocation(),
10399 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10400 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10401 ODRDiagNote(SecondMethod->getLocation(),
10402 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10403 << SecondMethodType << SecondName
10404 << (SecondTemplateArgs != nullptr);
10405
10406 Diagnosed = true;
10407 break;
10408 }
10409
10410 if (FirstTemplateArgs && SecondTemplateArgs) {
10411 // Remove pack expansions from argument list.
10412 auto ExpandTemplateArgumentList =
10413 [](const TemplateArgumentList *TAL) {
10414 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10415 for (const TemplateArgument &TA : TAL->asArray()) {
10416 if (TA.getKind() != TemplateArgument::Pack) {
10417 ExpandedList.push_back(&TA);
10418 continue;
10419 }
10420 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10421 ExpandedList.push_back(&PackTA);
10422 }
10423 }
10424 return ExpandedList;
10425 };
10426 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10427 ExpandTemplateArgumentList(FirstTemplateArgs);
10428 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10429 ExpandTemplateArgumentList(SecondTemplateArgs);
10430
10431 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10432 ODRDiagError(FirstMethod->getLocation(),
10433 FirstMethod->getSourceRange(),
10434 MethodDifferentNumberTemplateArguments)
10435 << FirstMethodType << FirstName
10436 << (unsigned)FirstExpandedList.size();
10437 ODRDiagNote(SecondMethod->getLocation(),
10438 SecondMethod->getSourceRange(),
10439 MethodDifferentNumberTemplateArguments)
10440 << SecondMethodType << SecondName
10441 << (unsigned)SecondExpandedList.size();
10442
10443 Diagnosed = true;
10444 break;
10445 }
10446
10447 bool TemplateArgumentMismatch = false;
10448 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10449 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10450 &SecondTA = *SecondExpandedList[i];
10451 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10452 ComputeTemplateArgumentODRHash(SecondTA)) {
10453 continue;
10454 }
10455
10456 ODRDiagError(FirstMethod->getLocation(),
10457 FirstMethod->getSourceRange(),
10458 MethodDifferentTemplateArgument)
10459 << FirstMethodType << FirstName << FirstTA << i + 1;
10460 ODRDiagNote(SecondMethod->getLocation(),
10461 SecondMethod->getSourceRange(),
10462 MethodDifferentTemplateArgument)
10463 << SecondMethodType << SecondName << SecondTA << i + 1;
10464
10465 TemplateArgumentMismatch = true;
10466 break;
10467 }
10468
10469 if (TemplateArgumentMismatch) {
10470 Diagnosed = true;
10471 break;
10472 }
10473 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010474
10475 // Compute the hash of the method as if it has no body.
10476 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10477 Hash.clear();
10478 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10479 return Hash.CalculateHash();
10480 };
10481
10482 // Compare the hash generated to the hash stored. A difference means
10483 // that a body was present in the original source. Due to merging,
10484 // the stardard way of detecting a body will not work.
10485 const bool HasFirstBody =
10486 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10487 const bool HasSecondBody =
10488 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10489
10490 if (HasFirstBody != HasSecondBody) {
10491 ODRDiagError(FirstMethod->getLocation(),
10492 FirstMethod->getSourceRange(), MethodSingleBody)
10493 << FirstMethodType << FirstName << HasFirstBody;
10494 ODRDiagNote(SecondMethod->getLocation(),
10495 SecondMethod->getSourceRange(), MethodSingleBody)
10496 << SecondMethodType << SecondName << HasSecondBody;
10497 Diagnosed = true;
10498 break;
10499 }
10500
10501 if (HasFirstBody && HasSecondBody) {
10502 ODRDiagError(FirstMethod->getLocation(),
10503 FirstMethod->getSourceRange(), MethodDifferentBody)
10504 << FirstMethodType << FirstName;
10505 ODRDiagNote(SecondMethod->getLocation(),
10506 SecondMethod->getSourceRange(), MethodDifferentBody)
10507 << SecondMethodType << SecondName;
10508 Diagnosed = true;
10509 break;
10510 }
10511
Richard Trieu48143742017-02-28 21:24:38 +000010512 break;
10513 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010514 case TypeAlias:
10515 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010516 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10517 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010518 auto FirstName = FirstTD->getDeclName();
10519 auto SecondName = SecondTD->getDeclName();
10520 if (FirstName != SecondName) {
10521 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10522 TypedefName)
10523 << (FirstDiffType == TypeAlias) << FirstName;
10524 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10525 TypedefName)
10526 << (FirstDiffType == TypeAlias) << SecondName;
10527 Diagnosed = true;
10528 break;
10529 }
10530
10531 QualType FirstType = FirstTD->getUnderlyingType();
10532 QualType SecondType = SecondTD->getUnderlyingType();
10533 if (ComputeQualTypeODRHash(FirstType) !=
10534 ComputeQualTypeODRHash(SecondType)) {
10535 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10536 TypedefType)
10537 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10538 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10539 TypedefType)
10540 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10541 Diagnosed = true;
10542 break;
10543 }
10544 break;
10545 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010546 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010547 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10548 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010549 auto FirstName = FirstVD->getDeclName();
10550 auto SecondName = SecondVD->getDeclName();
10551 if (FirstName != SecondName) {
10552 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10553 VarName)
10554 << FirstName;
10555 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10556 VarName)
10557 << SecondName;
10558 Diagnosed = true;
10559 break;
10560 }
10561
10562 QualType FirstType = FirstVD->getType();
10563 QualType SecondType = SecondVD->getType();
10564 if (ComputeQualTypeODRHash(FirstType) !=
10565 ComputeQualTypeODRHash(SecondType)) {
10566 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10567 VarType)
10568 << FirstName << FirstType;
10569 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10570 VarType)
10571 << SecondName << SecondType;
10572 Diagnosed = true;
10573 break;
10574 }
10575
10576 const Expr *FirstInit = FirstVD->getInit();
10577 const Expr *SecondInit = SecondVD->getInit();
10578 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10579 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10580 VarSingleInitializer)
10581 << FirstName << (FirstInit == nullptr)
10582 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10583 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10584 VarSingleInitializer)
10585 << SecondName << (SecondInit == nullptr)
10586 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10587 Diagnosed = true;
10588 break;
10589 }
10590
10591 if (FirstInit && SecondInit &&
10592 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10593 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10594 VarDifferentInitializer)
10595 << FirstName << FirstInit->getSourceRange();
10596 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10597 VarDifferentInitializer)
10598 << SecondName << SecondInit->getSourceRange();
10599 Diagnosed = true;
10600 break;
10601 }
10602
10603 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10604 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10605 if (FirstIsConstexpr != SecondIsConstexpr) {
10606 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10607 VarConstexpr)
10608 << FirstName << FirstIsConstexpr;
10609 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10610 VarConstexpr)
10611 << SecondName << SecondIsConstexpr;
10612 Diagnosed = true;
10613 break;
10614 }
10615 break;
10616 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010617 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010618 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10619 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010620
10621 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10622 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10623
10624 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10625 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10626
10627 if (FirstND && SecondND) {
10628 ODRDiagError(FirstFriend->getFriendLoc(),
10629 FirstFriend->getSourceRange(), FriendFunction)
10630 << FirstND;
10631 ODRDiagNote(SecondFriend->getFriendLoc(),
10632 SecondFriend->getSourceRange(), FriendFunction)
10633 << SecondND;
10634
10635 Diagnosed = true;
10636 break;
10637 }
10638
10639 if (FirstTSI && SecondTSI) {
10640 QualType FirstFriendType = FirstTSI->getType();
10641 QualType SecondFriendType = SecondTSI->getType();
10642 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10643 ComputeQualTypeODRHash(SecondFriendType));
10644 ODRDiagError(FirstFriend->getFriendLoc(),
10645 FirstFriend->getSourceRange(), FriendType)
10646 << FirstFriendType;
10647 ODRDiagNote(SecondFriend->getFriendLoc(),
10648 SecondFriend->getSourceRange(), FriendType)
10649 << SecondFriendType;
10650 Diagnosed = true;
10651 break;
10652 }
10653
10654 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10655 FriendTypeFunction)
10656 << (FirstTSI == nullptr);
10657 ODRDiagNote(SecondFriend->getFriendLoc(),
10658 SecondFriend->getSourceRange(), FriendTypeFunction)
10659 << (SecondTSI == nullptr);
10660
10661 Diagnosed = true;
10662 break;
10663 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010664 case FunctionTemplate: {
10665 FunctionTemplateDecl *FirstTemplate =
10666 cast<FunctionTemplateDecl>(FirstDecl);
10667 FunctionTemplateDecl *SecondTemplate =
10668 cast<FunctionTemplateDecl>(SecondDecl);
10669
10670 TemplateParameterList *FirstTPL =
10671 FirstTemplate->getTemplateParameters();
10672 TemplateParameterList *SecondTPL =
10673 SecondTemplate->getTemplateParameters();
10674
10675 if (FirstTPL->size() != SecondTPL->size()) {
10676 ODRDiagError(FirstTemplate->getLocation(),
10677 FirstTemplate->getSourceRange(),
10678 FunctionTemplateDifferentNumberParameters)
10679 << FirstTemplate << FirstTPL->size();
10680 ODRDiagNote(SecondTemplate->getLocation(),
10681 SecondTemplate->getSourceRange(),
10682 FunctionTemplateDifferentNumberParameters)
10683 << SecondTemplate << SecondTPL->size();
10684
10685 Diagnosed = true;
10686 break;
10687 }
10688
10689 bool ParameterMismatch = false;
10690 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10691 NamedDecl *FirstParam = FirstTPL->getParam(i);
10692 NamedDecl *SecondParam = SecondTPL->getParam(i);
10693
10694 if (FirstParam->getKind() != SecondParam->getKind()) {
10695 enum {
10696 TemplateTypeParameter,
10697 NonTypeTemplateParameter,
10698 TemplateTemplateParameter,
10699 };
10700 auto GetParamType = [](NamedDecl *D) {
10701 switch (D->getKind()) {
10702 default:
10703 llvm_unreachable("Unexpected template parameter type");
10704 case Decl::TemplateTypeParm:
10705 return TemplateTypeParameter;
10706 case Decl::NonTypeTemplateParm:
10707 return NonTypeTemplateParameter;
10708 case Decl::TemplateTemplateParm:
10709 return TemplateTemplateParameter;
10710 }
10711 };
10712
10713 ODRDiagError(FirstTemplate->getLocation(),
10714 FirstTemplate->getSourceRange(),
10715 FunctionTemplateParameterDifferentKind)
10716 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10717 ODRDiagNote(SecondTemplate->getLocation(),
10718 SecondTemplate->getSourceRange(),
10719 FunctionTemplateParameterDifferentKind)
10720 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10721
10722 ParameterMismatch = true;
10723 break;
10724 }
10725
10726 if (FirstParam->getName() != SecondParam->getName()) {
10727 ODRDiagError(FirstTemplate->getLocation(),
10728 FirstTemplate->getSourceRange(),
10729 FunctionTemplateParameterName)
10730 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10731 << FirstParam;
10732 ODRDiagNote(SecondTemplate->getLocation(),
10733 SecondTemplate->getSourceRange(),
10734 FunctionTemplateParameterName)
10735 << SecondTemplate << (i + 1)
10736 << (bool)SecondParam->getIdentifier() << SecondParam;
10737 ParameterMismatch = true;
10738 break;
10739 }
10740
10741 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10742 isa<TemplateTypeParmDecl>(SecondParam)) {
10743 TemplateTypeParmDecl *FirstTTPD =
10744 cast<TemplateTypeParmDecl>(FirstParam);
10745 TemplateTypeParmDecl *SecondTTPD =
10746 cast<TemplateTypeParmDecl>(SecondParam);
10747 bool HasFirstDefaultArgument =
10748 FirstTTPD->hasDefaultArgument() &&
10749 !FirstTTPD->defaultArgumentWasInherited();
10750 bool HasSecondDefaultArgument =
10751 SecondTTPD->hasDefaultArgument() &&
10752 !SecondTTPD->defaultArgumentWasInherited();
10753 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10754 ODRDiagError(FirstTemplate->getLocation(),
10755 FirstTemplate->getSourceRange(),
10756 FunctionTemplateParameterSingleDefaultArgument)
10757 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10758 ODRDiagNote(SecondTemplate->getLocation(),
10759 SecondTemplate->getSourceRange(),
10760 FunctionTemplateParameterSingleDefaultArgument)
10761 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10762 ParameterMismatch = true;
10763 break;
10764 }
10765
10766 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10767 QualType FirstType = FirstTTPD->getDefaultArgument();
10768 QualType SecondType = SecondTTPD->getDefaultArgument();
10769 if (ComputeQualTypeODRHash(FirstType) !=
10770 ComputeQualTypeODRHash(SecondType)) {
10771 ODRDiagError(FirstTemplate->getLocation(),
10772 FirstTemplate->getSourceRange(),
10773 FunctionTemplateParameterDifferentDefaultArgument)
10774 << FirstTemplate << (i + 1) << FirstType;
10775 ODRDiagNote(SecondTemplate->getLocation(),
10776 SecondTemplate->getSourceRange(),
10777 FunctionTemplateParameterDifferentDefaultArgument)
10778 << SecondTemplate << (i + 1) << SecondType;
10779 ParameterMismatch = true;
10780 break;
10781 }
10782 }
10783
10784 if (FirstTTPD->isParameterPack() !=
10785 SecondTTPD->isParameterPack()) {
10786 ODRDiagError(FirstTemplate->getLocation(),
10787 FirstTemplate->getSourceRange(),
10788 FunctionTemplatePackParameter)
10789 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10790 ODRDiagNote(SecondTemplate->getLocation(),
10791 SecondTemplate->getSourceRange(),
10792 FunctionTemplatePackParameter)
10793 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10794 ParameterMismatch = true;
10795 break;
10796 }
10797 }
10798
10799 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10800 isa<TemplateTemplateParmDecl>(SecondParam)) {
10801 TemplateTemplateParmDecl *FirstTTPD =
10802 cast<TemplateTemplateParmDecl>(FirstParam);
10803 TemplateTemplateParmDecl *SecondTTPD =
10804 cast<TemplateTemplateParmDecl>(SecondParam);
10805
10806 TemplateParameterList *FirstTPL =
10807 FirstTTPD->getTemplateParameters();
10808 TemplateParameterList *SecondTPL =
10809 SecondTTPD->getTemplateParameters();
10810
10811 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10812 ComputeTemplateParameterListODRHash(SecondTPL)) {
10813 ODRDiagError(FirstTemplate->getLocation(),
10814 FirstTemplate->getSourceRange(),
10815 FunctionTemplateParameterDifferentType)
10816 << FirstTemplate << (i + 1);
10817 ODRDiagNote(SecondTemplate->getLocation(),
10818 SecondTemplate->getSourceRange(),
10819 FunctionTemplateParameterDifferentType)
10820 << SecondTemplate << (i + 1);
10821 ParameterMismatch = true;
10822 break;
10823 }
10824
10825 bool HasFirstDefaultArgument =
10826 FirstTTPD->hasDefaultArgument() &&
10827 !FirstTTPD->defaultArgumentWasInherited();
10828 bool HasSecondDefaultArgument =
10829 SecondTTPD->hasDefaultArgument() &&
10830 !SecondTTPD->defaultArgumentWasInherited();
10831 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10832 ODRDiagError(FirstTemplate->getLocation(),
10833 FirstTemplate->getSourceRange(),
10834 FunctionTemplateParameterSingleDefaultArgument)
10835 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10836 ODRDiagNote(SecondTemplate->getLocation(),
10837 SecondTemplate->getSourceRange(),
10838 FunctionTemplateParameterSingleDefaultArgument)
10839 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10840 ParameterMismatch = true;
10841 break;
10842 }
10843
10844 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10845 TemplateArgument FirstTA =
10846 FirstTTPD->getDefaultArgument().getArgument();
10847 TemplateArgument SecondTA =
10848 SecondTTPD->getDefaultArgument().getArgument();
10849 if (ComputeTemplateArgumentODRHash(FirstTA) !=
10850 ComputeTemplateArgumentODRHash(SecondTA)) {
10851 ODRDiagError(FirstTemplate->getLocation(),
10852 FirstTemplate->getSourceRange(),
10853 FunctionTemplateParameterDifferentDefaultArgument)
10854 << FirstTemplate << (i + 1) << FirstTA;
10855 ODRDiagNote(SecondTemplate->getLocation(),
10856 SecondTemplate->getSourceRange(),
10857 FunctionTemplateParameterDifferentDefaultArgument)
10858 << SecondTemplate << (i + 1) << SecondTA;
10859 ParameterMismatch = true;
10860 break;
10861 }
10862 }
10863
10864 if (FirstTTPD->isParameterPack() !=
10865 SecondTTPD->isParameterPack()) {
10866 ODRDiagError(FirstTemplate->getLocation(),
10867 FirstTemplate->getSourceRange(),
10868 FunctionTemplatePackParameter)
10869 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10870 ODRDiagNote(SecondTemplate->getLocation(),
10871 SecondTemplate->getSourceRange(),
10872 FunctionTemplatePackParameter)
10873 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10874 ParameterMismatch = true;
10875 break;
10876 }
10877 }
10878
10879 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10880 isa<NonTypeTemplateParmDecl>(SecondParam)) {
10881 NonTypeTemplateParmDecl *FirstNTTPD =
10882 cast<NonTypeTemplateParmDecl>(FirstParam);
10883 NonTypeTemplateParmDecl *SecondNTTPD =
10884 cast<NonTypeTemplateParmDecl>(SecondParam);
10885
10886 QualType FirstType = FirstNTTPD->getType();
10887 QualType SecondType = SecondNTTPD->getType();
10888 if (ComputeQualTypeODRHash(FirstType) !=
10889 ComputeQualTypeODRHash(SecondType)) {
10890 ODRDiagError(FirstTemplate->getLocation(),
10891 FirstTemplate->getSourceRange(),
10892 FunctionTemplateParameterDifferentType)
10893 << FirstTemplate << (i + 1);
10894 ODRDiagNote(SecondTemplate->getLocation(),
10895 SecondTemplate->getSourceRange(),
10896 FunctionTemplateParameterDifferentType)
10897 << SecondTemplate << (i + 1);
10898 ParameterMismatch = true;
10899 break;
10900 }
10901
10902 bool HasFirstDefaultArgument =
10903 FirstNTTPD->hasDefaultArgument() &&
10904 !FirstNTTPD->defaultArgumentWasInherited();
10905 bool HasSecondDefaultArgument =
10906 SecondNTTPD->hasDefaultArgument() &&
10907 !SecondNTTPD->defaultArgumentWasInherited();
10908 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10909 ODRDiagError(FirstTemplate->getLocation(),
10910 FirstTemplate->getSourceRange(),
10911 FunctionTemplateParameterSingleDefaultArgument)
10912 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10913 ODRDiagNote(SecondTemplate->getLocation(),
10914 SecondTemplate->getSourceRange(),
10915 FunctionTemplateParameterSingleDefaultArgument)
10916 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10917 ParameterMismatch = true;
10918 break;
10919 }
10920
10921 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10922 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10923 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10924 if (ComputeODRHash(FirstDefaultArgument) !=
10925 ComputeODRHash(SecondDefaultArgument)) {
10926 ODRDiagError(FirstTemplate->getLocation(),
10927 FirstTemplate->getSourceRange(),
10928 FunctionTemplateParameterDifferentDefaultArgument)
10929 << FirstTemplate << (i + 1) << FirstDefaultArgument;
10930 ODRDiagNote(SecondTemplate->getLocation(),
10931 SecondTemplate->getSourceRange(),
10932 FunctionTemplateParameterDifferentDefaultArgument)
10933 << SecondTemplate << (i + 1) << SecondDefaultArgument;
10934 ParameterMismatch = true;
10935 break;
10936 }
10937 }
10938
10939 if (FirstNTTPD->isParameterPack() !=
10940 SecondNTTPD->isParameterPack()) {
10941 ODRDiagError(FirstTemplate->getLocation(),
10942 FirstTemplate->getSourceRange(),
10943 FunctionTemplatePackParameter)
10944 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
10945 ODRDiagNote(SecondTemplate->getLocation(),
10946 SecondTemplate->getSourceRange(),
10947 FunctionTemplatePackParameter)
10948 << SecondTemplate << (i + 1)
10949 << SecondNTTPD->isParameterPack();
10950 ParameterMismatch = true;
10951 break;
10952 }
10953 }
10954 }
10955
10956 if (ParameterMismatch) {
10957 Diagnosed = true;
10958 break;
10959 }
10960
10961 break;
10962 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010963 }
10964
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010965 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010966 continue;
10967
Richard Trieu708859a2017-06-08 00:56:21 +000010968 Diag(FirstDecl->getLocation(),
10969 diag::err_module_odr_violation_mismatch_decl_unknown)
10970 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10971 << FirstDecl->getSourceRange();
10972 Diag(SecondDecl->getLocation(),
10973 diag::note_module_odr_violation_mismatch_decl_unknown)
10974 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010975 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010976 }
10977
10978 if (!Diagnosed) {
10979 // All definitions are updates to the same declaration. This happens if a
10980 // module instantiates the declaration of a class template specialization
10981 // and two or more other modules instantiate its definition.
10982 //
10983 // FIXME: Indicate which modules had instantiations of this definition.
10984 // FIXME: How can this even happen?
10985 Diag(Merge.first->getLocation(),
10986 diag::err_module_odr_violation_different_instantiations)
10987 << Merge.first;
10988 }
10989 }
Richard Trieue6caa262017-12-23 00:41:01 +000010990
10991 // Issue ODR failures diagnostics for functions.
10992 for (auto &Merge : FunctionOdrMergeFailures) {
10993 enum ODRFunctionDifference {
10994 ReturnType,
10995 ParameterName,
10996 ParameterType,
10997 ParameterSingleDefaultArgument,
10998 ParameterDifferentDefaultArgument,
10999 FunctionBody,
11000 };
11001
11002 FunctionDecl *FirstFunction = Merge.first;
11003 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11004
11005 bool Diagnosed = false;
11006 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011007
Richard Trieue6caa262017-12-23 00:41:01 +000011008 if (FirstFunction == SecondFunction)
11009 continue;
11010
11011 std::string SecondModule =
11012 getOwningModuleNameForDiagnostic(SecondFunction);
11013
11014 auto ODRDiagError = [FirstFunction, &FirstModule,
11015 this](SourceLocation Loc, SourceRange Range,
11016 ODRFunctionDifference DiffType) {
11017 return Diag(Loc, diag::err_module_odr_violation_function)
11018 << FirstFunction << FirstModule.empty() << FirstModule << Range
11019 << DiffType;
11020 };
11021 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11022 SourceRange Range,
11023 ODRFunctionDifference DiffType) {
11024 return Diag(Loc, diag::note_module_odr_violation_function)
11025 << SecondModule << Range << DiffType;
11026 };
11027
11028 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11029 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11030 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11031 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11032 << FirstFunction->getReturnType();
11033 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11034 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11035 << SecondFunction->getReturnType();
11036 Diagnosed = true;
11037 break;
11038 }
11039
11040 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11041 "Merged functions with different number of parameters");
11042
11043 auto ParamSize = FirstFunction->param_size();
11044 bool ParameterMismatch = false;
11045 for (unsigned I = 0; I < ParamSize; ++I) {
11046 auto *FirstParam = FirstFunction->getParamDecl(I);
11047 auto *SecondParam = SecondFunction->getParamDecl(I);
11048
11049 assert(getContext().hasSameType(FirstParam->getType(),
11050 SecondParam->getType()) &&
11051 "Merged function has different parameter types.");
11052
11053 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11054 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11055 ParameterName)
11056 << I + 1 << FirstParam->getDeclName();
11057 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11058 ParameterName)
11059 << I + 1 << SecondParam->getDeclName();
11060 ParameterMismatch = true;
11061 break;
11062 };
11063
11064 QualType FirstParamType = FirstParam->getType();
11065 QualType SecondParamType = SecondParam->getType();
11066 if (FirstParamType != SecondParamType &&
11067 ComputeQualTypeODRHash(FirstParamType) !=
11068 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011069 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011070 FirstParamType->getAs<DecayedType>()) {
11071 ODRDiagError(FirstParam->getLocation(),
11072 FirstParam->getSourceRange(), ParameterType)
11073 << (I + 1) << FirstParamType << true
11074 << ParamDecayedType->getOriginalType();
11075 } else {
11076 ODRDiagError(FirstParam->getLocation(),
11077 FirstParam->getSourceRange(), ParameterType)
11078 << (I + 1) << FirstParamType << false;
11079 }
11080
Vedant Kumar48b4f762018-04-14 01:40:48 +000011081 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011082 SecondParamType->getAs<DecayedType>()) {
11083 ODRDiagNote(SecondParam->getLocation(),
11084 SecondParam->getSourceRange(), ParameterType)
11085 << (I + 1) << SecondParamType << true
11086 << ParamDecayedType->getOriginalType();
11087 } else {
11088 ODRDiagNote(SecondParam->getLocation(),
11089 SecondParam->getSourceRange(), ParameterType)
11090 << (I + 1) << SecondParamType << false;
11091 }
11092 ParameterMismatch = true;
11093 break;
11094 }
11095
11096 const Expr *FirstInit = FirstParam->getInit();
11097 const Expr *SecondInit = SecondParam->getInit();
11098 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11099 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11100 ParameterSingleDefaultArgument)
11101 << (I + 1) << (FirstInit == nullptr)
11102 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11103 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11104 ParameterSingleDefaultArgument)
11105 << (I + 1) << (SecondInit == nullptr)
11106 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11107 ParameterMismatch = true;
11108 break;
11109 }
11110
11111 if (FirstInit && SecondInit &&
11112 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11113 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11114 ParameterDifferentDefaultArgument)
11115 << (I + 1) << FirstInit->getSourceRange();
11116 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11117 ParameterDifferentDefaultArgument)
11118 << (I + 1) << SecondInit->getSourceRange();
11119 ParameterMismatch = true;
11120 break;
11121 }
11122
11123 assert(ComputeSubDeclODRHash(FirstParam) ==
11124 ComputeSubDeclODRHash(SecondParam) &&
11125 "Undiagnosed parameter difference.");
11126 }
11127
11128 if (ParameterMismatch) {
11129 Diagnosed = true;
11130 break;
11131 }
11132
11133 // If no error has been generated before now, assume the problem is in
11134 // the body and generate a message.
11135 ODRDiagError(FirstFunction->getLocation(),
11136 FirstFunction->getSourceRange(), FunctionBody);
11137 ODRDiagNote(SecondFunction->getLocation(),
11138 SecondFunction->getSourceRange(), FunctionBody);
11139 Diagnosed = true;
11140 break;
11141 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011142 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011143 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11144 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011145
11146 // Issue ODR failures diagnostics for enums.
11147 for (auto &Merge : EnumOdrMergeFailures) {
11148 enum ODREnumDifference {
11149 SingleScopedEnum,
11150 EnumTagKeywordMismatch,
11151 SingleSpecifiedType,
11152 DifferentSpecifiedTypes,
11153 DifferentNumberEnumConstants,
11154 EnumConstantName,
11155 EnumConstantSingleInitilizer,
11156 EnumConstantDifferentInitilizer,
11157 };
11158
11159 // If we've already pointed out a specific problem with this enum, don't
11160 // bother issuing a general "something's different" diagnostic.
11161 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11162 continue;
11163
11164 EnumDecl *FirstEnum = Merge.first;
11165 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11166
11167 using DeclHashes =
11168 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11169 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11170 DeclHashes &Hashes, EnumDecl *Enum) {
11171 for (auto *D : Enum->decls()) {
11172 // Due to decl merging, the first EnumDecl is the parent of
11173 // Decls in both records.
11174 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11175 continue;
11176 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11177 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11178 ComputeSubDeclODRHash(D));
11179 }
11180 };
11181 DeclHashes FirstHashes;
11182 PopulateHashes(FirstHashes, FirstEnum);
11183 bool Diagnosed = false;
11184 for (auto &SecondEnum : Merge.second) {
11185
11186 if (FirstEnum == SecondEnum)
11187 continue;
11188
11189 std::string SecondModule =
11190 getOwningModuleNameForDiagnostic(SecondEnum);
11191
11192 auto ODRDiagError = [FirstEnum, &FirstModule,
11193 this](SourceLocation Loc, SourceRange Range,
11194 ODREnumDifference DiffType) {
11195 return Diag(Loc, diag::err_module_odr_violation_enum)
11196 << FirstEnum << FirstModule.empty() << FirstModule << Range
11197 << DiffType;
11198 };
11199 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11200 SourceRange Range,
11201 ODREnumDifference DiffType) {
11202 return Diag(Loc, diag::note_module_odr_violation_enum)
11203 << SecondModule << Range << DiffType;
11204 };
11205
11206 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11207 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11208 SingleScopedEnum)
11209 << FirstEnum->isScoped();
11210 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11211 SingleScopedEnum)
11212 << SecondEnum->isScoped();
11213 Diagnosed = true;
11214 continue;
11215 }
11216
11217 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11218 if (FirstEnum->isScopedUsingClassTag() !=
11219 SecondEnum->isScopedUsingClassTag()) {
11220 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11221 EnumTagKeywordMismatch)
11222 << FirstEnum->isScopedUsingClassTag();
11223 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11224 EnumTagKeywordMismatch)
11225 << SecondEnum->isScopedUsingClassTag();
11226 Diagnosed = true;
11227 continue;
11228 }
11229 }
11230
11231 QualType FirstUnderlyingType =
11232 FirstEnum->getIntegerTypeSourceInfo()
11233 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11234 : QualType();
11235 QualType SecondUnderlyingType =
11236 SecondEnum->getIntegerTypeSourceInfo()
11237 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11238 : QualType();
11239 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11240 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11241 SingleSpecifiedType)
11242 << !FirstUnderlyingType.isNull();
11243 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11244 SingleSpecifiedType)
11245 << !SecondUnderlyingType.isNull();
11246 Diagnosed = true;
11247 continue;
11248 }
11249
11250 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11251 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11252 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11253 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11254 DifferentSpecifiedTypes)
11255 << FirstUnderlyingType;
11256 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11257 DifferentSpecifiedTypes)
11258 << SecondUnderlyingType;
11259 Diagnosed = true;
11260 continue;
11261 }
11262 }
11263
11264 DeclHashes SecondHashes;
11265 PopulateHashes(SecondHashes, SecondEnum);
11266
11267 if (FirstHashes.size() != SecondHashes.size()) {
11268 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11269 DifferentNumberEnumConstants)
11270 << (int)FirstHashes.size();
11271 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11272 DifferentNumberEnumConstants)
11273 << (int)SecondHashes.size();
11274 Diagnosed = true;
11275 continue;
11276 }
11277
11278 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11279 if (FirstHashes[I].second == SecondHashes[I].second)
11280 continue;
11281 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11282 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11283
11284 if (FirstEnumConstant->getDeclName() !=
11285 SecondEnumConstant->getDeclName()) {
11286
11287 ODRDiagError(FirstEnumConstant->getLocation(),
11288 FirstEnumConstant->getSourceRange(), EnumConstantName)
11289 << I + 1 << FirstEnumConstant;
11290 ODRDiagNote(SecondEnumConstant->getLocation(),
11291 SecondEnumConstant->getSourceRange(), EnumConstantName)
11292 << I + 1 << SecondEnumConstant;
11293 Diagnosed = true;
11294 break;
11295 }
11296
11297 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11298 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11299 if (!FirstInit && !SecondInit)
11300 continue;
11301
11302 if (!FirstInit || !SecondInit) {
11303 ODRDiagError(FirstEnumConstant->getLocation(),
11304 FirstEnumConstant->getSourceRange(),
11305 EnumConstantSingleInitilizer)
11306 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11307 ODRDiagNote(SecondEnumConstant->getLocation(),
11308 SecondEnumConstant->getSourceRange(),
11309 EnumConstantSingleInitilizer)
11310 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11311 Diagnosed = true;
11312 break;
11313 }
11314
11315 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11316 ODRDiagError(FirstEnumConstant->getLocation(),
11317 FirstEnumConstant->getSourceRange(),
11318 EnumConstantDifferentInitilizer)
11319 << I + 1 << FirstEnumConstant;
11320 ODRDiagNote(SecondEnumConstant->getLocation(),
11321 SecondEnumConstant->getSourceRange(),
11322 EnumConstantDifferentInitilizer)
11323 << I + 1 << SecondEnumConstant;
11324 Diagnosed = true;
11325 break;
11326 }
11327 }
11328 }
11329
11330 (void)Diagnosed;
11331 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11332 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011333}
11334
Richard Smithce18a182015-07-14 00:26:00 +000011335void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011336 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011337 ReadTimer->startTimer();
11338}
11339
Guy Benyei11169dd2012-12-18 14:30:41 +000011340void ASTReader::FinishedDeserializing() {
11341 assert(NumCurrentElementsDeserializing &&
11342 "FinishedDeserializing not paired with StartedDeserializing");
11343 if (NumCurrentElementsDeserializing == 1) {
11344 // We decrease NumCurrentElementsDeserializing only after pending actions
11345 // are finished, to avoid recursively re-calling finishPendingActions().
11346 finishPendingActions();
11347 }
11348 --NumCurrentElementsDeserializing;
11349
Richard Smitha0ce9c42014-07-29 23:23:27 +000011350 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011351 // Propagate exception specification and deduced type updates along
11352 // redeclaration chains.
11353 //
11354 // We do this now rather than in finishPendingActions because we want to
11355 // be able to walk the complete redeclaration chains of the updated decls.
11356 while (!PendingExceptionSpecUpdates.empty() ||
11357 !PendingDeducedTypeUpdates.empty()) {
11358 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011359 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011360 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011361 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011362 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011363 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011364 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011365 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011366 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011367 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011368 }
Richard Smitha62d1982018-08-03 01:00:01 +000011369
11370 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11371 PendingDeducedTypeUpdates.clear();
11372 for (auto Update : DTUpdates) {
11373 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11374 // FIXME: If the return type is already deduced, check that it matches.
11375 getContext().adjustDeducedFunctionResultType(Update.first,
11376 Update.second);
11377 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011378 }
11379
Richard Smithce18a182015-07-14 00:26:00 +000011380 if (ReadTimer)
11381 ReadTimer->stopTimer();
11382
Richard Smith0f4e2c42015-08-06 04:23:48 +000011383 diagnoseOdrViolations();
11384
Richard Smith04d05b52014-03-23 00:27:18 +000011385 // We are not in recursive loading, so it's safe to pass the "interesting"
11386 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011387 if (Consumer)
11388 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011389 }
11390}
11391
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011392void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011393 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11394 // Remove any fake results before adding any real ones.
11395 auto It = PendingFakeLookupResults.find(II);
11396 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011397 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011398 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011399 // FIXME: this works around module+PCH performance issue.
11400 // Rather than erase the result from the map, which is O(n), just clear
11401 // the vector of NamedDecls.
11402 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011403 }
11404 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011405
11406 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11407 SemaObj->TUScope->AddDecl(D);
11408 } else if (SemaObj->TUScope) {
11409 // Adding the decl to IdResolver may have failed because it was already in
11410 // (even though it was not added in scope). If it is already in, make sure
11411 // it gets in the scope as well.
11412 if (std::find(SemaObj->IdResolver.begin(Name),
11413 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11414 SemaObj->TUScope->AddDecl(D);
11415 }
11416}
11417
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011418ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11419 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011420 const PCHContainerReader &PCHContainerRdr,
11421 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11422 StringRef isysroot, bool DisableValidation,
11423 bool AllowASTWithCompilerErrors,
11424 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011425 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000011426 std::unique_ptr<llvm::Timer> ReadTimer)
11427 : Listener(DisableValidation
11428 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11429 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011430 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011431 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011432 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11433 PCHContainerRdr, PP.getHeaderSearchInfo()),
11434 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011435 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011436 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11437 AllowConfigurationMismatch(AllowConfigurationMismatch),
11438 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011439 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011440 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011441 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011442
11443 for (const auto &Ext : Extensions) {
11444 auto BlockName = Ext->getExtensionMetadata().BlockName;
11445 auto Known = ModuleFileExtensions.find(BlockName);
11446 if (Known != ModuleFileExtensions.end()) {
11447 Diags.Report(diag::warn_duplicate_module_file_extension)
11448 << BlockName;
11449 continue;
11450 }
11451
11452 ModuleFileExtensions.insert({BlockName, Ext});
11453 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011454}
11455
11456ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011457 if (OwnsDeserializationListener)
11458 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011459}
Richard Smith10379092016-05-06 23:14:07 +000011460
11461IdentifierResolver &ASTReader::getIdResolver() {
11462 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11463}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011464
JF Bastien0e828952019-06-26 19:50:12 +000011465Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11466 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000011467 Idx = 0;
11468 Record.clear();
11469 return Cursor.readRecord(AbbrevID, Record);
11470}
Kelvin Libe286f52018-09-15 13:54:15 +000011471//===----------------------------------------------------------------------===//
11472//// OMPClauseReader implementation
11473////===----------------------------------------------------------------------===//
11474
John McCallc2f18312019-12-14 03:01:28 -050011475// This has to be in namespace clang because it's friended by all
11476// of the OMP clauses.
11477namespace clang {
11478
11479class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11480 ASTRecordReader &Record;
11481 ASTContext &Context;
11482
11483public:
11484 OMPClauseReader(ASTRecordReader &Record)
11485 : Record(Record), Context(Record.getContext()) {}
11486
11487#define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *C);
11488#include "clang/Basic/OpenMPKinds.def"
11489 OMPClause *readClause();
11490 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11491 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11492};
11493
11494} // end namespace clang
11495
11496OMPClause *ASTRecordReader::readOMPClause() {
11497 return OMPClauseReader(*this).readClause();
11498}
11499
Kelvin Libe286f52018-09-15 13:54:15 +000011500OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011501 OMPClause *C = nullptr;
Kelvin Libe286f52018-09-15 13:54:15 +000011502 switch (Record.readInt()) {
11503 case OMPC_if:
11504 C = new (Context) OMPIfClause();
11505 break;
11506 case OMPC_final:
11507 C = new (Context) OMPFinalClause();
11508 break;
11509 case OMPC_num_threads:
11510 C = new (Context) OMPNumThreadsClause();
11511 break;
11512 case OMPC_safelen:
11513 C = new (Context) OMPSafelenClause();
11514 break;
11515 case OMPC_simdlen:
11516 C = new (Context) OMPSimdlenClause();
11517 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011518 case OMPC_allocator:
11519 C = new (Context) OMPAllocatorClause();
11520 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011521 case OMPC_collapse:
11522 C = new (Context) OMPCollapseClause();
11523 break;
11524 case OMPC_default:
11525 C = new (Context) OMPDefaultClause();
11526 break;
11527 case OMPC_proc_bind:
11528 C = new (Context) OMPProcBindClause();
11529 break;
11530 case OMPC_schedule:
11531 C = new (Context) OMPScheduleClause();
11532 break;
11533 case OMPC_ordered:
11534 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11535 break;
11536 case OMPC_nowait:
11537 C = new (Context) OMPNowaitClause();
11538 break;
11539 case OMPC_untied:
11540 C = new (Context) OMPUntiedClause();
11541 break;
11542 case OMPC_mergeable:
11543 C = new (Context) OMPMergeableClause();
11544 break;
11545 case OMPC_read:
11546 C = new (Context) OMPReadClause();
11547 break;
11548 case OMPC_write:
11549 C = new (Context) OMPWriteClause();
11550 break;
11551 case OMPC_update:
11552 C = new (Context) OMPUpdateClause();
11553 break;
11554 case OMPC_capture:
11555 C = new (Context) OMPCaptureClause();
11556 break;
11557 case OMPC_seq_cst:
11558 C = new (Context) OMPSeqCstClause();
11559 break;
11560 case OMPC_threads:
11561 C = new (Context) OMPThreadsClause();
11562 break;
11563 case OMPC_simd:
11564 C = new (Context) OMPSIMDClause();
11565 break;
11566 case OMPC_nogroup:
11567 C = new (Context) OMPNogroupClause();
11568 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011569 case OMPC_unified_address:
11570 C = new (Context) OMPUnifiedAddressClause();
11571 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011572 case OMPC_unified_shared_memory:
11573 C = new (Context) OMPUnifiedSharedMemoryClause();
11574 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011575 case OMPC_reverse_offload:
11576 C = new (Context) OMPReverseOffloadClause();
11577 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011578 case OMPC_dynamic_allocators:
11579 C = new (Context) OMPDynamicAllocatorsClause();
11580 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011581 case OMPC_atomic_default_mem_order:
11582 C = new (Context) OMPAtomicDefaultMemOrderClause();
11583 break;
11584 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011585 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11586 break;
11587 case OMPC_firstprivate:
11588 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11589 break;
11590 case OMPC_lastprivate:
11591 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11592 break;
11593 case OMPC_shared:
11594 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11595 break;
11596 case OMPC_reduction:
11597 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11598 break;
11599 case OMPC_task_reduction:
11600 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11601 break;
11602 case OMPC_in_reduction:
11603 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11604 break;
11605 case OMPC_linear:
11606 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11607 break;
11608 case OMPC_aligned:
11609 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11610 break;
11611 case OMPC_copyin:
11612 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11613 break;
11614 case OMPC_copyprivate:
11615 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11616 break;
11617 case OMPC_flush:
11618 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11619 break;
11620 case OMPC_depend: {
11621 unsigned NumVars = Record.readInt();
11622 unsigned NumLoops = Record.readInt();
11623 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11624 break;
11625 }
11626 case OMPC_device:
11627 C = new (Context) OMPDeviceClause();
11628 break;
11629 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011630 OMPMappableExprListSizeTy Sizes;
11631 Sizes.NumVars = Record.readInt();
11632 Sizes.NumUniqueDeclarations = Record.readInt();
11633 Sizes.NumComponentLists = Record.readInt();
11634 Sizes.NumComponents = Record.readInt();
11635 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011636 break;
11637 }
11638 case OMPC_num_teams:
11639 C = new (Context) OMPNumTeamsClause();
11640 break;
11641 case OMPC_thread_limit:
11642 C = new (Context) OMPThreadLimitClause();
11643 break;
11644 case OMPC_priority:
11645 C = new (Context) OMPPriorityClause();
11646 break;
11647 case OMPC_grainsize:
11648 C = new (Context) OMPGrainsizeClause();
11649 break;
11650 case OMPC_num_tasks:
11651 C = new (Context) OMPNumTasksClause();
11652 break;
11653 case OMPC_hint:
11654 C = new (Context) OMPHintClause();
11655 break;
11656 case OMPC_dist_schedule:
11657 C = new (Context) OMPDistScheduleClause();
11658 break;
11659 case OMPC_defaultmap:
11660 C = new (Context) OMPDefaultmapClause();
11661 break;
11662 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011663 OMPMappableExprListSizeTy Sizes;
11664 Sizes.NumVars = Record.readInt();
11665 Sizes.NumUniqueDeclarations = Record.readInt();
11666 Sizes.NumComponentLists = Record.readInt();
11667 Sizes.NumComponents = Record.readInt();
11668 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011669 break;
11670 }
11671 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011672 OMPMappableExprListSizeTy Sizes;
11673 Sizes.NumVars = Record.readInt();
11674 Sizes.NumUniqueDeclarations = Record.readInt();
11675 Sizes.NumComponentLists = Record.readInt();
11676 Sizes.NumComponents = Record.readInt();
11677 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011678 break;
11679 }
11680 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011681 OMPMappableExprListSizeTy Sizes;
11682 Sizes.NumVars = Record.readInt();
11683 Sizes.NumUniqueDeclarations = Record.readInt();
11684 Sizes.NumComponentLists = Record.readInt();
11685 Sizes.NumComponents = Record.readInt();
11686 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011687 break;
11688 }
11689 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011690 OMPMappableExprListSizeTy Sizes;
11691 Sizes.NumVars = Record.readInt();
11692 Sizes.NumUniqueDeclarations = Record.readInt();
11693 Sizes.NumComponentLists = Record.readInt();
11694 Sizes.NumComponents = Record.readInt();
11695 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011696 break;
11697 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000011698 case OMPC_allocate:
11699 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11700 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050011701 case OMPC_nontemporal:
11702 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11703 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011704 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011705 assert(C && "Unknown OMPClause type");
11706
Kelvin Libe286f52018-09-15 13:54:15 +000011707 Visit(C);
11708 C->setLocStart(Record.readSourceLocation());
11709 C->setLocEnd(Record.readSourceLocation());
11710
11711 return C;
11712}
11713
11714void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11715 C->setPreInitStmt(Record.readSubStmt(),
11716 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11717}
11718
11719void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11720 VisitOMPClauseWithPreInit(C);
11721 C->setPostUpdateExpr(Record.readSubExpr());
11722}
11723
11724void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11725 VisitOMPClauseWithPreInit(C);
11726 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11727 C->setNameModifierLoc(Record.readSourceLocation());
11728 C->setColonLoc(Record.readSourceLocation());
11729 C->setCondition(Record.readSubExpr());
11730 C->setLParenLoc(Record.readSourceLocation());
11731}
11732
11733void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011734 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000011735 C->setCondition(Record.readSubExpr());
11736 C->setLParenLoc(Record.readSourceLocation());
11737}
11738
11739void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11740 VisitOMPClauseWithPreInit(C);
11741 C->setNumThreads(Record.readSubExpr());
11742 C->setLParenLoc(Record.readSourceLocation());
11743}
11744
11745void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11746 C->setSafelen(Record.readSubExpr());
11747 C->setLParenLoc(Record.readSourceLocation());
11748}
11749
11750void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11751 C->setSimdlen(Record.readSubExpr());
11752 C->setLParenLoc(Record.readSourceLocation());
11753}
11754
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011755void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11756 C->setAllocator(Record.readExpr());
11757 C->setLParenLoc(Record.readSourceLocation());
11758}
11759
Kelvin Libe286f52018-09-15 13:54:15 +000011760void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11761 C->setNumForLoops(Record.readSubExpr());
11762 C->setLParenLoc(Record.readSourceLocation());
11763}
11764
11765void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11766 C->setDefaultKind(
11767 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11768 C->setLParenLoc(Record.readSourceLocation());
11769 C->setDefaultKindKwLoc(Record.readSourceLocation());
11770}
11771
11772void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11773 C->setProcBindKind(
11774 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
11775 C->setLParenLoc(Record.readSourceLocation());
11776 C->setProcBindKindKwLoc(Record.readSourceLocation());
11777}
11778
11779void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11780 VisitOMPClauseWithPreInit(C);
11781 C->setScheduleKind(
11782 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11783 C->setFirstScheduleModifier(
11784 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11785 C->setSecondScheduleModifier(
11786 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11787 C->setChunkSize(Record.readSubExpr());
11788 C->setLParenLoc(Record.readSourceLocation());
11789 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11790 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11791 C->setScheduleKindLoc(Record.readSourceLocation());
11792 C->setCommaLoc(Record.readSourceLocation());
11793}
11794
11795void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11796 C->setNumForLoops(Record.readSubExpr());
11797 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11798 C->setLoopNumIterations(I, Record.readSubExpr());
11799 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11800 C->setLoopCounter(I, Record.readSubExpr());
11801 C->setLParenLoc(Record.readSourceLocation());
11802}
11803
11804void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11805
11806void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11807
11808void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11809
11810void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11811
11812void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11813
11814void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11815
11816void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11817
11818void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11819
11820void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11821
11822void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11823
11824void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11825
Kelvin Li1408f912018-09-26 04:28:39 +000011826void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11827
Patrick Lyster4a370b92018-10-01 13:47:43 +000011828void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11829 OMPUnifiedSharedMemoryClause *) {}
11830
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011831void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11832
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011833void
11834OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11835}
11836
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011837void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11838 OMPAtomicDefaultMemOrderClause *C) {
11839 C->setAtomicDefaultMemOrderKind(
11840 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11841 C->setLParenLoc(Record.readSourceLocation());
11842 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11843}
11844
Kelvin Libe286f52018-09-15 13:54:15 +000011845void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11846 C->setLParenLoc(Record.readSourceLocation());
11847 unsigned NumVars = C->varlist_size();
11848 SmallVector<Expr *, 16> Vars;
11849 Vars.reserve(NumVars);
11850 for (unsigned i = 0; i != NumVars; ++i)
11851 Vars.push_back(Record.readSubExpr());
11852 C->setVarRefs(Vars);
11853 Vars.clear();
11854 for (unsigned i = 0; i != NumVars; ++i)
11855 Vars.push_back(Record.readSubExpr());
11856 C->setPrivateCopies(Vars);
11857}
11858
11859void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11860 VisitOMPClauseWithPreInit(C);
11861 C->setLParenLoc(Record.readSourceLocation());
11862 unsigned NumVars = C->varlist_size();
11863 SmallVector<Expr *, 16> Vars;
11864 Vars.reserve(NumVars);
11865 for (unsigned i = 0; i != NumVars; ++i)
11866 Vars.push_back(Record.readSubExpr());
11867 C->setVarRefs(Vars);
11868 Vars.clear();
11869 for (unsigned i = 0; i != NumVars; ++i)
11870 Vars.push_back(Record.readSubExpr());
11871 C->setPrivateCopies(Vars);
11872 Vars.clear();
11873 for (unsigned i = 0; i != NumVars; ++i)
11874 Vars.push_back(Record.readSubExpr());
11875 C->setInits(Vars);
11876}
11877
11878void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11879 VisitOMPClauseWithPostUpdate(C);
11880 C->setLParenLoc(Record.readSourceLocation());
11881 unsigned NumVars = C->varlist_size();
11882 SmallVector<Expr *, 16> Vars;
11883 Vars.reserve(NumVars);
11884 for (unsigned i = 0; i != NumVars; ++i)
11885 Vars.push_back(Record.readSubExpr());
11886 C->setVarRefs(Vars);
11887 Vars.clear();
11888 for (unsigned i = 0; i != NumVars; ++i)
11889 Vars.push_back(Record.readSubExpr());
11890 C->setPrivateCopies(Vars);
11891 Vars.clear();
11892 for (unsigned i = 0; i != NumVars; ++i)
11893 Vars.push_back(Record.readSubExpr());
11894 C->setSourceExprs(Vars);
11895 Vars.clear();
11896 for (unsigned i = 0; i != NumVars; ++i)
11897 Vars.push_back(Record.readSubExpr());
11898 C->setDestinationExprs(Vars);
11899 Vars.clear();
11900 for (unsigned i = 0; i != NumVars; ++i)
11901 Vars.push_back(Record.readSubExpr());
11902 C->setAssignmentOps(Vars);
11903}
11904
11905void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11906 C->setLParenLoc(Record.readSourceLocation());
11907 unsigned NumVars = C->varlist_size();
11908 SmallVector<Expr *, 16> Vars;
11909 Vars.reserve(NumVars);
11910 for (unsigned i = 0; i != NumVars; ++i)
11911 Vars.push_back(Record.readSubExpr());
11912 C->setVarRefs(Vars);
11913}
11914
11915void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11916 VisitOMPClauseWithPostUpdate(C);
11917 C->setLParenLoc(Record.readSourceLocation());
11918 C->setColonLoc(Record.readSourceLocation());
11919 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050011920 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000011921 C->setQualifierLoc(NNSL);
11922 C->setNameInfo(DNI);
11923
11924 unsigned NumVars = C->varlist_size();
11925 SmallVector<Expr *, 16> Vars;
11926 Vars.reserve(NumVars);
11927 for (unsigned i = 0; i != NumVars; ++i)
11928 Vars.push_back(Record.readSubExpr());
11929 C->setVarRefs(Vars);
11930 Vars.clear();
11931 for (unsigned i = 0; i != NumVars; ++i)
11932 Vars.push_back(Record.readSubExpr());
11933 C->setPrivates(Vars);
11934 Vars.clear();
11935 for (unsigned i = 0; i != NumVars; ++i)
11936 Vars.push_back(Record.readSubExpr());
11937 C->setLHSExprs(Vars);
11938 Vars.clear();
11939 for (unsigned i = 0; i != NumVars; ++i)
11940 Vars.push_back(Record.readSubExpr());
11941 C->setRHSExprs(Vars);
11942 Vars.clear();
11943 for (unsigned i = 0; i != NumVars; ++i)
11944 Vars.push_back(Record.readSubExpr());
11945 C->setReductionOps(Vars);
11946}
11947
11948void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11949 VisitOMPClauseWithPostUpdate(C);
11950 C->setLParenLoc(Record.readSourceLocation());
11951 C->setColonLoc(Record.readSourceLocation());
11952 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050011953 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000011954 C->setQualifierLoc(NNSL);
11955 C->setNameInfo(DNI);
11956
11957 unsigned NumVars = C->varlist_size();
11958 SmallVector<Expr *, 16> Vars;
11959 Vars.reserve(NumVars);
11960 for (unsigned I = 0; I != NumVars; ++I)
11961 Vars.push_back(Record.readSubExpr());
11962 C->setVarRefs(Vars);
11963 Vars.clear();
11964 for (unsigned I = 0; I != NumVars; ++I)
11965 Vars.push_back(Record.readSubExpr());
11966 C->setPrivates(Vars);
11967 Vars.clear();
11968 for (unsigned I = 0; I != NumVars; ++I)
11969 Vars.push_back(Record.readSubExpr());
11970 C->setLHSExprs(Vars);
11971 Vars.clear();
11972 for (unsigned I = 0; I != NumVars; ++I)
11973 Vars.push_back(Record.readSubExpr());
11974 C->setRHSExprs(Vars);
11975 Vars.clear();
11976 for (unsigned I = 0; I != NumVars; ++I)
11977 Vars.push_back(Record.readSubExpr());
11978 C->setReductionOps(Vars);
11979}
11980
11981void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11982 VisitOMPClauseWithPostUpdate(C);
11983 C->setLParenLoc(Record.readSourceLocation());
11984 C->setColonLoc(Record.readSourceLocation());
11985 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050011986 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000011987 C->setQualifierLoc(NNSL);
11988 C->setNameInfo(DNI);
11989
11990 unsigned NumVars = C->varlist_size();
11991 SmallVector<Expr *, 16> Vars;
11992 Vars.reserve(NumVars);
11993 for (unsigned I = 0; I != NumVars; ++I)
11994 Vars.push_back(Record.readSubExpr());
11995 C->setVarRefs(Vars);
11996 Vars.clear();
11997 for (unsigned I = 0; I != NumVars; ++I)
11998 Vars.push_back(Record.readSubExpr());
11999 C->setPrivates(Vars);
12000 Vars.clear();
12001 for (unsigned I = 0; I != NumVars; ++I)
12002 Vars.push_back(Record.readSubExpr());
12003 C->setLHSExprs(Vars);
12004 Vars.clear();
12005 for (unsigned I = 0; I != NumVars; ++I)
12006 Vars.push_back(Record.readSubExpr());
12007 C->setRHSExprs(Vars);
12008 Vars.clear();
12009 for (unsigned I = 0; I != NumVars; ++I)
12010 Vars.push_back(Record.readSubExpr());
12011 C->setReductionOps(Vars);
12012 Vars.clear();
12013 for (unsigned I = 0; I != NumVars; ++I)
12014 Vars.push_back(Record.readSubExpr());
12015 C->setTaskgroupDescriptors(Vars);
12016}
12017
12018void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12019 VisitOMPClauseWithPostUpdate(C);
12020 C->setLParenLoc(Record.readSourceLocation());
12021 C->setColonLoc(Record.readSourceLocation());
12022 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12023 C->setModifierLoc(Record.readSourceLocation());
12024 unsigned NumVars = C->varlist_size();
12025 SmallVector<Expr *, 16> Vars;
12026 Vars.reserve(NumVars);
12027 for (unsigned i = 0; i != NumVars; ++i)
12028 Vars.push_back(Record.readSubExpr());
12029 C->setVarRefs(Vars);
12030 Vars.clear();
12031 for (unsigned i = 0; i != NumVars; ++i)
12032 Vars.push_back(Record.readSubExpr());
12033 C->setPrivates(Vars);
12034 Vars.clear();
12035 for (unsigned i = 0; i != NumVars; ++i)
12036 Vars.push_back(Record.readSubExpr());
12037 C->setInits(Vars);
12038 Vars.clear();
12039 for (unsigned i = 0; i != NumVars; ++i)
12040 Vars.push_back(Record.readSubExpr());
12041 C->setUpdates(Vars);
12042 Vars.clear();
12043 for (unsigned i = 0; i != NumVars; ++i)
12044 Vars.push_back(Record.readSubExpr());
12045 C->setFinals(Vars);
12046 C->setStep(Record.readSubExpr());
12047 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012048 Vars.clear();
12049 for (unsigned I = 0; I != NumVars + 1; ++I)
12050 Vars.push_back(Record.readSubExpr());
12051 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012052}
12053
12054void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12055 C->setLParenLoc(Record.readSourceLocation());
12056 C->setColonLoc(Record.readSourceLocation());
12057 unsigned NumVars = C->varlist_size();
12058 SmallVector<Expr *, 16> Vars;
12059 Vars.reserve(NumVars);
12060 for (unsigned i = 0; i != NumVars; ++i)
12061 Vars.push_back(Record.readSubExpr());
12062 C->setVarRefs(Vars);
12063 C->setAlignment(Record.readSubExpr());
12064}
12065
12066void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12067 C->setLParenLoc(Record.readSourceLocation());
12068 unsigned NumVars = C->varlist_size();
12069 SmallVector<Expr *, 16> Exprs;
12070 Exprs.reserve(NumVars);
12071 for (unsigned i = 0; i != NumVars; ++i)
12072 Exprs.push_back(Record.readSubExpr());
12073 C->setVarRefs(Exprs);
12074 Exprs.clear();
12075 for (unsigned i = 0; i != NumVars; ++i)
12076 Exprs.push_back(Record.readSubExpr());
12077 C->setSourceExprs(Exprs);
12078 Exprs.clear();
12079 for (unsigned i = 0; i != NumVars; ++i)
12080 Exprs.push_back(Record.readSubExpr());
12081 C->setDestinationExprs(Exprs);
12082 Exprs.clear();
12083 for (unsigned i = 0; i != NumVars; ++i)
12084 Exprs.push_back(Record.readSubExpr());
12085 C->setAssignmentOps(Exprs);
12086}
12087
12088void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12089 C->setLParenLoc(Record.readSourceLocation());
12090 unsigned NumVars = C->varlist_size();
12091 SmallVector<Expr *, 16> Exprs;
12092 Exprs.reserve(NumVars);
12093 for (unsigned i = 0; i != NumVars; ++i)
12094 Exprs.push_back(Record.readSubExpr());
12095 C->setVarRefs(Exprs);
12096 Exprs.clear();
12097 for (unsigned i = 0; i != NumVars; ++i)
12098 Exprs.push_back(Record.readSubExpr());
12099 C->setSourceExprs(Exprs);
12100 Exprs.clear();
12101 for (unsigned i = 0; i != NumVars; ++i)
12102 Exprs.push_back(Record.readSubExpr());
12103 C->setDestinationExprs(Exprs);
12104 Exprs.clear();
12105 for (unsigned i = 0; i != NumVars; ++i)
12106 Exprs.push_back(Record.readSubExpr());
12107 C->setAssignmentOps(Exprs);
12108}
12109
12110void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12111 C->setLParenLoc(Record.readSourceLocation());
12112 unsigned NumVars = C->varlist_size();
12113 SmallVector<Expr *, 16> Vars;
12114 Vars.reserve(NumVars);
12115 for (unsigned i = 0; i != NumVars; ++i)
12116 Vars.push_back(Record.readSubExpr());
12117 C->setVarRefs(Vars);
12118}
12119
12120void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12121 C->setLParenLoc(Record.readSourceLocation());
12122 C->setDependencyKind(
12123 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12124 C->setDependencyLoc(Record.readSourceLocation());
12125 C->setColonLoc(Record.readSourceLocation());
12126 unsigned NumVars = C->varlist_size();
12127 SmallVector<Expr *, 16> Vars;
12128 Vars.reserve(NumVars);
12129 for (unsigned I = 0; I != NumVars; ++I)
12130 Vars.push_back(Record.readSubExpr());
12131 C->setVarRefs(Vars);
12132 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12133 C->setLoopData(I, Record.readSubExpr());
12134}
12135
12136void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12137 VisitOMPClauseWithPreInit(C);
12138 C->setDevice(Record.readSubExpr());
12139 C->setLParenLoc(Record.readSourceLocation());
12140}
12141
12142void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12143 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012144 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12145 C->setMapTypeModifier(
12146 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12147 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12148 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012149 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012150 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012151 C->setMapType(
12152 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12153 C->setMapLoc(Record.readSourceLocation());
12154 C->setColonLoc(Record.readSourceLocation());
12155 auto NumVars = C->varlist_size();
12156 auto UniqueDecls = C->getUniqueDeclarationsNum();
12157 auto TotalLists = C->getTotalComponentListNum();
12158 auto TotalComponents = C->getTotalComponentsNum();
12159
12160 SmallVector<Expr *, 16> Vars;
12161 Vars.reserve(NumVars);
12162 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012163 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012164 C->setVarRefs(Vars);
12165
Michael Kruse4304e9d2019-02-19 16:38:20 +000012166 SmallVector<Expr *, 16> UDMappers;
12167 UDMappers.reserve(NumVars);
12168 for (unsigned I = 0; I < NumVars; ++I)
12169 UDMappers.push_back(Record.readExpr());
12170 C->setUDMapperRefs(UDMappers);
12171
Kelvin Libe286f52018-09-15 13:54:15 +000012172 SmallVector<ValueDecl *, 16> Decls;
12173 Decls.reserve(UniqueDecls);
12174 for (unsigned i = 0; i < UniqueDecls; ++i)
12175 Decls.push_back(Record.readDeclAs<ValueDecl>());
12176 C->setUniqueDecls(Decls);
12177
12178 SmallVector<unsigned, 16> ListsPerDecl;
12179 ListsPerDecl.reserve(UniqueDecls);
12180 for (unsigned i = 0; i < UniqueDecls; ++i)
12181 ListsPerDecl.push_back(Record.readInt());
12182 C->setDeclNumLists(ListsPerDecl);
12183
12184 SmallVector<unsigned, 32> ListSizes;
12185 ListSizes.reserve(TotalLists);
12186 for (unsigned i = 0; i < TotalLists; ++i)
12187 ListSizes.push_back(Record.readInt());
12188 C->setComponentListSizes(ListSizes);
12189
12190 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12191 Components.reserve(TotalComponents);
12192 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012193 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012194 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12195 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12196 AssociatedExpr, AssociatedDecl));
12197 }
12198 C->setComponents(Components, ListSizes);
12199}
12200
Alexey Bataeve04483e2019-03-27 14:14:31 +000012201void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12202 C->setLParenLoc(Record.readSourceLocation());
12203 C->setColonLoc(Record.readSourceLocation());
12204 C->setAllocator(Record.readSubExpr());
12205 unsigned NumVars = C->varlist_size();
12206 SmallVector<Expr *, 16> Vars;
12207 Vars.reserve(NumVars);
12208 for (unsigned i = 0; i != NumVars; ++i)
12209 Vars.push_back(Record.readSubExpr());
12210 C->setVarRefs(Vars);
12211}
12212
Kelvin Libe286f52018-09-15 13:54:15 +000012213void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12214 VisitOMPClauseWithPreInit(C);
12215 C->setNumTeams(Record.readSubExpr());
12216 C->setLParenLoc(Record.readSourceLocation());
12217}
12218
12219void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12220 VisitOMPClauseWithPreInit(C);
12221 C->setThreadLimit(Record.readSubExpr());
12222 C->setLParenLoc(Record.readSourceLocation());
12223}
12224
12225void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +000012226 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012227 C->setPriority(Record.readSubExpr());
12228 C->setLParenLoc(Record.readSourceLocation());
12229}
12230
12231void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000012232 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012233 C->setGrainsize(Record.readSubExpr());
12234 C->setLParenLoc(Record.readSourceLocation());
12235}
12236
12237void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000012238 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012239 C->setNumTasks(Record.readSubExpr());
12240 C->setLParenLoc(Record.readSourceLocation());
12241}
12242
12243void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12244 C->setHint(Record.readSubExpr());
12245 C->setLParenLoc(Record.readSourceLocation());
12246}
12247
12248void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12249 VisitOMPClauseWithPreInit(C);
12250 C->setDistScheduleKind(
12251 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12252 C->setChunkSize(Record.readSubExpr());
12253 C->setLParenLoc(Record.readSourceLocation());
12254 C->setDistScheduleKindLoc(Record.readSourceLocation());
12255 C->setCommaLoc(Record.readSourceLocation());
12256}
12257
12258void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12259 C->setDefaultmapKind(
12260 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12261 C->setDefaultmapModifier(
12262 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12263 C->setLParenLoc(Record.readSourceLocation());
12264 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12265 C->setDefaultmapKindLoc(Record.readSourceLocation());
12266}
12267
12268void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12269 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012270 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012271 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012272 auto NumVars = C->varlist_size();
12273 auto UniqueDecls = C->getUniqueDeclarationsNum();
12274 auto TotalLists = C->getTotalComponentListNum();
12275 auto TotalComponents = C->getTotalComponentsNum();
12276
12277 SmallVector<Expr *, 16> Vars;
12278 Vars.reserve(NumVars);
12279 for (unsigned i = 0; i != NumVars; ++i)
12280 Vars.push_back(Record.readSubExpr());
12281 C->setVarRefs(Vars);
12282
Michael Kruse01f670d2019-02-22 22:29:42 +000012283 SmallVector<Expr *, 16> UDMappers;
12284 UDMappers.reserve(NumVars);
12285 for (unsigned I = 0; I < NumVars; ++I)
12286 UDMappers.push_back(Record.readSubExpr());
12287 C->setUDMapperRefs(UDMappers);
12288
Kelvin Libe286f52018-09-15 13:54:15 +000012289 SmallVector<ValueDecl *, 16> Decls;
12290 Decls.reserve(UniqueDecls);
12291 for (unsigned i = 0; i < UniqueDecls; ++i)
12292 Decls.push_back(Record.readDeclAs<ValueDecl>());
12293 C->setUniqueDecls(Decls);
12294
12295 SmallVector<unsigned, 16> ListsPerDecl;
12296 ListsPerDecl.reserve(UniqueDecls);
12297 for (unsigned i = 0; i < UniqueDecls; ++i)
12298 ListsPerDecl.push_back(Record.readInt());
12299 C->setDeclNumLists(ListsPerDecl);
12300
12301 SmallVector<unsigned, 32> ListSizes;
12302 ListSizes.reserve(TotalLists);
12303 for (unsigned i = 0; i < TotalLists; ++i)
12304 ListSizes.push_back(Record.readInt());
12305 C->setComponentListSizes(ListSizes);
12306
12307 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12308 Components.reserve(TotalComponents);
12309 for (unsigned i = 0; i < TotalComponents; ++i) {
12310 Expr *AssociatedExpr = Record.readSubExpr();
12311 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12312 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12313 AssociatedExpr, AssociatedDecl));
12314 }
12315 C->setComponents(Components, ListSizes);
12316}
12317
12318void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12319 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012320 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012321 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012322 auto NumVars = C->varlist_size();
12323 auto UniqueDecls = C->getUniqueDeclarationsNum();
12324 auto TotalLists = C->getTotalComponentListNum();
12325 auto TotalComponents = C->getTotalComponentsNum();
12326
12327 SmallVector<Expr *, 16> Vars;
12328 Vars.reserve(NumVars);
12329 for (unsigned i = 0; i != NumVars; ++i)
12330 Vars.push_back(Record.readSubExpr());
12331 C->setVarRefs(Vars);
12332
Michael Kruse0336c752019-02-25 20:34:15 +000012333 SmallVector<Expr *, 16> UDMappers;
12334 UDMappers.reserve(NumVars);
12335 for (unsigned I = 0; I < NumVars; ++I)
12336 UDMappers.push_back(Record.readSubExpr());
12337 C->setUDMapperRefs(UDMappers);
12338
Kelvin Libe286f52018-09-15 13:54:15 +000012339 SmallVector<ValueDecl *, 16> Decls;
12340 Decls.reserve(UniqueDecls);
12341 for (unsigned i = 0; i < UniqueDecls; ++i)
12342 Decls.push_back(Record.readDeclAs<ValueDecl>());
12343 C->setUniqueDecls(Decls);
12344
12345 SmallVector<unsigned, 16> ListsPerDecl;
12346 ListsPerDecl.reserve(UniqueDecls);
12347 for (unsigned i = 0; i < UniqueDecls; ++i)
12348 ListsPerDecl.push_back(Record.readInt());
12349 C->setDeclNumLists(ListsPerDecl);
12350
12351 SmallVector<unsigned, 32> ListSizes;
12352 ListSizes.reserve(TotalLists);
12353 for (unsigned i = 0; i < TotalLists; ++i)
12354 ListSizes.push_back(Record.readInt());
12355 C->setComponentListSizes(ListSizes);
12356
12357 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12358 Components.reserve(TotalComponents);
12359 for (unsigned i = 0; i < TotalComponents; ++i) {
12360 Expr *AssociatedExpr = Record.readSubExpr();
12361 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12362 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12363 AssociatedExpr, AssociatedDecl));
12364 }
12365 C->setComponents(Components, ListSizes);
12366}
12367
12368void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12369 C->setLParenLoc(Record.readSourceLocation());
12370 auto NumVars = C->varlist_size();
12371 auto UniqueDecls = C->getUniqueDeclarationsNum();
12372 auto TotalLists = C->getTotalComponentListNum();
12373 auto TotalComponents = C->getTotalComponentsNum();
12374
12375 SmallVector<Expr *, 16> Vars;
12376 Vars.reserve(NumVars);
12377 for (unsigned i = 0; i != NumVars; ++i)
12378 Vars.push_back(Record.readSubExpr());
12379 C->setVarRefs(Vars);
12380 Vars.clear();
12381 for (unsigned i = 0; i != NumVars; ++i)
12382 Vars.push_back(Record.readSubExpr());
12383 C->setPrivateCopies(Vars);
12384 Vars.clear();
12385 for (unsigned i = 0; i != NumVars; ++i)
12386 Vars.push_back(Record.readSubExpr());
12387 C->setInits(Vars);
12388
12389 SmallVector<ValueDecl *, 16> Decls;
12390 Decls.reserve(UniqueDecls);
12391 for (unsigned i = 0; i < UniqueDecls; ++i)
12392 Decls.push_back(Record.readDeclAs<ValueDecl>());
12393 C->setUniqueDecls(Decls);
12394
12395 SmallVector<unsigned, 16> ListsPerDecl;
12396 ListsPerDecl.reserve(UniqueDecls);
12397 for (unsigned i = 0; i < UniqueDecls; ++i)
12398 ListsPerDecl.push_back(Record.readInt());
12399 C->setDeclNumLists(ListsPerDecl);
12400
12401 SmallVector<unsigned, 32> ListSizes;
12402 ListSizes.reserve(TotalLists);
12403 for (unsigned i = 0; i < TotalLists; ++i)
12404 ListSizes.push_back(Record.readInt());
12405 C->setComponentListSizes(ListSizes);
12406
12407 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12408 Components.reserve(TotalComponents);
12409 for (unsigned i = 0; i < TotalComponents; ++i) {
12410 Expr *AssociatedExpr = Record.readSubExpr();
12411 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12412 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12413 AssociatedExpr, AssociatedDecl));
12414 }
12415 C->setComponents(Components, ListSizes);
12416}
12417
12418void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12419 C->setLParenLoc(Record.readSourceLocation());
12420 auto NumVars = C->varlist_size();
12421 auto UniqueDecls = C->getUniqueDeclarationsNum();
12422 auto TotalLists = C->getTotalComponentListNum();
12423 auto TotalComponents = C->getTotalComponentsNum();
12424
12425 SmallVector<Expr *, 16> Vars;
12426 Vars.reserve(NumVars);
12427 for (unsigned i = 0; i != NumVars; ++i)
12428 Vars.push_back(Record.readSubExpr());
12429 C->setVarRefs(Vars);
12430 Vars.clear();
12431
12432 SmallVector<ValueDecl *, 16> Decls;
12433 Decls.reserve(UniqueDecls);
12434 for (unsigned i = 0; i < UniqueDecls; ++i)
12435 Decls.push_back(Record.readDeclAs<ValueDecl>());
12436 C->setUniqueDecls(Decls);
12437
12438 SmallVector<unsigned, 16> ListsPerDecl;
12439 ListsPerDecl.reserve(UniqueDecls);
12440 for (unsigned i = 0; i < UniqueDecls; ++i)
12441 ListsPerDecl.push_back(Record.readInt());
12442 C->setDeclNumLists(ListsPerDecl);
12443
12444 SmallVector<unsigned, 32> ListSizes;
12445 ListSizes.reserve(TotalLists);
12446 for (unsigned i = 0; i < TotalLists; ++i)
12447 ListSizes.push_back(Record.readInt());
12448 C->setComponentListSizes(ListSizes);
12449
12450 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12451 Components.reserve(TotalComponents);
12452 for (unsigned i = 0; i < TotalComponents; ++i) {
12453 Expr *AssociatedExpr = Record.readSubExpr();
12454 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12455 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12456 AssociatedExpr, AssociatedDecl));
12457 }
12458 C->setComponents(Components, ListSizes);
12459}
Alexey Bataevb6e70842019-12-16 15:54:17 -050012460
12461void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12462 C->setLParenLoc(Record.readSourceLocation());
12463 unsigned NumVars = C->varlist_size();
12464 SmallVector<Expr *, 16> Vars;
12465 Vars.reserve(NumVars);
12466 for (unsigned i = 0; i != NumVars; ++i)
12467 Vars.push_back(Record.readSubExpr());
12468 C->setVarRefs(Vars);
12469}