blob: f7e3805fd04c7634658a5e00ad78bf1cf02028ed [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
13#include "clang/Serialization/ASTReader.h"
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000018#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTUnresolvedSet.h"
20#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000021#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000023#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclGroup.h"
25#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000027#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000030#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000032#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000037#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000039#include "clang/AST/UnresolvedSet.h"
40#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000041#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000042#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000043#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000046#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000049#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Basic/ObjCRuntime.h"
51#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000052#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Basic/SourceManager.h"
56#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000057#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include "clang/Basic/TargetInfo.h"
59#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000062#include "clang/Lex/HeaderSearch.h"
63#include "clang/Lex/HeaderSearchOptions.h"
64#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000066#include "clang/Lex/PreprocessingRecord.h"
67#include "clang/Lex/Preprocessor.h"
68#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000069#include "clang/Lex/Token.h"
70#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000071#include "clang/Sema/Scope.h"
72#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000074#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000076#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000077#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000078#include "clang/Serialization/InMemoryModuleCache.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/Module.h"
80#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000081#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000082#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include "llvm/ADT/APFloat.h"
85#include "llvm/ADT/APInt.h"
86#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000087#include "llvm/ADT/ArrayRef.h"
88#include "llvm/ADT/DenseMap.h"
89#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000090#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000091#include "llvm/ADT/IntrusiveRefCntPtr.h"
92#include "llvm/ADT/None.h"
93#include "llvm/ADT/Optional.h"
94#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000095#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000096#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000098#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +000099#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/StringMap.h"
101#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000103#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000104#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000105#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000106#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000107#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000108#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000110#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000111#include "llvm/Support/ErrorHandling.h"
112#include "llvm/Support/FileSystem.h"
113#include "llvm/Support/MemoryBuffer.h"
114#include "llvm/Support/Path.h"
115#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000116#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000117#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000118#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000119#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000121#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000123#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000125#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <limits>
127#include <map>
128#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000129#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000130#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000131#include <tuple>
132#include <utility>
133#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000134
135using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000136using namespace clang::serialization;
137using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000138using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000139
Ben Langmuircb69b572014-03-07 06:40:32 +0000140//===----------------------------------------------------------------------===//
141// ChainedASTReaderListener implementation
142//===----------------------------------------------------------------------===//
143
144bool
145ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
146 return First->ReadFullVersionInformation(FullVersion) ||
147 Second->ReadFullVersionInformation(FullVersion);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000150void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
151 First->ReadModuleName(ModuleName);
152 Second->ReadModuleName(ModuleName);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
156 First->ReadModuleMapFile(ModuleMapPath);
157 Second->ReadModuleMapFile(ModuleMapPath);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000160bool
161ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
162 bool Complain,
163 bool AllowCompatibleDifferences) {
164 return First->ReadLanguageOptions(LangOpts, Complain,
165 AllowCompatibleDifferences) ||
166 Second->ReadLanguageOptions(LangOpts, Complain,
167 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000169
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000170bool ChainedASTReaderListener::ReadTargetOptions(
171 const TargetOptions &TargetOpts, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadTargetOptions(TargetOpts, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadTargetOptions(TargetOpts, Complain,
176 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000177}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000178
Ben Langmuircb69b572014-03-07 06:40:32 +0000179bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000180 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000181 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
182 Second->ReadDiagnosticOptions(DiagOpts, Complain);
183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000184
Ben Langmuircb69b572014-03-07 06:40:32 +0000185bool
186ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
187 bool Complain) {
188 return First->ReadFileSystemOptions(FSOpts, Complain) ||
189 Second->ReadFileSystemOptions(FSOpts, Complain);
190}
191
192bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000193 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
194 bool Complain) {
195 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
196 Complain) ||
197 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
198 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000200
Ben Langmuircb69b572014-03-07 06:40:32 +0000201bool ChainedASTReaderListener::ReadPreprocessorOptions(
202 const PreprocessorOptions &PPOpts, bool Complain,
203 std::string &SuggestedPredefines) {
204 return First->ReadPreprocessorOptions(PPOpts, Complain,
205 SuggestedPredefines) ||
206 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
207}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000208
Ben Langmuircb69b572014-03-07 06:40:32 +0000209void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
210 unsigned Value) {
211 First->ReadCounter(M, Value);
212 Second->ReadCounter(M, Value);
213}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000214
Ben Langmuircb69b572014-03-07 06:40:32 +0000215bool ChainedASTReaderListener::needsInputFileVisitation() {
216 return First->needsInputFileVisitation() ||
217 Second->needsInputFileVisitation();
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
221 return First->needsSystemInputFileVisitation() ||
222 Second->needsSystemInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Richard Smith216a3bd2015-08-13 17:57:10 +0000225void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
226 ModuleKind Kind) {
227 First->visitModuleFile(Filename, Kind);
228 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000230
Ben Langmuircb69b572014-03-07 06:40:32 +0000231bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000232 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000233 bool isOverridden,
234 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000235 bool Continue = false;
236 if (First->needsInputFileVisitation() &&
237 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
239 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 if (Second->needsInputFileVisitation() &&
241 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000242 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
243 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000244 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000245}
246
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000247void ChainedASTReaderListener::readModuleFileExtension(
248 const ModuleFileExtensionMetadata &Metadata) {
249 First->readModuleFileExtension(Metadata);
250 Second->readModuleFileExtension(Metadata);
251}
252
Guy Benyei11169dd2012-12-18 14:30:41 +0000253//===----------------------------------------------------------------------===//
254// PCH validator implementation
255//===----------------------------------------------------------------------===//
256
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000257ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000259/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000260/// language options.
261///
262/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000263/// \param AllowCompatibleDifferences If true, differences between compatible
264/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000265///
266/// \returns true if the languagae options mis-match, false otherwise.
267static bool checkLanguageOptions(const LangOptions &LangOpts,
268 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000269 DiagnosticsEngine *Diags,
270 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#define LANGOPT(Name, Bits, Default, Description) \
272 if (ExistingLangOpts.Name != LangOpts.Name) { \
273 if (Diags) \
274 Diags->Report(diag::err_pch_langopt_mismatch) \
275 << Description << LangOpts.Name << ExistingLangOpts.Name; \
276 return true; \
277 }
278
279#define VALUE_LANGOPT(Name, Bits, Default, Description) \
280 if (ExistingLangOpts.Name != LangOpts.Name) { \
281 if (Diags) \
282 Diags->Report(diag::err_pch_langopt_value_mismatch) \
283 << Description; \
284 return true; \
285 }
286
287#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
289 if (Diags) \
290 Diags->Report(diag::err_pch_langopt_value_mismatch) \
291 << Description; \
292 return true; \
293 }
294
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000295#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
296 if (!AllowCompatibleDifferences) \
297 LANGOPT(Name, Bits, Default, Description)
298
299#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
300 if (!AllowCompatibleDifferences) \
301 ENUM_LANGOPT(Name, Bits, Default, Description)
302
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000303#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
304 if (!AllowCompatibleDifferences) \
305 VALUE_LANGOPT(Name, Bits, Default, Description)
306
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define BENIGN_LANGOPT(Name, Bits, Default, Description)
308#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000309#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310#include "clang/Basic/LangOptions.def"
311
Ben Langmuircd98cb72015-06-23 18:20:18 +0000312 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
313 if (Diags)
314 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
315 return true;
316 }
317
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
319 if (Diags)
320 Diags->Report(diag::err_pch_langopt_value_mismatch)
321 << "target Objective-C runtime";
322 return true;
323 }
324
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000325 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
326 LangOpts.CommentOpts.BlockCommandNames) {
327 if (Diags)
328 Diags->Report(diag::err_pch_langopt_value_mismatch)
329 << "block command names";
330 return true;
331 }
332
Vedant Kumar85a83c22017-06-01 20:01:01 +0000333 // Sanitizer feature mismatches are treated as compatible differences. If
334 // compatible differences aren't allowed, we still only want to check for
335 // mismatches of non-modular sanitizers (the only ones which can affect AST
336 // generation).
337 if (!AllowCompatibleDifferences) {
338 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
339 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
340 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
341 ExistingSanitizers.clear(ModularSanitizers);
342 ImportedSanitizers.clear(ModularSanitizers);
343 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
344 const std::string Flag = "-fsanitize=";
345 if (Diags) {
346#define SANITIZER(NAME, ID) \
347 { \
348 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
349 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
350 if (InExistingModule != InImportedModule) \
351 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
352 << InExistingModule << (Flag + NAME); \
353 }
354#include "clang/Basic/Sanitizers.def"
355 }
356 return true;
357 }
358 }
359
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 return false;
361}
362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000363/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000364/// target options.
365///
366/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
367///
368/// \returns true if the target options mis-match, false otherwise.
369static bool checkTargetOptions(const TargetOptions &TargetOpts,
370 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000371 DiagnosticsEngine *Diags,
372 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000373#define CHECK_TARGET_OPT(Field, Name) \
374 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
375 if (Diags) \
376 Diags->Report(diag::err_pch_targetopt_mismatch) \
377 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
378 return true; \
379 }
380
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000381 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000384
385 // We can tolerate different CPUs in many cases, notably when one CPU
386 // supports a strict superset of another. When allowing compatible
387 // differences skip this check.
388 if (!AllowCompatibleDifferences)
389 CHECK_TARGET_OPT(CPU, "target CPU");
390
Guy Benyei11169dd2012-12-18 14:30:41 +0000391#undef CHECK_TARGET_OPT
392
393 // Compare feature sets.
394 SmallVector<StringRef, 4> ExistingFeatures(
395 ExistingTargetOpts.FeaturesAsWritten.begin(),
396 ExistingTargetOpts.FeaturesAsWritten.end());
397 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
398 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000399 llvm::sort(ExistingFeatures);
400 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000401
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000402 // We compute the set difference in both directions explicitly so that we can
403 // diagnose the differences differently.
404 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
405 std::set_difference(
406 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
407 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
408 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
409 ExistingFeatures.begin(), ExistingFeatures.end(),
410 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000412 // If we are allowing compatible differences and the read feature set is
413 // a strict subset of the existing feature set, there is nothing to diagnose.
414 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
415 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 if (Diags) {
418 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000420 << /* is-existing-feature */ false << Feature;
421 for (StringRef Feature : UnmatchedExistingFeatures)
422 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000426 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000427}
428
429bool
430PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000431 bool Complain,
432 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 const LangOptions &ExistingLangOpts = PP.getLangOpts();
434 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000435 Complain ? &Reader.Diags : nullptr,
436 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000437}
438
439bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000440 bool Complain,
441 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
443 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000444 Complain ? &Reader.Diags : nullptr,
445 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000446}
447
448namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000449
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000450using MacroDefinitionsMap =
451 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
452using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000453
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000454} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000455
Ben Langmuirb92de022014-04-29 16:25:26 +0000456static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000460
461 // Check current mappings for new -Werror mappings, and the stored mappings
462 // for cases that were explicitly mapped to *not* be errors that are now
463 // errors because of options like -Werror.
464 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
465
Vedant Kumar48b4f762018-04-14 01:40:48 +0000466 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000467 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
468 diag::kind DiagID = DiagIDMappingPair.first;
469 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
470 if (CurLevel < DiagnosticsEngine::Error)
471 continue; // not significant
472 Level StoredLevel =
473 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
474 if (StoredLevel < DiagnosticsEngine::Error) {
475 if (Complain)
476 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
477 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
478 return true;
479 }
480 }
481 }
482
483 return false;
484}
485
Alp Tokerac4e8e52014-06-22 21:58:33 +0000486static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
487 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
488 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
489 return true;
490 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000491}
492
493static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
494 DiagnosticsEngine &Diags,
495 bool IsSystem, bool Complain) {
496 // Top-level options
497 if (IsSystem) {
498 if (Diags.getSuppressSystemWarnings())
499 return false;
500 // If -Wsystem-headers was not enabled before, be conservative
501 if (StoredDiags.getSuppressSystemWarnings()) {
502 if (Complain)
503 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
504 return true;
505 }
506 }
507
508 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
509 if (Complain)
510 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
511 return true;
512 }
513
514 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
515 !StoredDiags.getEnableAllWarnings()) {
516 if (Complain)
517 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
518 return true;
519 }
520
521 if (isExtHandlingFromDiagsError(Diags) &&
522 !isExtHandlingFromDiagsError(StoredDiags)) {
523 if (Complain)
524 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
525 return true;
526 }
527
528 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
529}
530
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000531/// Return the top import module if it is implicit, nullptr otherwise.
532static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
533 Preprocessor &PP) {
534 // If the original import came from a file explicitly generated by the user,
535 // don't check the diagnostic mappings.
536 // FIXME: currently this is approximated by checking whether this is not a
537 // module import of an implicitly-loaded module file.
538 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
539 // the transitive closure of its imports, since unrelated modules cannot be
540 // imported until after this module finishes validation.
541 ModuleFile *TopImport = &*ModuleMgr.rbegin();
542 while (!TopImport->ImportedBy.empty())
543 TopImport = TopImport->ImportedBy[0];
544 if (TopImport->Kind != MK_ImplicitModule)
545 return nullptr;
546
547 StringRef ModuleName = TopImport->ModuleName;
548 assert(!ModuleName.empty() && "diagnostic options read before module name");
549
550 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
551 assert(M && "missing module");
552 return M;
553}
554
Ben Langmuirb92de022014-04-29 16:25:26 +0000555bool PCHValidator::ReadDiagnosticOptions(
556 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
557 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
558 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
559 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000560 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000561 // This should never fail, because we would have processed these options
562 // before writing them to an ASTFile.
563 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
564
565 ModuleManager &ModuleMgr = Reader.getModuleManager();
566 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
567
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000568 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
569 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000570 return false;
571
Ben Langmuirb92de022014-04-29 16:25:26 +0000572 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
573 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000574 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
575 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000576}
577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000578/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000579/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000580static void
581collectMacroDefinitions(const PreprocessorOptions &PPOpts,
582 MacroDefinitionsMap &Macros,
583 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000584 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
585 StringRef Macro = PPOpts.Macros[I].first;
586 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000587
588 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
589 StringRef MacroName = MacroPair.first;
590 StringRef MacroBody = MacroPair.second;
591
592 // For an #undef'd macro, we only care about the name.
593 if (IsUndef) {
594 if (MacroNames && !Macros.count(MacroName))
595 MacroNames->push_back(MacroName);
596
597 Macros[MacroName] = std::make_pair("", true);
598 continue;
599 }
600
601 // For a #define'd macro, figure out the actual definition.
602 if (MacroName.size() == Macro.size())
603 MacroBody = "1";
604 else {
605 // Note: GCC drops anything following an end-of-line character.
606 StringRef::size_type End = MacroBody.find_first_of("\n\r");
607 MacroBody = MacroBody.substr(0, End);
608 }
609
610 if (MacroNames && !Macros.count(MacroName))
611 MacroNames->push_back(MacroName);
612 Macros[MacroName] = std::make_pair(MacroBody, false);
613 }
614}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000616/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000617/// against the preprocessor options in an existing preprocessor.
618///
619/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000620/// \param Validate If true, validate preprocessor options. If false, allow
621/// macros defined by \p ExistingPPOpts to override those defined by
622/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000623static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
624 const PreprocessorOptions &ExistingPPOpts,
625 DiagnosticsEngine *Diags,
626 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000627 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000628 const LangOptions &LangOpts,
629 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 // Check macro definitions.
631 MacroDefinitionsMap ASTFileMacros;
632 collectMacroDefinitions(PPOpts, ASTFileMacros);
633 MacroDefinitionsMap ExistingMacros;
634 SmallVector<StringRef, 4> ExistingMacroNames;
635 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
636
Vedant Kumar48b4f762018-04-14 01:40:48 +0000637 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000639 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
641
642 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000643 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
644 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000645 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 // FIXME: Check whether this identifier was referenced anywhere in the
647 // AST file. If so, we should reject the AST file. Unfortunately, this
648 // information isn't in the control block. What shall we do about it?
649
650 if (Existing.second) {
651 SuggestedPredefines += "#undef ";
652 SuggestedPredefines += MacroName.str();
653 SuggestedPredefines += '\n';
654 } else {
655 SuggestedPredefines += "#define ";
656 SuggestedPredefines += MacroName.str();
657 SuggestedPredefines += ' ';
658 SuggestedPredefines += Existing.first.str();
659 SuggestedPredefines += '\n';
660 }
661 continue;
662 }
663
664 // If the macro was defined in one but undef'd in the other, we have a
665 // conflict.
666 if (Existing.second != Known->second.second) {
667 if (Diags) {
668 Diags->Report(diag::err_pch_macro_def_undef)
669 << MacroName << Known->second.second;
670 }
671 return true;
672 }
673
674 // If the macro was #undef'd in both, or if the macro bodies are identical,
675 // it's fine.
676 if (Existing.second || Existing.first == Known->second.first)
677 continue;
678
679 // The macro bodies differ; complain.
680 if (Diags) {
681 Diags->Report(diag::err_pch_macro_def_conflict)
682 << MacroName << Known->second.first << Existing.first;
683 }
684 return true;
685 }
686
687 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000688 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000689 if (Diags) {
690 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
691 }
692 return true;
693 }
694
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000695 // Detailed record is important since it is used for the module cache hash.
696 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000697 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000698 if (Diags) {
699 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
700 }
701 return true;
702 }
703
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000705 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
706 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000707
708 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
709 !ExistingPPOpts.PCHThroughHeader.empty()) {
710 // In case the through header is an include, we must add all the includes
711 // to the predefines so the start point can be determined.
712 SuggestedPredefines += "#include \"";
713 SuggestedPredefines += File;
714 SuggestedPredefines += "\"\n";
715 continue;
716 }
717
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 if (File == ExistingPPOpts.ImplicitPCHInclude)
719 continue;
720
721 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
722 != PPOpts.Includes.end())
723 continue;
724
725 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000726 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 SuggestedPredefines += "\"\n";
728 }
729
Vedant Kumar48b4f762018-04-14 01:40:48 +0000730 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
731 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
733 File)
734 != PPOpts.MacroIncludes.end())
735 continue;
736
737 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000738 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 SuggestedPredefines += "\"\n##\n";
740 }
741
742 return false;
743}
744
745bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
746 bool Complain,
747 std::string &SuggestedPredefines) {
748 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
749
750 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000751 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000753 SuggestedPredefines,
754 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000755}
756
Yaxun Liu43712e02016-09-07 18:40:20 +0000757bool SimpleASTReaderListener::ReadPreprocessorOptions(
758 const PreprocessorOptions &PPOpts,
759 bool Complain,
760 std::string &SuggestedPredefines) {
761 return checkPreprocessorOptions(PPOpts,
762 PP.getPreprocessorOpts(),
763 nullptr,
764 PP.getFileManager(),
765 SuggestedPredefines,
766 PP.getLangOpts(),
767 false);
768}
769
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000770/// Check the header search options deserialized from the control block
771/// against the header search options in an existing preprocessor.
772///
773/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
774static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
775 StringRef SpecificModuleCachePath,
776 StringRef ExistingModuleCachePath,
777 DiagnosticsEngine *Diags,
778 const LangOptions &LangOpts) {
779 if (LangOpts.Modules) {
780 if (SpecificModuleCachePath != ExistingModuleCachePath) {
781 if (Diags)
782 Diags->Report(diag::err_pch_modulecache_mismatch)
783 << SpecificModuleCachePath << ExistingModuleCachePath;
784 return true;
785 }
786 }
787
788 return false;
789}
790
791bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
792 StringRef SpecificModuleCachePath,
793 bool Complain) {
794 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
795 PP.getHeaderSearchInfo().getModuleCachePath(),
796 Complain ? &Reader.Diags : nullptr,
797 PP.getLangOpts());
798}
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
801 PP.setCounterValue(Value);
802}
803
804//===----------------------------------------------------------------------===//
805// AST reader implementation
806//===----------------------------------------------------------------------===//
807
Nico Weber824285e2014-05-08 04:26:47 +0000808void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
809 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000811 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000812}
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
815 return serialization::ComputeHash(Sel);
816}
817
Guy Benyei11169dd2012-12-18 14:30:41 +0000818std::pair<unsigned, unsigned>
819ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000821
Justin Bogner57ba0b22014-03-28 22:03:24 +0000822 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
823 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 return std::make_pair(KeyLen, DataLen);
825}
826
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000827ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000828ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000829 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000830
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
833 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
834 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 if (N == 0)
836 return SelTable.getNullarySelector(FirstII);
837 else if (N == 1)
838 return SelTable.getUnarySelector(FirstII);
839
840 SmallVector<IdentifierInfo *, 16> Args;
841 Args.push_back(FirstII);
842 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 Args.push_back(Reader.getLocalIdentifier(
844 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000845
846 return SelTable.getSelector(N, Args.data());
847}
848
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000849ASTSelectorLookupTrait::data_type
850ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000852 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000853
854 data_type Result;
855
Justin Bogner57ba0b22014-03-28 22:03:24 +0000856 Result.ID = Reader.getGlobalSelectorID(
857 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000858 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
859 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
860 Result.InstanceBits = FullInstanceBits & 0x3;
861 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
862 Result.FactoryBits = FullFactoryBits & 0x3;
863 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
864 unsigned NumInstanceMethods = FullInstanceBits >> 3;
865 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000866
867 // Load instance methods
868 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000869 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000870 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 Result.Instance.push_back(Method);
872 }
873
874 // Load factory methods
875 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000876 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000877 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 Result.Factory.push_back(Method);
879 }
880
881 return Result;
882}
883
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000884unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000885 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000886}
887
888std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000890 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000891
Justin Bogner57ba0b22014-03-28 22:03:24 +0000892 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
893 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000894 return std::make_pair(KeyLen, DataLen);
895}
896
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000897ASTIdentifierLookupTraitBase::internal_key_type
898ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000900 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000901}
902
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000903/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000904static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
905 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000906 return II.hadMacroDefinition() ||
907 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000908 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000909 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000910 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000911 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000912}
913
Richard Smith76c2f2c2015-07-17 20:09:43 +0000914static bool readBit(unsigned &Bits) {
915 bool Value = Bits & 0x1;
916 Bits >>= 1;
917 return Value;
918}
919
Richard Smith79bf9202015-08-24 03:33:22 +0000920IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
921 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000922
Richard Smith79bf9202015-08-24 03:33:22 +0000923 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
924 return Reader.getGlobalIdentifierID(F, RawID >> 1);
925}
926
Richard Smitheb4b58f62016-02-05 01:40:54 +0000927static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
928 if (!II.isFromAST()) {
929 II.setIsFromAST();
930 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
931 if (isInterestingIdentifier(Reader, II, IsModule))
932 II.setChangedSinceDeserialization();
933 }
934}
935
Guy Benyei11169dd2012-12-18 14:30:41 +0000936IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
937 const unsigned char* d,
938 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000939 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000940
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 bool IsInteresting = RawID & 0x01;
943
944 // Wipe out the "is interesting" bit.
945 RawID = RawID >> 1;
946
Richard Smith76c2f2c2015-07-17 20:09:43 +0000947 // Build the IdentifierInfo and link the identifier ID with it.
948 IdentifierInfo *II = KnownII;
949 if (!II) {
950 II = &Reader.getIdentifierTable().getOwn(k);
951 KnownII = II;
952 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000953 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000954 Reader.markIdentifierUpToDate(II);
955
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
957 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000958 // For uninteresting identifiers, there's nothing else to do. Just notify
959 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 return II;
962 }
963
Justin Bogner57ba0b22014-03-28 22:03:24 +0000964 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
965 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000966 bool CPlusPlusOperatorKeyword = readBit(Bits);
967 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000968 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000969 bool Poisoned = readBit(Bits);
970 bool ExtensionToken = readBit(Bits);
971 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972
973 assert(Bits == 0 && "Extra bits in the identifier?");
974 DataLen -= 8;
975
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // Set or check the various bits in the IdentifierInfo structure.
977 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000978 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000979 II->revertTokenIDToIdentifier();
980 if (!F.isModule())
981 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
982 else if (HasRevertedBuiltin && II->getBuiltinID()) {
983 II->revertBuiltin();
984 assert((II->hasRevertedBuiltin() ||
985 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
986 "Incorrect ObjC keyword or builtin ID");
987 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 assert(II->isExtensionToken() == ExtensionToken &&
989 "Incorrect extension token flag");
990 (void)ExtensionToken;
991 if (Poisoned)
992 II->setIsPoisoned(true);
993 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
994 "Incorrect C++ operator keyword flag");
995 (void)CPlusPlusOperatorKeyword;
996
997 // If this identifier is a macro, deserialize the macro
998 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000999 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001000 uint32_t MacroDirectivesOffset =
1001 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001002 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001003
Richard Smithd7329392015-04-21 21:46:32 +00001004 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 }
1006
1007 Reader.SetIdentifierInfo(ID, II);
1008
1009 // Read all of the declarations visible at global scope with this
1010 // name.
1011 if (DataLen > 0) {
1012 SmallVector<uint32_t, 4> DeclIDs;
1013 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 DeclIDs.push_back(Reader.getGlobalDeclID(
1015 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1017 }
1018
1019 return II;
1020}
1021
Richard Smitha06c7e62015-08-26 23:55:49 +00001022DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1023 : Kind(Name.getNameKind()) {
1024 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001026 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001034 Data = Name.getCXXOverloadedOperator();
1035 break;
1036 case DeclarationName::CXXLiteralOperatorName:
1037 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1038 break;
Richard Smith35845152017-02-07 01:37:30 +00001039 case DeclarationName::CXXDeductionGuideName:
1040 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1041 ->getDeclName().getAsIdentifierInfo();
1042 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001043 case DeclarationName::CXXConstructorName:
1044 case DeclarationName::CXXDestructorName:
1045 case DeclarationName::CXXConversionFunctionName:
1046 case DeclarationName::CXXUsingDirective:
1047 Data = 0;
1048 break;
1049 }
1050}
1051
1052unsigned DeclarationNameKey::getHash() const {
1053 llvm::FoldingSetNodeID ID;
1054 ID.AddInteger(Kind);
1055
1056 switch (Kind) {
1057 case DeclarationName::Identifier:
1058 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001059 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001060 ID.AddString(((IdentifierInfo*)Data)->getName());
1061 break;
1062 case DeclarationName::ObjCZeroArgSelector:
1063 case DeclarationName::ObjCOneArgSelector:
1064 case DeclarationName::ObjCMultiArgSelector:
1065 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1066 break;
1067 case DeclarationName::CXXOperatorName:
1068 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 break;
1070 case DeclarationName::CXXConstructorName:
1071 case DeclarationName::CXXDestructorName:
1072 case DeclarationName::CXXConversionFunctionName:
1073 case DeclarationName::CXXUsingDirective:
1074 break;
1075 }
1076
1077 return ID.ComputeHash();
1078}
1079
Richard Smithd88a7f12015-09-01 20:35:42 +00001080ModuleFile *
1081ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1082 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001083
Richard Smithd88a7f12015-09-01 20:35:42 +00001084 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1085 return Reader.getLocalModuleFile(F, ModuleFileID);
1086}
1087
Guy Benyei11169dd2012-12-18 14:30:41 +00001088std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001089ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001090 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001091
Justin Bogner57ba0b22014-03-28 22:03:24 +00001092 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1093 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 return std::make_pair(KeyLen, DataLen);
1095}
1096
Richard Smitha06c7e62015-08-26 23:55:49 +00001097ASTDeclContextNameLookupTrait::internal_key_type
1098ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001099 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
Vedant Kumar48b4f762018-04-14 01:40:48 +00001101 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001102 uint64_t Data;
1103 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001105 case DeclarationName::CXXLiteralOperatorName:
1106 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001108 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 break;
1110 case DeclarationName::ObjCZeroArgSelector:
1111 case DeclarationName::ObjCOneArgSelector:
1112 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001113 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001114 (uint64_t)Reader.getLocalSelector(
1115 F, endian::readNext<uint32_t, little, unaligned>(
1116 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 break;
1118 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001119 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 case DeclarationName::CXXConstructorName:
1122 case DeclarationName::CXXDestructorName:
1123 case DeclarationName::CXXConversionFunctionName:
1124 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001125 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001126 break;
1127 }
1128
Richard Smitha06c7e62015-08-26 23:55:49 +00001129 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001130}
1131
Richard Smithd88a7f12015-09-01 20:35:42 +00001132void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1133 const unsigned char *d,
1134 unsigned DataLen,
1135 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001136 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001137
Richard Smithd88a7f12015-09-01 20:35:42 +00001138 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1139 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1140 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001142}
1143
Richard Smith0f4e2c42015-08-06 04:23:48 +00001144bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1145 BitstreamCursor &Cursor,
1146 uint64_t Offset,
1147 DeclContext *DC) {
1148 assert(Offset != 0);
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001151 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1152 Error(std::move(Err));
1153 return true;
1154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001155
Richard Smith0f4e2c42015-08-06 04:23:48 +00001156 RecordData Record;
1157 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001158 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1159 if (!MaybeCode) {
1160 Error(MaybeCode.takeError());
1161 return true;
1162 }
1163 unsigned Code = MaybeCode.get();
1164
1165 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1166 if (!MaybeRecCode) {
1167 Error(MaybeRecCode.takeError());
1168 return true;
1169 }
1170 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001171 if (RecCode != DECL_CONTEXT_LEXICAL) {
1172 Error("Expected lexical block");
1173 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 }
1175
Richard Smith82f8fcd2015-08-06 22:07:25 +00001176 assert(!isa<TranslationUnitDecl>(DC) &&
1177 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001178 // If we are handling a C++ class template instantiation, we can see multiple
1179 // lexical updates for the same record. It's important that we select only one
1180 // of them, so that field numbering works properly. Just pick the first one we
1181 // see.
1182 auto &Lex = LexicalDecls[DC];
1183 if (!Lex.first) {
1184 Lex = std::make_pair(
1185 &M, llvm::makeArrayRef(
1186 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1187 Blob.data()),
1188 Blob.size() / 4));
1189 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001190 DC->setHasExternalLexicalStorage(true);
1191 return false;
1192}
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
Richard Smith0f4e2c42015-08-06 04:23:48 +00001194bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1195 BitstreamCursor &Cursor,
1196 uint64_t Offset,
1197 DeclID ID) {
1198 assert(Offset != 0);
1199
1200 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001201 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1202 Error(std::move(Err));
1203 return true;
1204 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001205
1206 RecordData Record;
1207 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001208 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1209 if (!MaybeCode) {
1210 Error(MaybeCode.takeError());
1211 return true;
1212 }
1213 unsigned Code = MaybeCode.get();
1214
1215 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1216 if (!MaybeRecCode) {
1217 Error(MaybeRecCode.takeError());
1218 return true;
1219 }
1220 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001221 if (RecCode != DECL_CONTEXT_VISIBLE) {
1222 Error("Expected visible lookup table block");
1223 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 }
1225
Richard Smith0f4e2c42015-08-06 04:23:48 +00001226 // We can't safely determine the primary context yet, so delay attaching the
1227 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001228 auto *Data = (const unsigned char*)Blob.data();
1229 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 return false;
1231}
1232
Richard Smith37a93df2017-02-18 00:32:02 +00001233void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001235 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001236 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001237 Diag(diag::note_module_cache_path)
1238 << PP.getHeaderSearchInfo().getModuleCachePath();
1239 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001240}
1241
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001242void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1243 StringRef Arg3) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 if (Diags.isDiagnosticInFlight())
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001245 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 else
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001247 Diag(DiagID) << Arg1 << Arg2 << Arg3;
Guy Benyei11169dd2012-12-18 14:30:41 +00001248}
1249
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001250void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1251 unsigned Select) const {
1252 if (!Diags.isDiagnosticInFlight())
1253 Diag(DiagID) << Arg1 << Arg2 << Select;
1254}
1255
JF Bastien0e828952019-06-26 19:50:12 +00001256void ASTReader::Error(llvm::Error &&Err) const {
1257 Error(toString(std::move(Err)));
1258}
1259
Guy Benyei11169dd2012-12-18 14:30:41 +00001260//===----------------------------------------------------------------------===//
1261// Source Manager Deserialization
1262//===----------------------------------------------------------------------===//
1263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001264/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001265/// \returns true if there was an error.
1266bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001267 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 unsigned Idx = 0;
1269 LineTableInfo &LineTable = SourceMgr.getLineTable();
1270
1271 // Parse the file names
1272 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001273 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001274 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001275 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001276 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1278 }
Richard Smith63078492015-09-01 07:41:55 +00001279 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001280
1281 // Parse the line entries
1282 std::vector<LineEntry> Entries;
1283 while (Idx < Record.size()) {
1284 int FID = Record[Idx++];
1285 assert(FID >= 0 && "Serialized line entries for non-local file.");
1286 // Remap FileID from 1-based old view.
1287 FID += F.SLocEntryBaseID - 1;
1288
1289 // Extract the line entries
1290 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001291 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001292 Entries.clear();
1293 Entries.reserve(NumEntries);
1294 for (unsigned I = 0; I != NumEntries; ++I) {
1295 unsigned FileOffset = Record[Idx++];
1296 unsigned LineNo = Record[Idx++];
1297 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001298 SrcMgr::CharacteristicKind FileKind
1299 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 unsigned IncludeOffset = Record[Idx++];
1301 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1302 FileKind, IncludeOffset));
1303 }
1304 LineTable.AddEntry(FileID::get(FID), Entries);
1305 }
1306
1307 return false;
1308}
1309
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001310/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001311bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1312 using namespace SrcMgr;
1313
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001314 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001315
1316 // Set the source-location entry cursor to the current position in
1317 // the stream. This cursor will be used to read the contents of the
1318 // source manager block initially, and then lazily read
1319 // source-location entries as needed.
1320 SLocEntryCursor = F.Stream;
1321
1322 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001323 if (llvm::Error Err = F.Stream.SkipBlock()) {
1324 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 return true;
1326 }
1327
1328 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001329 if (llvm::Error Err =
1330 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1331 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 return true;
1333 }
1334
1335 RecordData Record;
1336 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001337 Expected<llvm::BitstreamEntry> MaybeE =
1338 SLocEntryCursor.advanceSkippingSubblocks();
1339 if (!MaybeE) {
1340 Error(MaybeE.takeError());
1341 return true;
1342 }
1343 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001344
Chris Lattnere7b154b2013-01-19 21:39:22 +00001345 switch (E.Kind) {
1346 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1347 case llvm::BitstreamEntry::Error:
1348 Error("malformed block record in AST file");
1349 return true;
1350 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001352 case llvm::BitstreamEntry::Record:
1353 // The interesting case.
1354 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001359 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001360 Expected<unsigned> MaybeRecord =
1361 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1362 if (!MaybeRecord) {
1363 Error(MaybeRecord.takeError());
1364 return true;
1365 }
1366 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001367 default: // Default behavior: ignore.
1368 break;
1369
1370 case SM_SLOC_FILE_ENTRY:
1371 case SM_SLOC_BUFFER_ENTRY:
1372 case SM_SLOC_EXPANSION_ENTRY:
1373 // Once we hit one of the source location entries, we're done.
1374 return false;
1375 }
1376 }
1377}
1378
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001379/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001380/// and the PCH file was moved from its original location, try to resolve the
1381/// file by assuming that header+PCH were moved together and the header is in
1382/// the same place relative to the PCH.
1383static std::string
1384resolveFileRelativeToOriginalDir(const std::string &Filename,
1385 const std::string &OriginalDir,
1386 const std::string &CurrDir) {
1387 assert(OriginalDir != CurrDir &&
1388 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001391
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 SmallString<128> filePath(Filename);
1393 fs::make_absolute(filePath);
1394 assert(path::is_absolute(OriginalDir));
1395 SmallString<128> currPCHPath(CurrDir);
1396
1397 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1398 fileDirE = path::end(path::parent_path(filePath));
1399 path::const_iterator origDirI = path::begin(OriginalDir),
1400 origDirE = path::end(OriginalDir);
1401 // Skip the common path components from filePath and OriginalDir.
1402 while (fileDirI != fileDirE && origDirI != origDirE &&
1403 *fileDirI == *origDirI) {
1404 ++fileDirI;
1405 ++origDirI;
1406 }
1407 for (; origDirI != origDirE; ++origDirI)
1408 path::append(currPCHPath, "..");
1409 path::append(currPCHPath, fileDirI, fileDirE);
1410 path::append(currPCHPath, path::filename(Filename));
1411 return currPCHPath.str();
1412}
1413
1414bool ASTReader::ReadSLocEntry(int ID) {
1415 if (ID == 0)
1416 return false;
1417
1418 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1419 Error("source location entry ID out-of-range for AST file");
1420 return true;
1421 }
1422
Richard Smithaada85c2016-02-06 02:06:43 +00001423 // Local helper to read the (possibly-compressed) buffer data following the
1424 // entry record.
1425 auto ReadBuffer = [this](
1426 BitstreamCursor &SLocEntryCursor,
1427 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1428 RecordData Record;
1429 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001430 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1431 if (!MaybeCode) {
1432 Error(MaybeCode.takeError());
1433 return nullptr;
1434 }
1435 unsigned Code = MaybeCode.get();
1436
1437 Expected<unsigned> MaybeRecCode =
1438 SLocEntryCursor.readRecord(Code, Record, &Blob);
1439 if (!MaybeRecCode) {
1440 Error(MaybeRecCode.takeError());
1441 return nullptr;
1442 }
1443 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001444
1445 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001446 if (!llvm::zlib::isAvailable()) {
1447 Error("zlib is not available");
1448 return nullptr;
1449 }
Richard Smithaada85c2016-02-06 02:06:43 +00001450 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001451 if (llvm::Error E =
1452 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1453 Error("could not decompress embedded file contents: " +
1454 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001455 return nullptr;
1456 }
1457 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1458 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1459 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1460 } else {
1461 Error("AST record has invalid code");
1462 return nullptr;
1463 }
1464 };
1465
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001467 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1468 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1469 Error(std::move(Err));
1470 return true;
1471 }
1472
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001473 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 unsigned BaseOffset = F->SLocEntryBaseOffset;
1475
1476 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001477 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1478 if (!MaybeEntry) {
1479 Error(MaybeEntry.takeError());
1480 return true;
1481 }
1482 llvm::BitstreamEntry Entry = MaybeEntry.get();
1483
Chris Lattnere7b154b2013-01-19 21:39:22 +00001484 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 Error("incorrectly-formatted source location entry in AST file");
1486 return true;
1487 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001488
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001490 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001491 Expected<unsigned> MaybeSLOC =
1492 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1493 if (!MaybeSLOC) {
1494 Error(MaybeSLOC.takeError());
1495 return true;
1496 }
1497 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 default:
1499 Error("incorrectly-formatted source location entry in AST file");
1500 return true;
1501
1502 case SM_SLOC_FILE_ENTRY: {
1503 // We will detect whether a file changed and return 'Failure' for it, but
1504 // we will also try to fail gracefully by setting up the SLocEntry.
1505 unsigned InputID = Record[4];
1506 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001507 const FileEntry *File = IF.getFile();
1508 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001509
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001510 // Note that we only check if a File was returned. If it was out-of-date
1511 // we have complained but we will continue creating a FileID to recover
1512 // gracefully.
1513 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 return true;
1515
1516 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1517 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1518 // This is the module's main file.
1519 IncludeLoc = getImportLocation(F);
1520 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001521 SrcMgr::CharacteristicKind
1522 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001523 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1525 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001526 SrcMgr::FileInfo &FileInfo =
1527 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 FileInfo.NumCreatedFIDs = Record[5];
1529 if (Record[3])
1530 FileInfo.setHasLineDirectives();
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001533 if (NumFileDecls && ContextObj) {
Roman Lebedevbf4f1e02019-10-10 12:22:42 +00001534 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1536 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1537 NumFileDecls));
1538 }
Richard Smithaada85c2016-02-06 02:06:43 +00001539
Guy Benyei11169dd2012-12-18 14:30:41 +00001540 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001541 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001543 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1544 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001545 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1546 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001548 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 }
1550
1551 break;
1552 }
1553
1554 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001555 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001556 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001557 SrcMgr::CharacteristicKind
1558 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001559 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001560 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 IncludeLoc = getImportLocation(F);
1562 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001563
Richard Smithaada85c2016-02-06 02:06:43 +00001564 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1565 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001567 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001568 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 break;
1570 }
1571
1572 case SM_SLOC_EXPANSION_ENTRY: {
1573 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1574 SourceMgr.createExpansionLoc(SpellingLoc,
1575 ReadSourceLocation(*F, Record[2]),
1576 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001577 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 Record[4],
1579 ID,
1580 BaseOffset + Record[0]);
1581 break;
1582 }
1583 }
1584
1585 return false;
1586}
1587
1588std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1589 if (ID == 0)
1590 return std::make_pair(SourceLocation(), "");
1591
1592 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1593 Error("source location entry ID out-of-range for AST file");
1594 return std::make_pair(SourceLocation(), "");
1595 }
1596
1597 // Find which module file this entry lands in.
1598 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001599 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 return std::make_pair(SourceLocation(), "");
1601
1602 // FIXME: Can we map this down to a particular submodule? That would be
1603 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001604 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001605}
1606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001607/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001608SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1609 if (F->ImportLoc.isValid())
1610 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001611
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 // Otherwise we have a PCH. It's considered to be "imported" at the first
1613 // location of its includer.
1614 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001615 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001616 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001617 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 return F->ImportedBy[0]->FirstLoc;
1620}
1621
JF Bastien0e828952019-06-26 19:50:12 +00001622/// Enter a subblock of the specified BlockID with the specified cursor. Read
1623/// the abbreviations that are at the top of the block and then leave the cursor
1624/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001625bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001626 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1627 // FIXME this drops errors on the floor.
1628 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001629 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001630 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001631
1632 while (true) {
1633 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001634 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1635 if (!MaybeCode) {
1636 // FIXME this drops errors on the floor.
1637 consumeError(MaybeCode.takeError());
1638 return true;
1639 }
1640 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001641
1642 // We expect all abbrevs to be at the start of the block.
1643 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001644 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1645 // FIXME this drops errors on the floor.
1646 consumeError(std::move(Err));
1647 return true;
1648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 return false;
1650 }
JF Bastien0e828952019-06-26 19:50:12 +00001651 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1652 // FIXME this drops errors on the floor.
1653 consumeError(std::move(Err));
1654 return true;
1655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 }
1657}
1658
Richard Smithe40f2ba2013-08-07 21:41:30 +00001659Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001660 unsigned &Idx) {
1661 Token Tok;
1662 Tok.startToken();
1663 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1664 Tok.setLength(Record[Idx++]);
1665 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1666 Tok.setIdentifierInfo(II);
1667 Tok.setKind((tok::TokenKind)Record[Idx++]);
1668 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1669 return Tok;
1670}
1671
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001672MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001673 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674
1675 // Keep track of where we are in the stream, then jump back there
1676 // after reading this macro.
1677 SavedStreamPosition SavedPosition(Stream);
1678
JF Bastien0e828952019-06-26 19:50:12 +00001679 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1680 // FIXME this drops errors on the floor.
1681 consumeError(std::move(Err));
1682 return nullptr;
1683 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001685 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001686 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001689 // Advance to the next record, but if we get to the end of the block, don't
1690 // pop it (removing all the abbreviations from the cursor) since we want to
1691 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001692 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001693 Expected<llvm::BitstreamEntry> MaybeEntry =
1694 Stream.advanceSkippingSubblocks(Flags);
1695 if (!MaybeEntry) {
1696 Error(MaybeEntry.takeError());
1697 return Macro;
1698 }
1699 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001700
Chris Lattnerefa77172013-01-20 00:00:22 +00001701 switch (Entry.Kind) {
1702 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1703 case llvm::BitstreamEntry::Error:
1704 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001705 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001706 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001707 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001708 case llvm::BitstreamEntry::Record:
1709 // The interesting case.
1710 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001711 }
1712
1713 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001715 PreprocessorRecordTypes RecType;
1716 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1717 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1718 else {
1719 Error(MaybeRecType.takeError());
1720 return Macro;
1721 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001723 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001724 case PP_MACRO_DIRECTIVE_HISTORY:
1725 return Macro;
1726
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 case PP_MACRO_OBJECT_LIKE:
1728 case PP_MACRO_FUNCTION_LIKE: {
1729 // If we already have a macro, that means that we've hit the end
1730 // of the definition of the macro we were looking for. We're
1731 // done.
1732 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001733 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001734
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001735 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001737 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001738 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001740 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001741
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1743 // Decode function-like macro info.
1744 bool isC99VarArgs = Record[NextIndex++];
1745 bool isGNUVarArgs = Record[NextIndex++];
1746 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001747 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 unsigned NumArgs = Record[NextIndex++];
1749 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001750 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001751
1752 // Install function-like macro info.
1753 MI->setIsFunctionLike();
1754 if (isC99VarArgs) MI->setIsC99Varargs();
1755 if (isGNUVarArgs) MI->setIsGNUVarargs();
1756 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001757 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 }
1759
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 // Remember that we saw this macro last so that we add the tokens that
1761 // form its body to it.
1762 Macro = MI;
1763
1764 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1765 Record[NextIndex]) {
1766 // We have a macro definition. Register the association
1767 PreprocessedEntityID
1768 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1769 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001770 PreprocessingRecord::PPEntityID PPID =
1771 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001772 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001773 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001774 if (PPDef)
1775 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001776 }
1777
1778 ++NumMacrosRead;
1779 break;
1780 }
1781
1782 case PP_TOKEN: {
1783 // If we see a TOKEN before a PP_MACRO_*, then the file is
1784 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001785 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001786
John McCallf413f5e2013-05-03 00:10:13 +00001787 unsigned Idx = 0;
1788 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 Macro->AddTokenToBody(Tok);
1790 break;
1791 }
1792 }
1793 }
1794}
1795
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001796PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001797ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1798 unsigned LocalID) const {
1799 if (!M.ModuleOffsetMap.empty())
1800 ReadModuleOffsetMap(M);
1801
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001802 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001804 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001806
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 return LocalID + I->second;
1808}
1809
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001810unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1811 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001812}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001813
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001814HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001815HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001816 internal_key_type ikey = {FE->getSize(),
1817 M.HasTimestamps ? FE->getModificationTime() : 0,
1818 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001819 return ikey;
1820}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001821
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001822bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001823 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 return false;
1825
Mehdi Amini004b9c72016-10-10 22:52:47 +00001826 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001827 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001828
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001830 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001831 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001832 if (!Key.Imported) {
1833 if (auto File = FileMgr.getFile(Key.Filename))
1834 return *File;
1835 return nullptr;
1836 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001837
1838 std::string Resolved = Key.Filename;
1839 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001840 if (auto File = FileMgr.getFile(Resolved))
1841 return *File;
1842 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001843 };
1844
1845 const FileEntry *FEA = GetFile(a);
1846 const FileEntry *FEB = GetFile(b);
1847 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001848}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001849
Guy Benyei11169dd2012-12-18 14:30:41 +00001850std::pair<unsigned, unsigned>
1851HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001852 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001853
Vedant Kumar48b4f762018-04-14 01:40:48 +00001854 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1855 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001856 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001857}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001858
1859HeaderFileInfoTrait::internal_key_type
1860HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001861 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001862
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001863 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001864 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1865 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001866 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001867 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001868 return ikey;
1869}
1870
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001871HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001872HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001874 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001875
1876 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 HeaderFileInfo HFI;
1878 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001879 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001880 HFI.isImport |= (Flags >> 5) & 0x01;
1881 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1882 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001884 // FIXME: Find a better way to handle this. Maybe just store a
1885 // "has been included" flag?
1886 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1887 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001888 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1889 M, endian::readNext<uint32_t, little, unaligned>(d));
1890 if (unsigned FrameworkOffset =
1891 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001892 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 // since 0 is used as an indicator for "no framework name".
1894 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1895 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1896 }
Richard Smith386bb072015-08-18 23:42:23 +00001897
1898 assert((End - d) % 4 == 0 &&
1899 "Wrong data length in HeaderFileInfo deserialization");
1900 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001901 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001902 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1903 LocalSMID >>= 2;
1904
1905 // This header is part of a module. Associate it with the module to enable
1906 // implicit module import.
1907 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1908 Module *Mod = Reader.getSubmodule(GlobalSMID);
1909 FileManager &FileMgr = Reader.getFileManager();
1910 ModuleMap &ModMap =
1911 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1912
1913 std::string Filename = key.Filename;
1914 if (key.Imported)
1915 Reader.ResolveImportedPath(M, Filename);
1916 // FIXME: This is not always the right filename-as-written, but we're not
1917 // going to use this information to rebuild the module, so it doesn't make
1918 // a lot of difference.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001919 Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001920 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1921 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001922 }
1923
Guy Benyei11169dd2012-12-18 14:30:41 +00001924 // This HeaderFileInfo was externally loaded.
1925 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001926 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 return HFI;
1928}
1929
Richard Smithd7329392015-04-21 21:46:32 +00001930void ASTReader::addPendingMacro(IdentifierInfo *II,
1931 ModuleFile *M,
1932 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1934 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001935}
1936
1937void ASTReader::ReadDefinedMacros() {
1938 // Note that we are loading defined macros.
1939 Deserializing Macros(this);
1940
Vedant Kumar48b4f762018-04-14 01:40:48 +00001941 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001942 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001943
1944 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001945 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001946 continue;
1947
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001948 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001949 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1950 Error(std::move(Err));
1951 return;
1952 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001953
1954 RecordData Record;
1955 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001956 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1957 if (!MaybeE) {
1958 Error(MaybeE.takeError());
1959 return;
1960 }
1961 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001962
Chris Lattnere7b154b2013-01-19 21:39:22 +00001963 switch (E.Kind) {
1964 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1965 case llvm::BitstreamEntry::Error:
1966 Error("malformed block record in AST file");
1967 return;
1968 case llvm::BitstreamEntry::EndBlock:
1969 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001970
JF Bastien0e828952019-06-26 19:50:12 +00001971 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001972 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001973 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1974 if (!MaybeRecord) {
1975 Error(MaybeRecord.takeError());
1976 return;
1977 }
1978 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001979 default: // Default behavior: ignore.
1980 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001981
Chris Lattnere7b154b2013-01-19 21:39:22 +00001982 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001983 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001984 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001985 if (II->isOutOfDate())
1986 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001987 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001988 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001989
Chris Lattnere7b154b2013-01-19 21:39:22 +00001990 case PP_TOKEN:
1991 // Ignore tokens.
1992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 break;
1995 }
JF Bastien0e828952019-06-26 19:50:12 +00001996 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001998 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 }
2000}
2001
2002namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002004 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 class IdentifierLookupVisitor {
2006 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002007 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002009 unsigned &NumIdentifierLookups;
2010 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002011 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002014 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2015 unsigned &NumIdentifierLookups,
2016 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002017 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2018 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002019 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002020 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002021
2022 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002024 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002025 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002026
Vedant Kumar48b4f762018-04-14 01:40:48 +00002027 ASTIdentifierLookupTable *IdTable
2028 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 if (!IdTable)
2030 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002031
2032 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002033 Found);
2034 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002035 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002036 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 if (Pos == IdTable->end())
2038 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002039
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 // Dereferencing the iterator has the effect of building the
2041 // IdentifierInfo node and populating it with the various
2042 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002043 ++NumIdentifierLookupHits;
2044 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 return true;
2046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002047
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002048 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002049 // files.
2050 IdentifierInfo *getIdentifierInfo() const { return Found; }
2051 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002052
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002053} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002054
2055void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2056 // Note that we are loading an identifier.
2057 Deserializing AnIdentifier(this);
2058
2059 unsigned PriorGeneration = 0;
2060 if (getContext().getLangOpts().Modules)
2061 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002062
2063 // If there is a global index, look there first to determine which modules
2064 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002065 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002066 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002067 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002068 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2069 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002070 }
2071 }
2072
Douglas Gregor7211ac12013-01-25 23:32:03 +00002073 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002074 NumIdentifierLookups,
2075 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002076 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 markIdentifierUpToDate(&II);
2078}
2079
2080void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2081 if (!II)
2082 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002083
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 II->setOutOfDate(false);
2085
2086 // Update the generation for this identifier.
2087 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002088 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002089}
2090
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002091void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2092 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002093 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002094
2095 BitstreamCursor &Cursor = M.MacroCursor;
2096 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002097 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2098 Error(std::move(Err));
2099 return;
2100 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002101
Richard Smith713369b2015-04-23 20:40:50 +00002102 struct ModuleMacroRecord {
2103 SubmoduleID SubModID;
2104 MacroInfo *MI;
2105 SmallVector<SubmoduleID, 8> Overrides;
2106 };
2107 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002108
Richard Smithd7329392015-04-21 21:46:32 +00002109 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2110 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2111 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002112 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002113 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002114 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002115 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002116 if (!MaybeEntry) {
2117 Error(MaybeEntry.takeError());
2118 return;
2119 }
2120 llvm::BitstreamEntry Entry = MaybeEntry.get();
2121
Richard Smithd7329392015-04-21 21:46:32 +00002122 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2123 Error("malformed block record in AST file");
2124 return;
2125 }
2126
2127 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002128 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2129 if (!MaybePP) {
2130 Error(MaybePP.takeError());
2131 return;
2132 }
2133 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002134 case PP_MACRO_DIRECTIVE_HISTORY:
2135 break;
2136
2137 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002138 ModuleMacros.push_back(ModuleMacroRecord());
2139 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002140 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2141 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002142 for (int I = 2, N = Record.size(); I != N; ++I)
2143 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002144 continue;
2145 }
2146
2147 default:
2148 Error("malformed block record in AST file");
2149 return;
2150 }
2151
2152 // We found the macro directive history; that's the last record
2153 // for this macro.
2154 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002155 }
2156
Richard Smithd7329392015-04-21 21:46:32 +00002157 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002158 {
2159 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002160 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002161 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002162 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002163 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002164 Module *Mod = getSubmodule(ModID);
2165 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002166 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002167 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002168 }
2169
2170 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002171 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002172 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002173 }
2174 }
2175
2176 // Don't read the directive history for a module; we don't have anywhere
2177 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002178 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002179 return;
2180
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002181 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002182 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002183 unsigned Idx = 0, N = Record.size();
2184 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002185 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002186 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002187 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002188 switch (K) {
2189 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002190 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002191 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002192 break;
2193 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002194 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002195 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002196 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002197 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002198 bool isPublic = Record[Idx++];
2199 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2200 break;
2201 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002202
2203 if (!Latest)
2204 Latest = MD;
2205 if (Earliest)
2206 Earliest->setPrevious(MD);
2207 Earliest = MD;
2208 }
2209
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002210 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002211 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002212}
2213
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002214ASTReader::InputFileInfo
2215ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002216 // Go find this input file.
2217 BitstreamCursor &Cursor = F.InputFilesCursor;
2218 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002219 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2220 // FIXME this drops errors on the floor.
2221 consumeError(std::move(Err));
2222 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002223
JF Bastien0e828952019-06-26 19:50:12 +00002224 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2225 if (!MaybeCode) {
2226 // FIXME this drops errors on the floor.
2227 consumeError(MaybeCode.takeError());
2228 }
2229 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002230 RecordData Record;
2231 StringRef Blob;
2232
JF Bastien0e828952019-06-26 19:50:12 +00002233 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2234 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2235 "invalid record type for input file");
2236 else {
2237 // FIXME this drops errors on the floor.
2238 consumeError(Maybe.takeError());
2239 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002240
2241 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002242 InputFileInfo R;
2243 R.StoredSize = static_cast<off_t>(Record[1]);
2244 R.StoredTime = static_cast<time_t>(Record[2]);
2245 R.Overridden = static_cast<bool>(Record[3]);
2246 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002247 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002248 R.Filename = Blob;
2249 ResolveImportedPath(F, R.Filename);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002250
2251 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2252 if (!MaybeEntry) // FIXME this drops errors on the floor.
2253 consumeError(MaybeEntry.takeError());
2254 llvm::BitstreamEntry Entry = MaybeEntry.get();
2255 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2256 "expected record type for input file hash");
2257
2258 Record.clear();
2259 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2260 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2261 "invalid record type for input file hash");
2262 else {
2263 // FIXME this drops errors on the floor.
2264 consumeError(Maybe.takeError());
2265 }
2266 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2267 static_cast<uint64_t>(Record[0]);
Hans Wennborg73945142014-03-14 17:45:06 +00002268 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002269}
2270
Manman Renc8c94152016-10-21 23:35:03 +00002271static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002272InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 // If this ID is bogus, just return an empty input file.
2274 if (ID == 0 || ID > F.InputFilesLoaded.size())
2275 return InputFile();
2276
2277 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002278 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 return F.InputFilesLoaded[ID-1];
2280
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002281 if (F.InputFilesLoaded[ID-1].isNotFound())
2282 return InputFile();
2283
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002285 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002287 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2288 // FIXME this drops errors on the floor.
2289 consumeError(std::move(Err));
2290 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002291
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002292 InputFileInfo FI = readInputFileInfo(F, ID);
2293 off_t StoredSize = FI.StoredSize;
2294 time_t StoredTime = FI.StoredTime;
2295 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002296 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002297 StringRef Filename = FI.Filename;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002298 uint64_t StoredContentHash = FI.ContentHash;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002299
Harlan Haskins8d323d12019-08-01 21:31:56 +00002300 const FileEntry *File = nullptr;
2301 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2302 File = *FE;
2303
Ben Langmuir198c1682014-03-07 07:27:49 +00002304 // If we didn't find the file, resolve it relative to the
2305 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002306 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2307 F.OriginalDir != F.BaseDirectory) {
2308 std::string Resolved = resolveFileRelativeToOriginalDir(
2309 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002310 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002311 if (auto FE = FileMgr.getFile(Resolved))
2312 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002313 }
2314
2315 // For an overridden file, create a virtual file with the stored
2316 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002317 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002318 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002319
Craig Toppera13603a2014-05-22 05:54:18 +00002320 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002321 if (Complain) {
2322 std::string ErrorStr = "could not find file '";
2323 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002324 ErrorStr += "' referenced by AST file '";
2325 ErrorStr += F.FileName;
2326 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002327 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002329 // Record that we didn't find the file.
2330 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2331 return InputFile();
2332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002333
Ben Langmuir198c1682014-03-07 07:27:49 +00002334 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002335 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002336 // can lead to problems when lexing using the source locations from the
2337 // PCH.
2338 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002339 // FIXME: Reject if the overrides are different.
2340 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002341 if (Complain)
2342 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002343
2344 // After emitting the diagnostic, bypass the overriding file to recover
2345 // (this creates a separate FileEntry).
2346 File = SM.bypassFileContentsOverride(*File);
2347 if (!File) {
2348 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2349 return InputFile();
2350 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002351 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002352
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002353 enum ModificationType {
2354 Size,
2355 ModTime,
2356 Content,
2357 None,
2358 };
2359 auto HasInputFileChanged = [&]() {
2360 if (StoredSize != File->getSize())
2361 return ModificationType::Size;
2362 if (!DisableValidation && StoredTime &&
2363 StoredTime != File->getModificationTime()) {
2364 // In case the modification time changes but not the content,
2365 // accept the cached file as legit.
2366 if (ValidateASTInputFilesContent &&
2367 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2368 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2369 if (!MemBuffOrError) {
2370 if (!Complain)
2371 return ModificationType::ModTime;
2372 std::string ErrorStr = "could not get buffer for file '";
2373 ErrorStr += File->getName();
2374 ErrorStr += "'";
2375 Error(ErrorStr);
2376 return ModificationType::ModTime;
2377 }
Eric Christopher3be91692019-10-14 23:14:24 +00002378
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002379 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2380 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2381 return ModificationType::None;
2382 return ModificationType::Content;
2383 }
2384 return ModificationType::ModTime;
2385 }
2386 return ModificationType::None;
2387 };
2388
2389 bool IsOutOfDate = false;
2390 auto FileChange = HasInputFileChanged();
Ben Langmuir198c1682014-03-07 07:27:49 +00002391 // For an overridden file, there is nothing to validate.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002392 if (!Overridden && FileChange != ModificationType::None) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002393 if (Complain) {
2394 // Build a list of the PCH imports that got us here (in reverse).
2395 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002396 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002397 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002398
Ben Langmuir198c1682014-03-07 07:27:49 +00002399 // The top-level PCH is stale.
2400 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002401 unsigned DiagnosticKind =
2402 moduleKindForDiagnostic(ImportStack.back()->Kind);
Manman Renc8c94152016-10-21 23:35:03 +00002403 if (DiagnosticKind == 0)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002404 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2405 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002406 else if (DiagnosticKind == 1)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002407 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2408 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002409 else
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002410 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2411 (unsigned)FileChange);
Ben Langmuire82630d2014-01-17 00:19:09 +00002412
Ben Langmuir198c1682014-03-07 07:27:49 +00002413 // Print the import stack.
2414 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2415 Diag(diag::note_pch_required_by)
2416 << Filename << ImportStack[0]->FileName;
2417 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002418 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002419 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002420 }
2421
Ben Langmuir198c1682014-03-07 07:27:49 +00002422 if (!Diags.isDiagnosticInFlight())
2423 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 }
2425
Ben Langmuir198c1682014-03-07 07:27:49 +00002426 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002428 // FIXME: If the file is overridden and we've already opened it,
2429 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002430
Richard Smitha8cfffa2015-11-26 02:04:16 +00002431 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002432
2433 // Note that we've loaded this input file.
2434 F.InputFilesLoaded[ID-1] = IF;
2435 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436}
2437
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002438/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002439/// is not an absolute path, add the system or module root to the beginning of
2440/// the file name.
2441void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2442 // Resolve relative to the base directory, if we have one.
2443 if (!M.BaseDirectory.empty())
2444 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002445}
2446
Richard Smith7ed1bc92014-12-05 22:42:13 +00002447void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2449 return;
2450
Richard Smith7ed1bc92014-12-05 22:42:13 +00002451 SmallString<128> Buffer;
2452 llvm::sys::path::append(Buffer, Prefix, Filename);
2453 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002454}
2455
Richard Smith0f99d6a2015-08-09 08:48:41 +00002456static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2457 switch (ARR) {
2458 case ASTReader::Failure: return true;
2459 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2460 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2461 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2462 case ASTReader::ConfigurationMismatch:
2463 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2464 case ASTReader::HadErrors: return true;
2465 case ASTReader::Success: return false;
2466 }
2467
2468 llvm_unreachable("unknown ASTReadResult");
2469}
2470
Richard Smith0516b182015-09-08 19:40:14 +00002471ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2472 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2473 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002474 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002475 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2476 // FIXME this drops errors on the floor.
2477 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002478 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002479 }
Richard Smith0516b182015-09-08 19:40:14 +00002480
2481 // Read all of the records in the options block.
2482 RecordData Record;
2483 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002484 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002485 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2486 if (!MaybeEntry) {
2487 // FIXME this drops errors on the floor.
2488 consumeError(MaybeEntry.takeError());
2489 return Failure;
2490 }
2491 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002492
Richard Smith0516b182015-09-08 19:40:14 +00002493 switch (Entry.Kind) {
2494 case llvm::BitstreamEntry::Error:
2495 case llvm::BitstreamEntry::SubBlock:
2496 return Failure;
2497
2498 case llvm::BitstreamEntry::EndBlock:
2499 return Result;
2500
2501 case llvm::BitstreamEntry::Record:
2502 // The interesting case.
2503 break;
2504 }
2505
2506 // Read and process a record.
2507 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002508 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2509 if (!MaybeRecordType) {
2510 // FIXME this drops errors on the floor.
2511 consumeError(MaybeRecordType.takeError());
2512 return Failure;
2513 }
2514 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002515 case LANGUAGE_OPTIONS: {
2516 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2517 if (ParseLanguageOptions(Record, Complain, Listener,
2518 AllowCompatibleConfigurationMismatch))
2519 Result = ConfigurationMismatch;
2520 break;
2521 }
2522
2523 case TARGET_OPTIONS: {
2524 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2525 if (ParseTargetOptions(Record, Complain, Listener,
2526 AllowCompatibleConfigurationMismatch))
2527 Result = ConfigurationMismatch;
2528 break;
2529 }
2530
Richard Smith0516b182015-09-08 19:40:14 +00002531 case FILE_SYSTEM_OPTIONS: {
2532 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2533 if (!AllowCompatibleConfigurationMismatch &&
2534 ParseFileSystemOptions(Record, Complain, Listener))
2535 Result = ConfigurationMismatch;
2536 break;
2537 }
2538
2539 case HEADER_SEARCH_OPTIONS: {
2540 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2541 if (!AllowCompatibleConfigurationMismatch &&
2542 ParseHeaderSearchOptions(Record, Complain, Listener))
2543 Result = ConfigurationMismatch;
2544 break;
2545 }
2546
2547 case PREPROCESSOR_OPTIONS:
2548 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2549 if (!AllowCompatibleConfigurationMismatch &&
2550 ParsePreprocessorOptions(Record, Complain, Listener,
2551 SuggestedPredefines))
2552 Result = ConfigurationMismatch;
2553 break;
2554 }
2555 }
2556}
2557
Guy Benyei11169dd2012-12-18 14:30:41 +00002558ASTReader::ASTReadResult
2559ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002560 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002561 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002563 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002564 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002565
JF Bastien0e828952019-06-26 19:50:12 +00002566 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2567 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 return Failure;
2569 }
2570
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002571 // Lambda to read the unhashed control block the first time it's called.
2572 //
2573 // For PCM files, the unhashed control block cannot be read until after the
2574 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2575 // need to look ahead before reading the IMPORTS record. For consistency,
2576 // this block is always read somehow (see BitstreamEntry::EndBlock).
2577 bool HasReadUnhashedControlBlock = false;
2578 auto readUnhashedControlBlockOnce = [&]() {
2579 if (!HasReadUnhashedControlBlock) {
2580 HasReadUnhashedControlBlock = true;
2581 if (ASTReadResult Result =
2582 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2583 return Result;
2584 }
2585 return Success;
2586 };
2587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 // Read all of the records and blocks in the control block.
2589 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002590 unsigned NumInputs = 0;
2591 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002592 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002593 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002594 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2595 if (!MaybeEntry) {
2596 Error(MaybeEntry.takeError());
2597 return Failure;
2598 }
2599 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002600
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601 switch (Entry.Kind) {
2602 case llvm::BitstreamEntry::Error:
2603 Error("malformed block record in AST file");
2604 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002605 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002606 // Validate the module before returning. This call catches an AST with
2607 // no module name and no imports.
2608 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2609 return Result;
2610
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002611 // Validate input files.
2612 const HeaderSearchOptions &HSOpts =
2613 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002614
Richard Smitha1825302014-10-23 22:18:29 +00002615 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002616 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2617 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002618 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2619 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002621
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002622 // If we are reading a module, we will create a verification timestamp,
2623 // so we verify all input files. Otherwise, verify only user input
2624 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002625
2626 unsigned N = NumUserInputs;
2627 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002628 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002629 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002630 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002631 N = NumInputs;
2632
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002633 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002634 InputFile IF = getInputFile(F, I+1, Complain);
2635 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002639
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002640 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002641 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002642
Ben Langmuircb69b572014-03-07 06:40:32 +00002643 if (Listener && Listener->needsInputFileVisitation()) {
2644 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2645 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002646 for (unsigned I = 0; I < N; ++I) {
2647 bool IsSystem = I >= NumUserInputs;
2648 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002649 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002650 F.Kind == MK_ExplicitModule ||
2651 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002652 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002653 }
2654
Richard Smith8a308ec2015-11-05 00:54:55 +00002655 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002656 }
2657
Chris Lattnere7b154b2013-01-19 21:39:22 +00002658 case llvm::BitstreamEntry::SubBlock:
2659 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 case INPUT_FILES_BLOCK_ID:
2661 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002662 if (llvm::Error Err = Stream.SkipBlock()) {
2663 Error(std::move(Err));
2664 return Failure;
2665 }
2666 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 Error("malformed block record in AST file");
2668 return Failure;
2669 }
2670 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002671
2672 case OPTIONS_BLOCK_ID:
2673 // If we're reading the first module for this group, check its options
2674 // are compatible with ours. For modules it imports, no further checking
2675 // is required, because we checked them when we built it.
2676 if (Listener && !ImportedBy) {
2677 // Should we allow the configuration of the module file to differ from
2678 // the configuration of the current translation unit in a compatible
2679 // way?
2680 //
2681 // FIXME: Allow this for files explicitly specified with -include-pch.
2682 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002683 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002684
Richard Smith8a308ec2015-11-05 00:54:55 +00002685 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2686 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002687 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002688 if (Result == Failure) {
2689 Error("malformed block record in AST file");
2690 return Result;
2691 }
2692
Richard Smith8a308ec2015-11-05 00:54:55 +00002693 if (DisableValidation ||
2694 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2695 Result = Success;
2696
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002697 // If we can't load the module, exit early since we likely
2698 // will rebuild the module anyway. The stream may be in the
2699 // middle of a block.
2700 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002701 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002702 } else if (llvm::Error Err = Stream.SkipBlock()) {
2703 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002704 return Failure;
2705 }
2706 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002707
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 default:
JF Bastien0e828952019-06-26 19:50:12 +00002709 if (llvm::Error Err = Stream.SkipBlock()) {
2710 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002711 return Failure;
2712 }
2713 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002715
Chris Lattnere7b154b2013-01-19 21:39:22 +00002716 case llvm::BitstreamEntry::Record:
2717 // The interesting case.
2718 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
2720
2721 // Read and process a record.
2722 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002724 Expected<unsigned> MaybeRecordType =
2725 Stream.readRecord(Entry.ID, Record, &Blob);
2726 if (!MaybeRecordType) {
2727 Error(MaybeRecordType.takeError());
2728 return Failure;
2729 }
2730 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 case METADATA: {
2732 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2733 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002734 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2735 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 return VersionMismatch;
2737 }
2738
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002739 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2741 Diag(diag::err_pch_with_compiler_errors);
2742 return HadErrors;
2743 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002744 if (hasErrors) {
2745 Diags.ErrorOccurred = true;
2746 Diags.UncompilableErrorOccurred = true;
2747 Diags.UnrecoverableErrorOccurred = true;
2748 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002749
2750 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002751 // Relative paths in a relocatable PCH are relative to our sysroot.
2752 if (F.RelocatablePCH)
2753 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754
Richard Smithe75ee0f2015-08-17 07:13:32 +00002755 F.HasTimestamps = Record[5];
2756
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002757 F.PCHHasObjectFile = Record[6];
2758
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002760 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2762 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002763 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 return VersionMismatch;
2765 }
2766 break;
2767 }
2768
2769 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002770 // Validate the AST before processing any imports (otherwise, untangling
2771 // them can be error-prone and expensive). A module will have a name and
2772 // will already have been validated, but this catches the PCH case.
2773 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2774 return Result;
2775
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002776 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 unsigned Idx = 0, N = Record.size();
2778 while (Idx < N) {
2779 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002780 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 // The import location will be the local one for now; we will adjust
2782 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002783 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002785 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002786 off_t StoredSize = (off_t)Record[Idx++];
2787 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002788 ASTFileSignature StoredSignature = {
2789 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2790 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2791 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002792
2793 std::string ImportedName = ReadString(Record, Idx);
2794 std::string ImportedFile;
2795
2796 // For prebuilt and explicit modules first consult the file map for
2797 // an override. Note that here we don't search prebuilt module
2798 // directories, only the explicit name to file mappings. Also, we will
2799 // still verify the size/signature making sure it is essentially the
2800 // same file but perhaps in a different location.
2801 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2802 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2803 ImportedName, /*FileMapOnly*/ true);
2804
2805 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002806 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2807 // ModuleCache as when writing.
2808 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002809 else
2810 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002811
Richard Smith0f99d6a2015-08-09 08:48:41 +00002812 // If our client can't cope with us being out of date, we can't cope with
2813 // our dependency being missing.
2814 unsigned Capabilities = ClientLoadCapabilities;
2815 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2816 Capabilities &= ~ARR_Missing;
2817
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002819 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2820 Loaded, StoredSize, StoredModTime,
2821 StoredSignature, Capabilities);
2822
2823 // If we diagnosed a problem, produce a backtrace.
2824 if (isDiagnosedResult(Result, Capabilities))
2825 Diag(diag::note_module_file_imported_by)
2826 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2827
2828 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 case Failure: return Failure;
2830 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002831 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 case OutOfDate: return OutOfDate;
2833 case VersionMismatch: return VersionMismatch;
2834 case ConfigurationMismatch: return ConfigurationMismatch;
2835 case HadErrors: return HadErrors;
2836 case Success: break;
2837 }
2838 }
2839 break;
2840 }
2841
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 case ORIGINAL_FILE:
2843 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002844 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002846 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 break;
2848
2849 case ORIGINAL_FILE_ID:
2850 F.OriginalSourceFileID = FileID::get(Record[0]);
2851 break;
2852
2853 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002854 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 break;
2856
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002857 case MODULE_NAME:
2858 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002859 Diag(diag::remark_module_import)
2860 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2861 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002862 if (Listener)
2863 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002864
2865 // Validate the AST as soon as we have a name so we can exit early on
2866 // failure.
2867 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2868 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002869
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002870 break;
2871
Richard Smith223d3f22014-12-06 03:21:08 +00002872 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002873 // Save the BaseDirectory as written in the PCM for computing the module
2874 // filename for the ModuleCache.
2875 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002876 assert(!F.ModuleName.empty() &&
2877 "MODULE_DIRECTORY found before MODULE_NAME");
2878 // If we've already loaded a module map file covering this module, we may
2879 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002880 Module *M = PP.getHeaderSearchInfo().lookupModule(
2881 F.ModuleName, /*AllowSearch*/ true,
2882 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002883 if (M && M->Directory) {
2884 // If we're implicitly loading a module, the base directory can't
2885 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002886 // Don't emit module relocation error if we have -fno-validate-pch
2887 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2888 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002889 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2890 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002891 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2892 Diag(diag::err_imported_module_relocated)
2893 << F.ModuleName << Blob << M->Directory->getName();
2894 return OutOfDate;
2895 }
2896 }
2897 F.BaseDirectory = M->Directory->getName();
2898 } else {
2899 F.BaseDirectory = Blob;
2900 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002901 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002902 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002903
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002904 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002905 if (ASTReadResult Result =
2906 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2907 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002908 break;
2909
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002910 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002911 NumInputs = Record[0];
2912 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002913 F.InputFileOffsets =
2914 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002915 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002916 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 break;
2918 }
2919 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002920}
2921
Ben Langmuir2c9af442014-04-10 17:57:43 +00002922ASTReader::ASTReadResult
2923ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002924 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002925
JF Bastien0e828952019-06-26 19:50:12 +00002926 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2927 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 // Read all of the records and blocks for the AST file.
2932 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002933 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002934 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2935 if (!MaybeEntry) {
2936 Error(MaybeEntry.takeError());
2937 return Failure;
2938 }
2939 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002940
Chris Lattnere7b154b2013-01-19 21:39:22 +00002941 switch (Entry.Kind) {
2942 case llvm::BitstreamEntry::Error:
2943 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002944 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002945 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002946 // Outside of C++, we do not store a lookup map for the translation unit.
2947 // Instead, mark it as needing a lookup map to be built if this module
2948 // contains any declarations lexically within it (which it always does!).
2949 // This usually has no cost, since we very rarely need the lookup map for
2950 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002951 if (ASTContext *Ctx = ContextObj) {
2952 DeclContext *DC = Ctx->getTranslationUnitDecl();
2953 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2954 DC->setMustBuildLookupTable();
2955 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002956
Ben Langmuir2c9af442014-04-10 17:57:43 +00002957 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002958 case llvm::BitstreamEntry::SubBlock:
2959 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 case DECLTYPES_BLOCK_ID:
2961 // We lazily load the decls block, but we want to set up the
2962 // DeclsCursor cursor to point into it. Clone our current bitcode
2963 // cursor to it, enter the block and read the abbrevs in that block.
2964 // With the main cursor, we just skip over it.
2965 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002966 if (llvm::Error Err = Stream.SkipBlock()) {
2967 Error(std::move(Err));
2968 return Failure;
2969 }
2970 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
2974 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002975
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 case PREPROCESSOR_BLOCK_ID:
2977 F.MacroCursor = Stream;
2978 if (!PP.getExternalSource())
2979 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002980
JF Bastien0e828952019-06-26 19:50:12 +00002981 if (llvm::Error Err = Stream.SkipBlock()) {
2982 Error(std::move(Err));
2983 return Failure;
2984 }
2985 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002987 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 }
2989 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2990 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002991
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 case PREPROCESSOR_DETAIL_BLOCK_ID:
2993 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002994
2995 if (llvm::Error Err = Stream.SkipBlock()) {
2996 Error(std::move(Err));
2997 return Failure;
2998 }
2999 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00003001 Error("malformed preprocessor detail record in AST file");
3002 return Failure;
3003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00003005 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003006
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 if (!PP.getPreprocessingRecord())
3008 PP.createPreprocessingRecord();
3009 if (!PP.getPreprocessingRecord()->getExternalSource())
3010 PP.getPreprocessingRecord()->SetExternalSource(*this);
3011 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003012
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 case SOURCE_MANAGER_BLOCK_ID:
3014 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003015 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003017
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00003019 if (ASTReadResult Result =
3020 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003023
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003025 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003026
3027 if (llvm::Error Err = Stream.SkipBlock()) {
3028 Error(std::move(Err));
3029 return Failure;
3030 }
3031 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
3035 CommentsCursors.push_back(std::make_pair(C, &F));
3036 break;
3037 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003038
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 default:
JF Bastien0e828952019-06-26 19:50:12 +00003040 if (llvm::Error Err = Stream.SkipBlock()) {
3041 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00003042 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003043 }
3044 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 }
3046 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003047
Chris Lattnere7b154b2013-01-19 21:39:22 +00003048 case llvm::BitstreamEntry::Record:
3049 // The interesting case.
3050 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 }
3052
3053 // Read and process a record.
3054 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003055 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003056 Expected<unsigned> MaybeRecordType =
3057 Stream.readRecord(Entry.ID, Record, &Blob);
3058 if (!MaybeRecordType) {
3059 Error(MaybeRecordType.takeError());
3060 return Failure;
3061 }
3062 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003063
3064 // If we're not loading an AST context, we don't care about most records.
3065 if (!ContextObj) {
3066 switch (RecordType) {
3067 case IDENTIFIER_TABLE:
3068 case IDENTIFIER_OFFSET:
3069 case INTERESTING_IDENTIFIERS:
3070 case STATISTICS:
3071 case PP_CONDITIONAL_STACK:
3072 case PP_COUNTER_VALUE:
3073 case SOURCE_LOCATION_OFFSETS:
3074 case MODULE_OFFSET_MAP:
3075 case SOURCE_MANAGER_LINE_TABLE:
3076 case SOURCE_LOCATION_PRELOADS:
3077 case PPD_ENTITIES_OFFSETS:
3078 case HEADER_SEARCH_TABLE:
3079 case IMPORTED_MODULES:
3080 case MACRO_OFFSET:
3081 break;
3082 default:
3083 continue;
3084 }
3085 }
3086
3087 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 default: // Default behavior: ignore.
3089 break;
3090
3091 case TYPE_OFFSET: {
3092 if (F.LocalNumTypes != 0) {
3093 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003094 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003096 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 F.LocalNumTypes = Record[0];
3098 unsigned LocalBaseTypeIndex = Record[1];
3099 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 if (F.LocalNumTypes > 0) {
3102 // Introduce the global -> local mapping for types within this module.
3103 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003104
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 // Introduce the local -> global mapping for types within this module.
3106 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003107 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003109
3110 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
3112 break;
3113 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003114
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 case DECL_OFFSET: {
3116 if (F.LocalNumDecls != 0) {
3117 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003118 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003120 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 F.LocalNumDecls = Record[0];
3122 unsigned LocalBaseDeclID = Record[1];
3123 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003124
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003126 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 // module.
3128 GlobalDeclMap.insert(
3129 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 // Introduce the local -> global mapping for declarations within this
3132 // module.
3133 F.DeclRemap.insertOrReplace(
3134 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 // Introduce the global -> local mapping for declarations within this
3137 // module.
3138 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003139
Ben Langmuir52ca6782014-10-20 16:27:32 +00003140 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 break;
3143 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003146 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003147 LexicalContents Contents(
3148 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3149 Blob.data()),
3150 static_cast<unsigned int>(Blob.size() / 4));
3151 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 TU->setHasExternalLexicalStorage(true);
3153 break;
3154 }
3155
3156 case UPDATE_VISIBLE: {
3157 unsigned Idx = 0;
3158 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003159 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003160 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003161 // If we've already loaded the decl, perform the updates when we finish
3162 // loading this block.
3163 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003164 PendingUpdateRecords.push_back(
3165 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 break;
3167 }
3168
3169 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003170 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003172 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3173 (const unsigned char *)F.IdentifierTableData + Record[0],
3174 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3175 (const unsigned char *)F.IdentifierTableData,
3176 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003177
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3179 }
3180 break;
3181
3182 case IDENTIFIER_OFFSET: {
3183 if (F.LocalNumIdentifiers != 0) {
3184 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003185 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003187 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 F.LocalNumIdentifiers = Record[0];
3189 unsigned LocalBaseIdentifierID = Record[1];
3190 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003191
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 if (F.LocalNumIdentifiers > 0) {
3193 // Introduce the global -> local mapping for identifiers within this
3194 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003195 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 // Introduce the local -> global mapping for identifiers within this
3199 // module.
3200 F.IdentifierRemap.insertOrReplace(
3201 std::make_pair(LocalBaseIdentifierID,
3202 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003203
Ben Langmuir52ca6782014-10-20 16:27:32 +00003204 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3205 + F.LocalNumIdentifiers);
3206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 break;
3208 }
3209
Richard Smith33e0f7e2015-07-22 02:08:40 +00003210 case INTERESTING_IDENTIFIERS:
3211 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3212 break;
3213
Ben Langmuir332aafe2014-01-31 01:06:56 +00003214 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003215 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3216 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003217 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003218 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003219 break;
3220
David Blaikie9ffe5a32017-01-30 05:00:26 +00003221 case MODULAR_CODEGEN_DECLS:
3222 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3223 // them (ie: if we're not codegenerating this module).
3224 if (F.Kind == MK_MainFile)
3225 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3226 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3227 break;
3228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003230 if (SpecialTypes.empty()) {
3231 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3232 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3233 break;
3234 }
3235
3236 if (SpecialTypes.size() != Record.size()) {
3237 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003238 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003239 }
3240
3241 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3242 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3243 if (!SpecialTypes[I])
3244 SpecialTypes[I] = ID;
3245 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3246 // merge step?
3247 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 break;
3249
3250 case STATISTICS:
3251 TotalNumStatements += Record[0];
3252 TotalNumMacros += Record[1];
3253 TotalLexicalDeclContexts += Record[2];
3254 TotalVisibleDeclContexts += Record[3];
3255 break;
3256
3257 case UNUSED_FILESCOPED_DECLS:
3258 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3259 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3260 break;
3261
3262 case DELEGATING_CTORS:
3263 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3264 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3265 break;
3266
3267 case WEAK_UNDECLARED_IDENTIFIERS:
3268 if (Record.size() % 4 != 0) {
3269 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003270 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003272
3273 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 // files. This isn't the way to do it :)
3275 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 // Translate the weak, undeclared identifiers into global IDs.
3278 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3279 WeakUndeclaredIdentifiers.push_back(
3280 getGlobalIdentifierID(F, Record[I++]));
3281 WeakUndeclaredIdentifiers.push_back(
3282 getGlobalIdentifierID(F, Record[I++]));
3283 WeakUndeclaredIdentifiers.push_back(
3284 ReadSourceLocation(F, Record, I).getRawEncoding());
3285 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3286 }
3287 break;
3288
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003290 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 F.LocalNumSelectors = Record[0];
3292 unsigned LocalBaseSelectorID = Record[1];
3293 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003296 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 // module.
3298 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003299
3300 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 // module.
3302 F.SelectorRemap.insertOrReplace(
3303 std::make_pair(LocalBaseSelectorID,
3304 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003305
3306 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 }
3308 break;
3309 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003310
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003312 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 if (Record[0])
3314 F.SelectorLookupTable
3315 = ASTSelectorLookupTable::Create(
3316 F.SelectorLookupTableData + Record[0],
3317 F.SelectorLookupTableData,
3318 ASTSelectorLookupTrait(*this, F));
3319 TotalNumMethodPoolEntries += Record[1];
3320 break;
3321
3322 case REFERENCED_SELECTOR_POOL:
3323 if (!Record.empty()) {
3324 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003325 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 Record[Idx++]));
3327 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3328 getRawEncoding());
3329 }
3330 }
3331 break;
3332
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003333 case PP_CONDITIONAL_STACK:
3334 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003335 unsigned Idx = 0, End = Record.size() - 1;
3336 bool ReachedEOFWhileSkipping = Record[Idx++];
3337 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3338 if (ReachedEOFWhileSkipping) {
3339 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3340 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3341 bool FoundNonSkipPortion = Record[Idx++];
3342 bool FoundElse = Record[Idx++];
3343 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3344 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3345 FoundElse, ElseLoc);
3346 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003347 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003348 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003349 auto Loc = ReadSourceLocation(F, Record, Idx);
3350 bool WasSkipping = Record[Idx++];
3351 bool FoundNonSkip = Record[Idx++];
3352 bool FoundElse = Record[Idx++];
3353 ConditionalStack.push_back(
3354 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3355 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003356 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003357 }
3358 break;
3359
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 case PP_COUNTER_VALUE:
3361 if (!Record.empty() && Listener)
3362 Listener->ReadCounter(F, Record[0]);
3363 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003366 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 F.NumFileSortedDecls = Record[0];
3368 break;
3369
3370 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003371 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 F.LocalNumSLocEntries = Record[0];
3373 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003374 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003375 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003377 if (!F.SLocEntryBaseID) {
3378 Error("ran out of source locations");
3379 break;
3380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 // Make our entry in the range map. BaseID is negative and growing, so
3382 // we invert it. Because we invert it, though, we need the other end of
3383 // the range.
3384 unsigned RangeStart =
3385 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3386 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3387 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3388
3389 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3390 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3391 GlobalSLocOffsetMap.insert(
3392 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3393 - SLocSpaceSize,&F));
3394
3395 // Initialize the remapping table.
3396 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003397 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003399 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 TotalNumSLocEntries += F.LocalNumSLocEntries;
3403 break;
3404 }
3405
Richard Smith37a93df2017-02-18 00:32:02 +00003406 case MODULE_OFFSET_MAP:
3407 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003409
3410 case SOURCE_MANAGER_LINE_TABLE:
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003411 if (ParseLineTable(F, Record)) {
3412 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003413 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003414 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 break;
3416
3417 case SOURCE_LOCATION_PRELOADS: {
3418 // Need to transform from the local view (1-based IDs) to the global view,
3419 // which is based off F.SLocEntryBaseID.
3420 if (!F.PreloadSLocEntries.empty()) {
3421 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003422 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003424
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 F.PreloadSLocEntries.swap(Record);
3426 break;
3427 }
3428
3429 case EXT_VECTOR_DECLS:
3430 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3431 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3432 break;
3433
3434 case VTABLE_USES:
3435 if (Record.size() % 3 != 0) {
3436 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003437 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003439
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 // Later tables overwrite earlier ones.
3441 // FIXME: Modules will have some trouble with this. This is clearly not
3442 // the right way to do this.
3443 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003444
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3446 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3447 VTableUses.push_back(
3448 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3449 VTableUses.push_back(Record[Idx++]);
3450 }
3451 break;
3452
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 case PENDING_IMPLICIT_INSTANTIATIONS:
3454 if (PendingInstantiations.size() % 2 != 0) {
3455 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003456 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 }
3458
3459 if (Record.size() % 2 != 0) {
3460 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003461 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 }
3463
3464 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3465 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3466 PendingInstantiations.push_back(
3467 ReadSourceLocation(F, Record, I).getRawEncoding());
3468 }
3469 break;
3470
3471 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003472 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003473 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003474 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003475 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3477 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3478 break;
3479
3480 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003481 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3482 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3483 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003484
3485 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003486
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 unsigned StartingID;
3488 if (!PP.getPreprocessingRecord())
3489 PP.createPreprocessingRecord();
3490 if (!PP.getPreprocessingRecord()->getExternalSource())
3491 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003492 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003494 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 F.BasePreprocessedEntityID = StartingID;
3496
3497 if (F.NumPreprocessedEntities > 0) {
3498 // Introduce the global -> local mapping for preprocessed entities in
3499 // this module.
3500 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 // Introduce the local -> global mapping for preprocessed entities in
3503 // this module.
3504 F.PreprocessedEntityRemap.insertOrReplace(
3505 std::make_pair(LocalBasePreprocessedEntityID,
3506 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3507 }
3508
3509 break;
3510 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003511
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003512 case PPD_SKIPPED_RANGES: {
3513 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3514 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3515 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3516
3517 if (!PP.getPreprocessingRecord())
3518 PP.createPreprocessingRecord();
3519 if (!PP.getPreprocessingRecord()->getExternalSource())
3520 PP.getPreprocessingRecord()->SetExternalSource(*this);
3521 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3522 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003523
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003524 if (F.NumPreprocessedSkippedRanges > 0)
3525 GlobalSkippedRangeMap.insert(
3526 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3527 break;
3528 }
3529
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003530 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 if (Record.size() % 2 != 0) {
3532 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003533 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003535 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3536 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3537 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3538
3539 // If we've already loaded the decl, perform the updates when we finish
3540 // loading this block.
3541 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003542 PendingUpdateRecords.push_back(
3543 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003546
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003547 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003548 if (F.LocalNumObjCCategoriesInMap != 0) {
3549 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003550 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003552
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003554 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003556
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 case OBJC_CATEGORIES:
3558 F.ObjCCategories.swap(Record);
3559 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003560
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 case CUDA_SPECIAL_DECL_REFS:
3562 // Later tables overwrite earlier ones.
3563 // FIXME: Modules will have trouble with this.
3564 CUDASpecialDeclRefs.clear();
3565 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3566 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3567 break;
3568
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003569 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003570 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003571 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 if (Record[0]) {
3573 F.HeaderFileInfoTable
3574 = HeaderFileInfoLookupTable::Create(
3575 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3576 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003577 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003579 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003580
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 PP.getHeaderSearchInfo().SetExternalSource(this);
3582 if (!PP.getHeaderSearchInfo().getExternalLookup())
3583 PP.getHeaderSearchInfo().SetExternalLookup(this);
3584 }
3585 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003586
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 case FP_PRAGMA_OPTIONS:
3588 // Later tables overwrite earlier ones.
3589 FPPragmaOptions.swap(Record);
3590 break;
3591
3592 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003593 for (unsigned I = 0, E = Record.size(); I != E; ) {
3594 auto Name = ReadString(Record, I);
3595 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003596 Opt.Supported = Record[I++] != 0;
3597 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003598 Opt.Avail = Record[I++];
3599 Opt.Core = Record[I++];
3600 }
3601 break;
3602
3603 case OPENCL_EXTENSION_TYPES:
3604 for (unsigned I = 0, E = Record.size(); I != E;) {
3605 auto TypeID = static_cast<::TypeID>(Record[I++]);
3606 auto *Type = GetType(TypeID).getTypePtr();
3607 auto NumExt = static_cast<unsigned>(Record[I++]);
3608 for (unsigned II = 0; II != NumExt; ++II) {
3609 auto Ext = ReadString(Record, I);
3610 OpenCLTypeExtMap[Type].insert(Ext);
3611 }
3612 }
3613 break;
3614
3615 case OPENCL_EXTENSION_DECLS:
3616 for (unsigned I = 0, E = Record.size(); I != E;) {
3617 auto DeclID = static_cast<::DeclID>(Record[I++]);
3618 auto *Decl = GetDecl(DeclID);
3619 auto NumExt = static_cast<unsigned>(Record[I++]);
3620 for (unsigned II = 0; II != NumExt; ++II) {
3621 auto Ext = ReadString(Record, I);
3622 OpenCLDeclExtMap[Decl].insert(Ext);
3623 }
3624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 break;
3626
3627 case TENTATIVE_DEFINITIONS:
3628 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3629 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3630 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003631
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 case KNOWN_NAMESPACES:
3633 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3634 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3635 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003636
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003637 case UNDEFINED_BUT_USED:
3638 if (UndefinedButUsed.size() % 2 != 0) {
3639 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003640 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003641 }
3642
3643 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003644 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003645 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003646 }
3647 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003648 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3649 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003650 ReadSourceLocation(F, Record, I).getRawEncoding());
3651 }
3652 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003653
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003654 case DELETE_EXPRS_TO_ANALYZE:
3655 for (unsigned I = 0, N = Record.size(); I != N;) {
3656 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3657 const uint64_t Count = Record[I++];
3658 DelayedDeleteExprs.push_back(Count);
3659 for (uint64_t C = 0; C < Count; ++C) {
3660 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3661 bool IsArrayForm = Record[I++] == 1;
3662 DelayedDeleteExprs.push_back(IsArrayForm);
3663 }
3664 }
3665 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003666
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003667 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003668 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 // If we aren't loading a module (which has its own exports), make
3670 // all of the imported modules visible.
3671 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003672 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3673 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3674 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003675 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003676 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003677 if (DeserializationListener)
3678 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3679 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 }
3681 }
3682 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003683
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 case MACRO_OFFSET: {
3685 if (F.LocalNumMacros != 0) {
3686 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003687 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003689 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 F.LocalNumMacros = Record[0];
3691 unsigned LocalBaseMacroID = Record[1];
3692 F.BaseMacroID = getTotalNumMacros();
3693
3694 if (F.LocalNumMacros > 0) {
3695 // Introduce the global -> local mapping for macros within this module.
3696 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3697
3698 // Introduce the local -> global mapping for macros within this module.
3699 F.MacroRemap.insertOrReplace(
3700 std::make_pair(LocalBaseMacroID,
3701 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003702
3703 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 }
3705 break;
3706 }
3707
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003708 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003709 LateParsedTemplates.append(Record.begin(), Record.end());
3710 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003711
3712 case OPTIMIZE_PRAGMA_OPTIONS:
3713 if (Record.size() != 1) {
3714 Error("invalid pragma optimize record");
3715 return Failure;
3716 }
3717 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3718 break;
Nico Weber72889432014-09-06 01:25:55 +00003719
Nico Weber779355f2016-03-02 23:22:00 +00003720 case MSSTRUCT_PRAGMA_OPTIONS:
3721 if (Record.size() != 1) {
3722 Error("invalid pragma ms_struct record");
3723 return Failure;
3724 }
3725 PragmaMSStructState = Record[0];
3726 break;
3727
Nico Weber42932312016-03-03 00:17:35 +00003728 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3729 if (Record.size() != 2) {
3730 Error("invalid pragma ms_struct record");
3731 return Failure;
3732 }
3733 PragmaMSPointersToMembersState = Record[0];
3734 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3735 break;
3736
Nico Weber72889432014-09-06 01:25:55 +00003737 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3738 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3739 UnusedLocalTypedefNameCandidates.push_back(
3740 getGlobalDeclID(F, Record[I]));
3741 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003742
3743 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3744 if (Record.size() != 1) {
3745 Error("invalid cuda pragma options record");
3746 return Failure;
3747 }
3748 ForceCUDAHostDeviceDepth = Record[0];
3749 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003750
3751 case PACK_PRAGMA_OPTIONS: {
3752 if (Record.size() < 3) {
3753 Error("invalid pragma pack record");
3754 return Failure;
3755 }
3756 PragmaPackCurrentValue = Record[0];
3757 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3758 unsigned NumStackEntries = Record[2];
3759 unsigned Idx = 3;
3760 // Reset the stack when importing a new module.
3761 PragmaPackStack.clear();
3762 for (unsigned I = 0; I < NumStackEntries; ++I) {
3763 PragmaPackStackEntry Entry;
3764 Entry.Value = Record[Idx++];
3765 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003766 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003767 PragmaPackStrings.push_back(ReadString(Record, Idx));
3768 Entry.SlotLabel = PragmaPackStrings.back();
3769 PragmaPackStack.push_back(Entry);
3770 }
3771 break;
3772 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 }
3774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003775}
3776
Richard Smith37a93df2017-02-18 00:32:02 +00003777void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3778 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3779
3780 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003781 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003782 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3783 F.ModuleOffsetMap = StringRef();
3784
3785 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3786 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3787 F.SLocRemap.insert(std::make_pair(0U, 0));
3788 F.SLocRemap.insert(std::make_pair(2U, 1));
3789 }
3790
3791 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003792 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003793 RemapBuilder SLocRemap(F.SLocRemap);
3794 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3795 RemapBuilder MacroRemap(F.MacroRemap);
3796 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3797 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3798 RemapBuilder SelectorRemap(F.SelectorRemap);
3799 RemapBuilder DeclRemap(F.DeclRemap);
3800 RemapBuilder TypeRemap(F.TypeRemap);
3801
3802 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003803 // FIXME: Looking up dependency modules by filename is horrible. Let's
3804 // start fixing this with prebuilt and explicit modules and see how it
3805 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003806 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003807 ModuleKind Kind = static_cast<ModuleKind>(
3808 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003809 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3810 StringRef Name = StringRef((const char*)Data, Len);
3811 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003812 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3813 ? ModuleMgr.lookupByModuleName(Name)
3814 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003815 if (!OM) {
3816 std::string Msg =
3817 "SourceLocation remap refers to unknown module, cannot find ";
3818 Msg.append(Name);
3819 Error(Msg);
3820 return;
3821 }
3822
3823 uint32_t SLocOffset =
3824 endian::readNext<uint32_t, little, unaligned>(Data);
3825 uint32_t IdentifierIDOffset =
3826 endian::readNext<uint32_t, little, unaligned>(Data);
3827 uint32_t MacroIDOffset =
3828 endian::readNext<uint32_t, little, unaligned>(Data);
3829 uint32_t PreprocessedEntityIDOffset =
3830 endian::readNext<uint32_t, little, unaligned>(Data);
3831 uint32_t SubmoduleIDOffset =
3832 endian::readNext<uint32_t, little, unaligned>(Data);
3833 uint32_t SelectorIDOffset =
3834 endian::readNext<uint32_t, little, unaligned>(Data);
3835 uint32_t DeclIDOffset =
3836 endian::readNext<uint32_t, little, unaligned>(Data);
3837 uint32_t TypeIndexOffset =
3838 endian::readNext<uint32_t, little, unaligned>(Data);
3839
3840 uint32_t None = std::numeric_limits<uint32_t>::max();
3841
3842 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3843 RemapBuilder &Remap) {
3844 if (Offset != None)
3845 Remap.insert(std::make_pair(Offset,
3846 static_cast<int>(BaseOffset - Offset)));
3847 };
3848 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3849 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3850 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3851 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3852 PreprocessedEntityRemap);
3853 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3854 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3855 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3856 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3857
3858 // Global -> local mappings.
3859 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3860 }
3861}
3862
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003863ASTReader::ASTReadResult
3864ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3865 const ModuleFile *ImportedBy,
3866 unsigned ClientLoadCapabilities) {
3867 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003868 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003869
3870 // Try to resolve ModuleName in the current header search context and
3871 // verify that it is found in the same module map file as we saved. If the
3872 // top-level AST file is a main file, skip this check because there is no
3873 // usable header search context.
3874 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003875 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003876 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003877 // An implicitly-loaded module file should have its module listed in some
3878 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003879 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003880 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3881 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003882 // Don't emit module relocation error if we have -fno-validate-pch
3883 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003884 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003885 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003886 // This module was defined by an imported (explicit) module.
3887 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3888 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003889 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003890 // This module was built with a different module map.
3891 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003892 << F.ModuleName << F.FileName
3893 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3894 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003895 // In case it was imported by a PCH, there's a chance the user is
3896 // just missing to include the search path to the directory containing
3897 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003898 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003899 Diag(diag::note_imported_by_pch_module_not_found)
3900 << llvm::sys::path::parent_path(F.ModuleMapPath);
3901 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003902 }
3903 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003904 }
3905
Richard Smithe842a472014-10-22 02:05:46 +00003906 assert(M->Name == F.ModuleName && "found module with different name");
3907
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003908 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003909 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3910 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003911 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003912 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3913 "top-level import should be verified");
3914 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003915 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3916 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003917 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3918 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003919 return OutOfDate;
3920 }
3921
3922 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3923 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3924 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003925 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003926 auto F = FileMgr.getFile(Filename, false, false);
3927 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003928 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3929 Error("could not find file '" + Filename +"' referenced by AST file");
3930 return OutOfDate;
3931 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003932 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003933 }
3934
3935 // Check any additional module map files (e.g. module.private.modulemap)
3936 // that are not in the pcm.
3937 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003938 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003939 // Remove files that match
3940 // Note: SmallPtrSet::erase is really remove
3941 if (!AdditionalStoredMaps.erase(ModMap)) {
3942 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3943 Diag(diag::err_module_different_modmap)
3944 << F.ModuleName << /*new*/0 << ModMap->getName();
3945 return OutOfDate;
3946 }
3947 }
3948 }
3949
3950 // Check any additional module map files that are in the pcm, but not
3951 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003952 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003953 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3954 Diag(diag::err_module_different_modmap)
3955 << F.ModuleName << /*not new*/1 << ModMap->getName();
3956 return OutOfDate;
3957 }
3958 }
3959
3960 if (Listener)
3961 Listener->ReadModuleMapFile(F.ModuleMapPath);
3962 return Success;
3963}
3964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003965/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003966static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3967 // Find the entry for this selector in the method pool.
3968 Sema::GlobalMethodPool::iterator Known
3969 = S.MethodPool.find(Method->getSelector());
3970 if (Known == S.MethodPool.end())
3971 return;
3972
3973 // Retrieve the appropriate method list.
3974 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3975 : Known->second.second;
3976 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003977 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003978 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003979 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003980 Found = true;
3981 } else {
3982 // Keep searching.
3983 continue;
3984 }
3985 }
3986
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003987 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003988 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003989 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003990 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003991 }
3992}
3993
Richard Smithde711422015-04-23 21:20:19 +00003994void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003995 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003996 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003997 bool wasHidden = D->isHidden();
3998 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003999
Vedant Kumar48b4f762018-04-14 01:40:48 +00004000 if (wasHidden && SemaObj) {
4001 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004002 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004003 }
4004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 }
4006}
4007
Richard Smith49f906a2014-03-01 00:08:04 +00004008void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004009 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004010 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004012 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004013 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004015 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004016
4017 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004018 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 // there is nothing more to do.
4020 continue;
4021 }
Richard Smith49f906a2014-03-01 00:08:04 +00004022
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 if (!Mod->isAvailable()) {
4024 // Modules that aren't available cannot be made visible.
4025 continue;
4026 }
4027
4028 // Update the module's name visibility.
4029 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004030
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 // If we've already deserialized any names from this module,
4032 // mark them as visible.
4033 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4034 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004035 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004037 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004038 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4039 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004041
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004043 SmallVector<Module *, 16> Exports;
4044 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004045 for (SmallVectorImpl<Module *>::iterator
4046 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4047 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004048 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004049 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 }
4052}
4053
Richard Smith6561f922016-09-12 21:06:40 +00004054/// We've merged the definition \p MergedDef into the existing definition
4055/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4056/// visible.
4057void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4058 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004059 if (Def->isHidden()) {
4060 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004061 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004062 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004063 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004064 getContext().mergeDefinitionIntoModule(
4065 Def, MergedDef->getImportedOwningModule(),
4066 /*NotifyListeners*/ false);
4067 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004068 }
Richard Smith6561f922016-09-12 21:06:40 +00004069 }
4070}
4071
Douglas Gregore060e572013-01-25 01:03:03 +00004072bool ASTReader::loadGlobalIndex() {
4073 if (GlobalIndex)
4074 return false;
4075
4076 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004077 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004078 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004079
Douglas Gregore060e572013-01-25 01:03:03 +00004080 // Try to load the global index.
4081 TriedLoadingGlobalIndex = true;
4082 StringRef ModuleCachePath
4083 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004084 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4085 GlobalModuleIndex::readIndex(ModuleCachePath);
4086 if (llvm::Error Err = std::move(Result.second)) {
4087 assert(!Result.first);
4088 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004089 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004090 }
Douglas Gregore060e572013-01-25 01:03:03 +00004091
4092 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004093 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004094 return false;
4095}
4096
4097bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004098 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004099 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4100}
4101
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004102static void updateModuleTimestamp(ModuleFile &MF) {
4103 // Overwrite the timestamp file contents so that file's mtime changes.
4104 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004105 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004106 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004107 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004108 return;
4109 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004110 OS.close();
4111 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004112}
4113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004114/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004115/// cursor into the start of the given block ID, returning false on success and
4116/// true on failure.
4117static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004118 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004119 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4120 if (!MaybeEntry) {
4121 // FIXME this drops errors on the floor.
4122 consumeError(MaybeEntry.takeError());
4123 return true;
4124 }
4125 llvm::BitstreamEntry Entry = MaybeEntry.get();
4126
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004127 switch (Entry.Kind) {
4128 case llvm::BitstreamEntry::Error:
4129 case llvm::BitstreamEntry::EndBlock:
4130 return true;
4131
4132 case llvm::BitstreamEntry::Record:
4133 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004134 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4135 break;
4136 else {
4137 // FIXME this drops errors on the floor.
4138 consumeError(Skipped.takeError());
4139 return true;
4140 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004141
4142 case llvm::BitstreamEntry::SubBlock:
4143 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004144 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4145 // FIXME this drops the error on the floor.
4146 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004147 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004148 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004149 // Found it!
4150 return false;
4151 }
4152
JF Bastien0e828952019-06-26 19:50:12 +00004153 if (llvm::Error Err = Cursor.SkipBlock()) {
4154 // FIXME this drops the error on the floor.
4155 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004156 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004157 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004158 }
4159 }
4160}
4161
Benjamin Kramer0772c422016-02-13 13:42:54 +00004162ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 ModuleKind Type,
4164 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004165 unsigned ClientLoadCapabilities,
4166 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004167 llvm::SaveAndRestore<SourceLocation>
4168 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4169
Richard Smithd1c46742014-04-30 02:24:17 +00004170 // Defer any pending actions until we get to the end of reading the AST file.
4171 Deserializing AnASTFile(this);
4172
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004174 unsigned PreviousGeneration = 0;
4175 if (ContextObj)
4176 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
4178 unsigned NumModules = ModuleMgr.size();
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004179 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4180 assert(ReadResult && "expected to return error");
Duncan P. N. Exon Smith8e9e4332019-11-10 10:31:03 -08004181 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004182 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004183 ? &PP.getHeaderSearchInfo().getModuleMap()
4184 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004185
4186 // If we find that any modules are unusable, the global index is going
4187 // to be out-of-date. Just remove it.
4188 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004189 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 return ReadResult;
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004191 };
4192
4193 SmallVector<ImportedModule, 4> Loaded;
4194 switch (ASTReadResult ReadResult =
4195 ReadASTCore(FileName, Type, ImportLoc,
4196 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4197 ASTFileSignature(), ClientLoadCapabilities)) {
4198 case Failure:
4199 case Missing:
4200 case OutOfDate:
4201 case VersionMismatch:
4202 case ConfigurationMismatch:
4203 case HadErrors:
4204 return removeModulesAndReturn(ReadResult);
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 case Success:
4206 break;
4207 }
4208
4209 // Here comes stuff that we only do once the entire chain is loaded.
4210
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004211 // Load the AST blocks of all of the modules that we loaded. We can still
4212 // hit errors parsing the ASTs at this point.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004213 for (ImportedModule &M : Loaded) {
4214 ModuleFile &F = *M.Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004215
4216 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004217 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004218 return removeModulesAndReturn(Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00004219
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004220 // Read the extension blocks.
4221 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4222 if (ASTReadResult Result = ReadExtensionBlock(F))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004223 return removeModulesAndReturn(Result);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004224 }
4225
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004226 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 // bits of all files we've seen.
4228 F.GlobalBitOffset = TotalModulesSizeInBits;
4229 TotalModulesSizeInBits += F.SizeInBits;
4230 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004231 }
4232
4233 // Preload source locations and interesting indentifiers.
4234 for (ImportedModule &M : Loaded) {
4235 ModuleFile &F = *M.Mod;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004236
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004238 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4239 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 // Load it through the SourceManager and don't call ReadSLocEntry()
4241 // directly because the entry may have already been loaded in which case
4242 // calling ReadSLocEntry() directly would trigger an assertion in
4243 // SourceManager.
4244 SourceMgr.getLoadedSLocEntryByID(Index);
4245 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004246
Richard Smithea741482017-05-01 22:10:47 +00004247 // Map the original source file ID into the ID space of the current
4248 // compilation.
4249 if (F.OriginalSourceFileID.isValid()) {
4250 F.OriginalSourceFileID = FileID::get(
4251 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4252 }
4253
Richard Smith33e0f7e2015-07-22 02:08:40 +00004254 // Preload all the pending interesting identifiers by marking them out of
4255 // date.
4256 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004257 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004258 F.IdentifierTableData + Offset);
4259
4260 ASTIdentifierLookupTrait Trait(*this, F);
4261 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4262 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004263 auto &II = PP.getIdentifierTable().getOwn(Key);
4264 II.setOutOfDate(true);
4265
4266 // Mark this identifier as being from an AST file so that we can track
4267 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004268 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004269
4270 // Associate the ID with the identifier so that the writer can reuse it.
4271 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4272 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004273 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 }
4275
Douglas Gregor603cd862013-03-22 18:50:14 +00004276 // Setup the import locations and notify the module manager that we've
4277 // committed to these module files.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004278 for (ImportedModule &M : Loaded) {
4279 ModuleFile &F = *M.Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004280
4281 ModuleMgr.moduleFileAccepted(&F);
4282
4283 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004284 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004285 // FIXME: We assume that locations from PCH / preamble do not need
4286 // any translation.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004287 if (!M.ImportedBy)
4288 F.ImportLoc = M.ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 else
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004290 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 }
4292
Richard Smithdbafb6c2017-06-29 23:23:46 +00004293 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004294 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4295 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004296 // Mark all of the identifiers in the identifier table as being out of date,
4297 // so that various accessors know to check the loaded modules when the
4298 // identifier is used.
4299 //
4300 // For C++ modules, we don't need information on many identifiers (just
4301 // those that provide macros or are poisoned), so we mark all of
4302 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004303 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4304 IdEnd = PP.getIdentifierTable().end();
4305 Id != IdEnd; ++Id)
4306 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004307 }
Manman Rena0f31a02016-04-29 19:04:05 +00004308 // Mark selectors as out of date.
4309 for (auto Sel : SelectorGeneration)
4310 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004311
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004313 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4314 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4316 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004317
4318 switch (Unresolved.Kind) {
4319 case UnresolvedModuleRef::Conflict:
4320 if (ResolvedMod) {
4321 Module::Conflict Conflict;
4322 Conflict.Other = ResolvedMod;
4323 Conflict.Message = Unresolved.String.str();
4324 Unresolved.Mod->Conflicts.push_back(Conflict);
4325 }
4326 continue;
4327
4328 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004330 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004332
Douglas Gregorfb912652013-03-20 21:10:35 +00004333 case UnresolvedModuleRef::Export:
4334 if (ResolvedMod || Unresolved.IsWildcard)
4335 Unresolved.Mod->Exports.push_back(
4336 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4337 continue;
4338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004340 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004341
Graydon Hoaree7196af2016-12-09 21:45:49 +00004342 if (Imported)
4343 Imported->append(ImportedModules.begin(),
4344 ImportedModules.end());
4345
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004346 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4347 // Might be unnecessary as use declarations are only used to build the
4348 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004349
Richard Smithdbafb6c2017-06-29 23:23:46 +00004350 if (ContextObj)
4351 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004352
Richard Smith3d8e97e2013-10-18 06:54:39 +00004353 if (SemaObj)
4354 UpdateSema();
4355
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (DeserializationListener)
4357 DeserializationListener->ReaderInitialized(this);
4358
4359 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004360 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 // If this AST file is a precompiled preamble, then set the
4362 // preamble file ID of the source manager to the file source file
4363 // from which the preamble was built.
4364 if (Type == MK_Preamble) {
4365 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4366 } else if (Type == MK_MainFile) {
4367 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4368 }
4369 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004370
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 // For any Objective-C class definitions we have already loaded, make sure
4372 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004373 if (ContextObj) {
4374 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4375 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4376 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004377 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004378 }
4379 }
Douglas Gregore060e572013-01-25 01:03:03 +00004380
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004381 if (PP.getHeaderSearchInfo()
4382 .getHeaderSearchOpts()
4383 .ModulesValidateOncePerBuildSession) {
4384 // Now we are certain that the module and all modules it depends on are
4385 // up to date. Create or update timestamp files for modules that are
4386 // located in the module cache (not for PCH files that could be anywhere
4387 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004388 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4389 ImportedModule &M = Loaded[I];
4390 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004391 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004392 }
4393 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004394 }
4395
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 return Success;
4397}
4398
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004399static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004400
JF Bastien0e828952019-06-26 19:50:12 +00004401/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4402static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4403 // FIXME checking magic headers is done in other places such as
4404 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4405 // always done the same. Unify it all with a helper.
4406 if (!Stream.canSkipToPos(4))
4407 return llvm::createStringError(std::errc::illegal_byte_sequence,
4408 "file too small to contain AST file magic");
4409 for (unsigned C : {'C', 'P', 'C', 'H'})
4410 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4411 if (Res.get() != C)
4412 return llvm::createStringError(
4413 std::errc::illegal_byte_sequence,
4414 "file doesn't start with AST file magic");
4415 } else
4416 return Res.takeError();
4417 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004418}
4419
Richard Smith0f99d6a2015-08-09 08:48:41 +00004420static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4421 switch (Kind) {
4422 case MK_PCH:
4423 return 0; // PCH
4424 case MK_ImplicitModule:
4425 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004426 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004427 return 1; // module
4428 case MK_MainFile:
4429 case MK_Preamble:
4430 return 2; // main source file
4431 }
4432 llvm_unreachable("unknown module kind");
4433}
4434
Guy Benyei11169dd2012-12-18 14:30:41 +00004435ASTReader::ASTReadResult
4436ASTReader::ReadASTCore(StringRef FileName,
4437 ModuleKind Type,
4438 SourceLocation ImportLoc,
4439 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004440 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004441 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004442 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 unsigned ClientLoadCapabilities) {
4444 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004446 ModuleManager::AddModuleResult AddResult
4447 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004448 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004449 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004450 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
Douglas Gregor7029ce12013-03-19 00:28:20 +00004452 switch (AddResult) {
4453 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004454 Diag(diag::remark_module_import)
4455 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4456 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004457 return Success;
4458
4459 case ModuleManager::NewlyLoaded:
4460 // Load module file below.
4461 break;
4462
4463 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004464 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004465 // it.
4466 if (ClientLoadCapabilities & ARR_Missing)
4467 return Missing;
4468
4469 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004470 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004471 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004472 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004473 return Failure;
4474
4475 case ModuleManager::OutOfDate:
4476 // We couldn't load the module file because it is out-of-date. If the
4477 // client can handle out-of-date, return it.
4478 if (ClientLoadCapabilities & ARR_OutOfDate)
4479 return OutOfDate;
4480
4481 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004482 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004483 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004484 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 return Failure;
4486 }
4487
Douglas Gregor7029ce12013-03-19 00:28:20 +00004488 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004489
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004490 bool ShouldFinalizePCM = false;
4491 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4492 auto &MC = getModuleManager().getModuleCache();
4493 if (ShouldFinalizePCM)
4494 MC.finalizePCM(FileName);
4495 else
4496 MC.tryToDropPCM(FileName);
4497 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004499 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004500 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004501 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004502
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004504 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4505 Diag(diag::err_module_file_invalid)
4506 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 return Failure;
4508 }
4509
4510 // This is used for compatibility with older PCH formats.
4511 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004512 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004513 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4514 if (!MaybeEntry) {
4515 Error(MaybeEntry.takeError());
4516 return Failure;
4517 }
4518 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004519
Chris Lattnerefa77172013-01-20 00:00:22 +00004520 switch (Entry.Kind) {
4521 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004522 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004523 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 Error("invalid record at top-level of AST file");
4525 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004526
Chris Lattnerefa77172013-01-20 00:00:22 +00004527 case llvm::BitstreamEntry::SubBlock:
4528 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
Chris Lattnerefa77172013-01-20 00:00:22 +00004531 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 case CONTROL_BLOCK_ID:
4533 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004534 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004536 // Check that we didn't try to load a non-module AST file as a module.
4537 //
4538 // FIXME: Should we also perform the converse check? Loading a module as
4539 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004540 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4541 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004542 F.ModuleName.empty()) {
4543 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4544 if (Result != OutOfDate ||
4545 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4546 Diag(diag::err_module_file_not_module) << FileName;
4547 return Result;
4548 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 break;
4550
4551 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004552 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 case OutOfDate: return OutOfDate;
4554 case VersionMismatch: return VersionMismatch;
4555 case ConfigurationMismatch: return ConfigurationMismatch;
4556 case HadErrors: return HadErrors;
4557 }
4558 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004559
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 case AST_BLOCK_ID:
4561 if (!HaveReadControlBlock) {
4562 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004563 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 return VersionMismatch;
4565 }
4566
4567 // Record that we've loaded this module.
4568 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004569 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 return Success;
4571
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004572 case UNHASHED_CONTROL_BLOCK_ID:
4573 // This block is handled using look-ahead during ReadControlBlock. We
4574 // shouldn't get here!
4575 Error("malformed block record in AST file");
4576 return Failure;
4577
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 default:
JF Bastien0e828952019-06-26 19:50:12 +00004579 if (llvm::Error Err = Stream.SkipBlock()) {
4580 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 return Failure;
4582 }
4583 break;
4584 }
4585 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004586
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004587 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004588}
4589
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004590ASTReader::ASTReadResult
4591ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4592 unsigned ClientLoadCapabilities) {
4593 const HeaderSearchOptions &HSOpts =
4594 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4595 bool AllowCompatibleConfigurationMismatch =
4596 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4597
4598 ASTReadResult Result = readUnhashedControlBlockImpl(
4599 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4600 Listener.get(),
4601 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4602
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004603 // If F was directly imported by another module, it's implicitly validated by
4604 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004605 if (DisableValidation || WasImportedBy ||
4606 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4607 return Success;
4608
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004609 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004610 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004611 return Failure;
4612 }
4613
4614 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004615 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004616 // with it; we can only load a single version of each module.
4617 //
4618 // This can happen when a module is imported in two contexts: in one, as a
4619 // user module; in another, as a system module (due to an import from
4620 // another module marked with the [system] flag). It usually indicates a
4621 // bug in the module map: this module should also be marked with [system].
4622 //
4623 // If -Wno-system-headers (the default), and the first import is as a
4624 // system module, then validation will fail during the as-user import,
4625 // since -Werror flags won't have been validated. However, it's reasonable
4626 // to treat this consistently as a system module.
4627 //
4628 // If -Wsystem-headers, the PCM on disk was built with
4629 // -Wno-system-headers, and the first import is as a user module, then
4630 // validation will fail during the as-system import since the PCM on disk
4631 // doesn't guarantee that -Werror was respected. However, the -Werror
4632 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004633 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004634 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4635 return Success;
4636 }
4637 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004638
4639 return Result;
4640}
4641
4642ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4643 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4644 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4645 bool ValidateDiagnosticOptions) {
4646 // Initialize a stream.
4647 BitstreamCursor Stream(StreamData);
4648
4649 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004650 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4651 // FIXME this drops the error on the floor.
4652 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004653 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004654 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004655
4656 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4657 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4658 return Failure;
4659
4660 // Read all of the records in the options block.
4661 RecordData Record;
4662 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004663 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004664 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4665 if (!MaybeEntry) {
4666 // FIXME this drops the error on the floor.
4667 consumeError(MaybeEntry.takeError());
4668 return Failure;
4669 }
4670 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004671
4672 switch (Entry.Kind) {
4673 case llvm::BitstreamEntry::Error:
4674 case llvm::BitstreamEntry::SubBlock:
4675 return Failure;
4676
4677 case llvm::BitstreamEntry::EndBlock:
4678 return Result;
4679
4680 case llvm::BitstreamEntry::Record:
4681 // The interesting case.
4682 break;
4683 }
4684
4685 // Read and process a record.
4686 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004687 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4688 if (!MaybeRecordType) {
4689 // FIXME this drops the error.
4690 return Failure;
4691 }
4692 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004693 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004694 if (F)
4695 std::copy(Record.begin(), Record.end(), F->Signature.data());
4696 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004697 case DIAGNOSTIC_OPTIONS: {
4698 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4699 if (Listener && ValidateDiagnosticOptions &&
4700 !AllowCompatibleConfigurationMismatch &&
4701 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004702 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004703 break;
4704 }
4705 case DIAG_PRAGMA_MAPPINGS:
4706 if (!F)
4707 break;
4708 if (F->PragmaDiagMappings.empty())
4709 F->PragmaDiagMappings.swap(Record);
4710 else
4711 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4712 Record.begin(), Record.end());
4713 break;
4714 }
4715 }
4716}
4717
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004718/// Parse a record and blob containing module file extension metadata.
4719static bool parseModuleFileExtensionMetadata(
4720 const SmallVectorImpl<uint64_t> &Record,
4721 StringRef Blob,
4722 ModuleFileExtensionMetadata &Metadata) {
4723 if (Record.size() < 4) return true;
4724
4725 Metadata.MajorVersion = Record[0];
4726 Metadata.MinorVersion = Record[1];
4727
4728 unsigned BlockNameLen = Record[2];
4729 unsigned UserInfoLen = Record[3];
4730
4731 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4732
4733 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4734 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4735 Blob.data() + BlockNameLen + UserInfoLen);
4736 return false;
4737}
4738
4739ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4740 BitstreamCursor &Stream = F.Stream;
4741
4742 RecordData Record;
4743 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004744 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4745 if (!MaybeEntry) {
4746 Error(MaybeEntry.takeError());
4747 return Failure;
4748 }
4749 llvm::BitstreamEntry Entry = MaybeEntry.get();
4750
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004751 switch (Entry.Kind) {
4752 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004753 if (llvm::Error Err = Stream.SkipBlock()) {
4754 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004755 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004756 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004757 continue;
4758
4759 case llvm::BitstreamEntry::EndBlock:
4760 return Success;
4761
4762 case llvm::BitstreamEntry::Error:
4763 return HadErrors;
4764
4765 case llvm::BitstreamEntry::Record:
4766 break;
4767 }
4768
4769 Record.clear();
4770 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004771 Expected<unsigned> MaybeRecCode =
4772 Stream.readRecord(Entry.ID, Record, &Blob);
4773 if (!MaybeRecCode) {
4774 Error(MaybeRecCode.takeError());
4775 return Failure;
4776 }
4777 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004778 case EXTENSION_METADATA: {
4779 ModuleFileExtensionMetadata Metadata;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004780 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4781 Error("malformed EXTENSION_METADATA in AST file");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004782 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004783 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004784
4785 // Find a module file extension with this block name.
4786 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4787 if (Known == ModuleFileExtensions.end()) break;
4788
4789 // Form a reader.
4790 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4791 F, Stream)) {
4792 F.ExtensionReaders.push_back(std::move(Reader));
4793 }
4794
4795 break;
4796 }
4797 }
4798 }
4799
4800 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004801}
4802
Richard Smitha7e2cc62015-05-01 01:53:09 +00004803void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004804 assert(ContextObj && "no context to initialize");
4805 ASTContext &Context = *ContextObj;
4806
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 // If there's a listener, notify them that we "read" the translation unit.
4808 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004809 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 Context.getTranslationUnitDecl());
4811
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 // FIXME: Find a better way to deal with collisions between these
4813 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004814
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 // Load the special types.
4816 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4817 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4818 if (!Context.CFConstantStringTypeDecl)
4819 Context.setCFConstantStringType(GetType(String));
4820 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004821
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4823 QualType FileType = GetType(File);
4824 if (FileType.isNull()) {
4825 Error("FILE type is NULL");
4826 return;
4827 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004828
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004830 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 Context.setFILEDecl(Typedef->getDecl());
4832 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004833 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 if (!Tag) {
4835 Error("Invalid FILE type in AST file");
4836 return;
4837 }
4838 Context.setFILEDecl(Tag->getDecl());
4839 }
4840 }
4841 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004842
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4844 QualType Jmp_bufType = GetType(Jmp_buf);
4845 if (Jmp_bufType.isNull()) {
4846 Error("jmp_buf type is NULL");
4847 return;
4848 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004849
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004851 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 Context.setjmp_bufDecl(Typedef->getDecl());
4853 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004854 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 if (!Tag) {
4856 Error("Invalid jmp_buf type in AST file");
4857 return;
4858 }
4859 Context.setjmp_bufDecl(Tag->getDecl());
4860 }
4861 }
4862 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004863
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4865 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4866 if (Sigjmp_bufType.isNull()) {
4867 Error("sigjmp_buf type is NULL");
4868 return;
4869 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004870
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004872 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 Context.setsigjmp_bufDecl(Typedef->getDecl());
4874 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004875 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 assert(Tag && "Invalid sigjmp_buf type in AST file");
4877 Context.setsigjmp_bufDecl(Tag->getDecl());
4878 }
4879 }
4880 }
4881
4882 if (unsigned ObjCIdRedef
4883 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4884 if (Context.ObjCIdRedefinitionType.isNull())
4885 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4886 }
4887
4888 if (unsigned ObjCClassRedef
4889 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4890 if (Context.ObjCClassRedefinitionType.isNull())
4891 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4892 }
4893
4894 if (unsigned ObjCSelRedef
4895 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4896 if (Context.ObjCSelRedefinitionType.isNull())
4897 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4898 }
4899
4900 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4901 QualType Ucontext_tType = GetType(Ucontext_t);
4902 if (Ucontext_tType.isNull()) {
4903 Error("ucontext_t type is NULL");
4904 return;
4905 }
4906
4907 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004908 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 Context.setucontext_tDecl(Typedef->getDecl());
4910 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004911 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 assert(Tag && "Invalid ucontext_t type in AST file");
4913 Context.setucontext_tDecl(Tag->getDecl());
4914 }
4915 }
4916 }
4917 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004918
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4920
4921 // If there were any CUDA special declarations, deserialize them.
4922 if (!CUDASpecialDeclRefs.empty()) {
4923 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4924 Context.setcudaConfigureCallDecl(
4925 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4926 }
Richard Smith56be7542014-03-21 00:33:59 +00004927
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004929 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004930 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004931 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004932 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004933 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004934 if (Import.ImportLoc.isValid())
4935 PP.makeModuleVisible(Imported, Import.ImportLoc);
4936 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004937 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 }
4939 ImportedModules.clear();
4940}
4941
4942void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004943 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004944}
4945
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004946/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004947/// else returns 0.
4948static ASTFileSignature readASTFileSignature(StringRef PCH) {
4949 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004950 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4951 // FIXME this drops the error on the floor.
4952 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004953 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004954 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004955
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004956 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4957 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004958 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004959
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004960 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004961 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004962 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004963 Expected<llvm::BitstreamEntry> MaybeEntry =
4964 Stream.advanceSkippingSubblocks();
4965 if (!MaybeEntry) {
4966 // FIXME this drops the error on the floor.
4967 consumeError(MaybeEntry.takeError());
4968 return ASTFileSignature();
4969 }
4970 llvm::BitstreamEntry Entry = MaybeEntry.get();
4971
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004972 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004973 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004974
4975 Record.clear();
4976 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004977 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4978 if (!MaybeRecord) {
4979 // FIXME this drops the error on the floor.
4980 consumeError(MaybeRecord.takeError());
4981 return ASTFileSignature();
4982 }
4983 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004984 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4985 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004986 }
4987}
4988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004989/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004990/// directly from the AST file, without actually loading the AST
4991/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004992std::string ASTReader::getOriginalSourceFile(
4993 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004994 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004996 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004998 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4999 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00005000 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 }
5002
5003 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00005004 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00005005
5006 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005007 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5008 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005009 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005011
Chris Lattnere7b154b2013-01-19 21:39:22 +00005012 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005013 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005014 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005015 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005017
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005018 // Scan for ORIGINAL_FILE inside the control block.
5019 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005020 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005021 Expected<llvm::BitstreamEntry> MaybeEntry =
5022 Stream.advanceSkippingSubblocks();
5023 if (!MaybeEntry) {
5024 // FIXME this drops errors on the floor.
5025 consumeError(MaybeEntry.takeError());
5026 return std::string();
5027 }
5028 llvm::BitstreamEntry Entry = MaybeEntry.get();
5029
Chris Lattnere7b154b2013-01-19 21:39:22 +00005030 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005031 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005032
Chris Lattnere7b154b2013-01-19 21:39:22 +00005033 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5034 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005035 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005037
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005039 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005040 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5041 if (!MaybeRecord) {
5042 // FIXME this drops the errors on the floor.
5043 consumeError(MaybeRecord.takeError());
5044 return std::string();
5045 }
5046 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005047 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005049}
5050
5051namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005052
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 class SimplePCHValidator : public ASTReaderListener {
5054 const LangOptions &ExistingLangOpts;
5055 const TargetOptions &ExistingTargetOpts;
5056 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005057 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005059
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 public:
5061 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5062 const TargetOptions &ExistingTargetOpts,
5063 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005064 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 FileManager &FileMgr)
5066 : ExistingLangOpts(ExistingLangOpts),
5067 ExistingTargetOpts(ExistingTargetOpts),
5068 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005069 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005070 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005071
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005072 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5073 bool AllowCompatibleDifferences) override {
5074 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5075 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005077
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005078 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5079 bool AllowCompatibleDifferences) override {
5080 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5081 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005083
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005084 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5085 StringRef SpecificModuleCachePath,
5086 bool Complain) override {
5087 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5088 ExistingModuleCachePath,
5089 nullptr, ExistingLangOpts);
5090 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005091
Craig Topper3e89dfe2014-03-13 02:13:41 +00005092 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5093 bool Complain,
5094 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005095 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005096 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 }
5098 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005099
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005100} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005101
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005102bool ASTReader::readASTFileControlBlock(
5103 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005104 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005105 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005106 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005108 // FIXME: This allows use of the VFS; we do not allow use of the
5109 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005110 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 if (!Buffer) {
5112 return true;
5113 }
5114
5115 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005116 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5117 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005118
5119 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005120 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5121 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005124
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005125 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005126 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005127 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005128
5129 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005130 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005131 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005132 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005133
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005135 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005136 bool DoneWithControlBlock = false;
5137 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005138 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5139 if (!MaybeEntry) {
5140 // FIXME this drops the error on the floor.
5141 consumeError(MaybeEntry.takeError());
5142 return true;
5143 }
5144 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005145
5146 switch (Entry.Kind) {
5147 case llvm::BitstreamEntry::SubBlock: {
5148 switch (Entry.ID) {
5149 case OPTIONS_BLOCK_ID: {
5150 std::string IgnoredSuggestedPredefines;
5151 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5152 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005153 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005154 return true;
5155 break;
5156 }
5157
5158 case INPUT_FILES_BLOCK_ID:
5159 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005160 if (llvm::Error Err = Stream.SkipBlock()) {
5161 // FIXME this drops the error on the floor.
5162 consumeError(std::move(Err));
5163 return true;
5164 }
5165 if (NeedsInputFiles &&
5166 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005167 return true;
5168 break;
5169
5170 default:
JF Bastien0e828952019-06-26 19:50:12 +00005171 if (llvm::Error Err = Stream.SkipBlock()) {
5172 // FIXME this drops the error on the floor.
5173 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005174 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005175 }
Richard Smith0516b182015-09-08 19:40:14 +00005176 break;
5177 }
5178
5179 continue;
5180 }
5181
5182 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005183 DoneWithControlBlock = true;
5184 break;
Richard Smith0516b182015-09-08 19:40:14 +00005185
5186 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005187 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005188
5189 case llvm::BitstreamEntry::Record:
5190 break;
5191 }
5192
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005193 if (DoneWithControlBlock) break;
5194
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005196 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005197 Expected<unsigned> MaybeRecCode =
5198 Stream.readRecord(Entry.ID, Record, &Blob);
5199 if (!MaybeRecCode) {
5200 // FIXME this drops the error.
5201 return Failure;
5202 }
5203 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005204 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005205 if (Record[0] != VERSION_MAJOR)
5206 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005207 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005208 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005209 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005210 case MODULE_NAME:
5211 Listener.ReadModuleName(Blob);
5212 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005213 case MODULE_DIRECTORY:
5214 ModuleDir = Blob;
5215 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005216 case MODULE_MAP_FILE: {
5217 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005218 auto Path = ReadString(Record, Idx);
5219 ResolveImportedPath(Path, ModuleDir);
5220 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005221 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005222 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005223 case INPUT_FILE_OFFSETS: {
5224 if (!NeedsInputFiles)
5225 break;
5226
5227 unsigned NumInputFiles = Record[0];
5228 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005229 const llvm::support::unaligned_uint64_t *InputFileOffs =
5230 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005231 for (unsigned I = 0; I != NumInputFiles; ++I) {
5232 // Go find this input file.
5233 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005234
5235 if (isSystemFile && !NeedsSystemInputFiles)
5236 break; // the rest are system input files
5237
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005238 BitstreamCursor &Cursor = InputFilesCursor;
5239 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005240 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5241 // FIXME this drops errors on the floor.
5242 consumeError(std::move(Err));
5243 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005244
JF Bastien0e828952019-06-26 19:50:12 +00005245 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5246 if (!MaybeCode) {
5247 // FIXME this drops errors on the floor.
5248 consumeError(MaybeCode.takeError());
5249 }
5250 unsigned Code = MaybeCode.get();
5251
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005252 RecordData Record;
5253 StringRef Blob;
5254 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005255 Expected<unsigned> MaybeRecordType =
5256 Cursor.readRecord(Code, Record, &Blob);
5257 if (!MaybeRecordType) {
5258 // FIXME this drops errors on the floor.
5259 consumeError(MaybeRecordType.takeError());
5260 }
5261 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005262 case INPUT_FILE_HASH:
5263 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005264 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005265 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005266 std::string Filename = Blob;
5267 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005268 shouldContinue = Listener.visitInputFile(
5269 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005270 break;
5271 }
5272 if (!shouldContinue)
5273 break;
5274 }
5275 break;
5276 }
5277
Richard Smithd4b230b2014-10-27 23:01:16 +00005278 case IMPORTS: {
5279 if (!NeedsImports)
5280 break;
5281
5282 unsigned Idx = 0, N = Record.size();
5283 while (Idx < N) {
5284 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005285 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5286 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005287 std::string Filename = ReadString(Record, Idx);
5288 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005289 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005290 }
5291 break;
5292 }
5293
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005294 default:
5295 // No other validation to perform.
5296 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 }
5298 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005299
5300 // Look for module file extension blocks, if requested.
5301 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005302 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005303 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5304 bool DoneWithExtensionBlock = false;
5305 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005306 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5307 if (!MaybeEntry) {
5308 // FIXME this drops the error.
5309 return true;
5310 }
5311 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005312
JF Bastien0e828952019-06-26 19:50:12 +00005313 switch (Entry.Kind) {
5314 case llvm::BitstreamEntry::SubBlock:
5315 if (llvm::Error Err = Stream.SkipBlock()) {
5316 // FIXME this drops the error on the floor.
5317 consumeError(std::move(Err));
5318 return true;
5319 }
5320 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005321
JF Bastien0e828952019-06-26 19:50:12 +00005322 case llvm::BitstreamEntry::EndBlock:
5323 DoneWithExtensionBlock = true;
5324 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005325
JF Bastien0e828952019-06-26 19:50:12 +00005326 case llvm::BitstreamEntry::Error:
5327 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005328
JF Bastien0e828952019-06-26 19:50:12 +00005329 case llvm::BitstreamEntry::Record:
5330 break;
5331 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005332
5333 Record.clear();
5334 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005335 Expected<unsigned> MaybeRecCode =
5336 Stream.readRecord(Entry.ID, Record, &Blob);
5337 if (!MaybeRecCode) {
5338 // FIXME this drops the error.
5339 return true;
5340 }
5341 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005342 case EXTENSION_METADATA: {
5343 ModuleFileExtensionMetadata Metadata;
5344 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5345 return true;
5346
5347 Listener.readModuleFileExtension(Metadata);
5348 break;
5349 }
5350 }
5351 }
5352 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005353 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005354 }
5355
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005356 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5357 if (readUnhashedControlBlockImpl(
5358 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5359 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5360 ValidateDiagnosticOptions) != Success)
5361 return true;
5362
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005363 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005364}
5365
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005366bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5367 const PCHContainerReader &PCHContainerRdr,
5368 const LangOptions &LangOpts,
5369 const TargetOptions &TargetOpts,
5370 const PreprocessorOptions &PPOpts,
5371 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005372 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5373 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005374 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005375 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005376 validator,
5377 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005378}
5379
Ben Langmuir2c9af442014-04-10 17:57:43 +00005380ASTReader::ASTReadResult
5381ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005383 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5384 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005385 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 }
5387
5388 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5389 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005390 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 RecordData Record;
5392 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005393 Expected<llvm::BitstreamEntry> MaybeEntry =
5394 F.Stream.advanceSkippingSubblocks();
5395 if (!MaybeEntry) {
5396 Error(MaybeEntry.takeError());
5397 return Failure;
5398 }
5399 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005400
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005401 switch (Entry.Kind) {
5402 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5403 case llvm::BitstreamEntry::Error:
5404 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005405 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005406 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005407 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005408 case llvm::BitstreamEntry::Record:
5409 // The interesting case.
5410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005412
Guy Benyei11169dd2012-12-18 14:30:41 +00005413 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005414 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005416 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5417 if (!MaybeKind) {
5418 Error(MaybeKind.takeError());
5419 return Failure;
5420 }
5421 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005422
5423 if ((Kind == SUBMODULE_METADATA) != First) {
5424 Error("submodule metadata record should be at beginning of block");
5425 return Failure;
5426 }
5427 First = false;
5428
5429 // Submodule information is only valid if we have a current module.
5430 // FIXME: Should we error on these cases?
5431 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5432 Kind != SUBMODULE_DEFINITION)
5433 continue;
5434
5435 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 default: // Default behavior: ignore.
5437 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005438
Richard Smith03478d92014-10-23 22:12:14 +00005439 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005440 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005443 }
Richard Smith03478d92014-10-23 22:12:14 +00005444
Chris Lattner0e6c9402013-01-20 02:38:54 +00005445 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005446 unsigned Idx = 0;
5447 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5448 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005449 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005450 bool IsFramework = Record[Idx++];
5451 bool IsExplicit = Record[Idx++];
5452 bool IsSystem = Record[Idx++];
5453 bool IsExternC = Record[Idx++];
5454 bool InferSubmodules = Record[Idx++];
5455 bool InferExplicitSubmodules = Record[Idx++];
5456 bool InferExportWildcard = Record[Idx++];
5457 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005458 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005459
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005460 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005461 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005463
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 // Retrieve this (sub)module from the module map, creating it if
5465 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005466 CurrentModule =
5467 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5468 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005469
5470 // FIXME: set the definition loc for CurrentModule, or call
5471 // ModMap.setInferredModuleAllowedBy()
5472
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5474 if (GlobalIndex >= SubmodulesLoaded.size() ||
5475 SubmodulesLoaded[GlobalIndex]) {
5476 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005477 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005479
Douglas Gregor7029ce12013-03-19 00:28:20 +00005480 if (!ParentModule) {
5481 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005482 // Don't emit module relocation error if we have -fno-validate-pch
5483 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5484 CurFile != F.File) {
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08005485 Error(diag::err_module_file_conflict,
5486 CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5487 F.File->getName());
Ben Langmuir2c9af442014-04-10 17:57:43 +00005488 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005489 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005490 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005491
5492 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005493 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005494 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005495
Richard Smithdd8b5332017-09-04 05:37:53 +00005496 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005497 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 CurrentModule->IsFromModuleFile = true;
5499 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005500 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005501 CurrentModule->InferSubmodules = InferSubmodules;
5502 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5503 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005504 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005505 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 if (DeserializationListener)
5507 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005508
Guy Benyei11169dd2012-12-18 14:30:41 +00005509 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005510
Richard Smith8a3e39a2016-03-28 21:31:09 +00005511 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005512 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005513 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005514 CurrentModule->UnresolvedConflicts.clear();
5515 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005516
5517 // The module is available unless it's missing a requirement; relevant
5518 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5519 // Missing headers that were present when the module was built do not
5520 // make it unavailable -- if we got this far, this must be an explicitly
5521 // imported module file.
5522 CurrentModule->Requirements.clear();
5523 CurrentModule->MissingHeaders.clear();
5524 CurrentModule->IsMissingRequirement =
5525 ParentModule && ParentModule->IsMissingRequirement;
5526 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 break;
5528 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005529
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005531 std::string Filename = Blob;
5532 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005533 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005535 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5536 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005537 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5538 Error("mismatched umbrella headers in submodule");
5539 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 }
5541 }
5542 break;
5543 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005544
Richard Smith202210b2014-10-24 20:23:01 +00005545 case SUBMODULE_HEADER:
5546 case SUBMODULE_EXCLUDED_HEADER:
5547 case SUBMODULE_PRIVATE_HEADER:
5548 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005549 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5550 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005551 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005552
Richard Smith202210b2014-10-24 20:23:01 +00005553 case SUBMODULE_TEXTUAL_HEADER:
5554 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5555 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5556 // them here.
5557 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005558
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005559 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005560 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005561 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005562
5563 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005564 std::string Dirname = Blob;
5565 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005566 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005567 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005568 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5569 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005570 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5571 Error("mismatched umbrella directories in submodule");
5572 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005573 }
5574 }
5575 break;
5576 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005577
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 F.BaseSubmoduleID = getTotalNumSubmodules();
5580 F.LocalNumSubmodules = Record[0];
5581 unsigned LocalBaseSubmoduleID = Record[1];
5582 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005583 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005584 // module.
5585 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005586
5587 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 // module.
5589 F.SubmoduleRemap.insertOrReplace(
5590 std::make_pair(LocalBaseSubmoduleID,
5591 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005592
Ben Langmuir52ca6782014-10-20 16:27:32 +00005593 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005595 break;
5596 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005597
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005598 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005600 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 Unresolved.File = &F;
5602 Unresolved.Mod = CurrentModule;
5603 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005604 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005606 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 }
5608 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005609
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005610 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005612 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 Unresolved.File = &F;
5614 Unresolved.Mod = CurrentModule;
5615 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005616 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005618 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005620
5621 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 // the parsed, unresolved exports around.
5623 CurrentModule->UnresolvedExports.clear();
5624 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005625
5626 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005627 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5628 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005630
5631 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005632 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005633 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005634 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005635 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005636
5637 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005638 CurrentModule->ConfigMacros.push_back(Blob.str());
5639 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005640
5641 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005642 UnresolvedModuleRef Unresolved;
5643 Unresolved.File = &F;
5644 Unresolved.Mod = CurrentModule;
5645 Unresolved.ID = Record[0];
5646 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5647 Unresolved.IsWildcard = false;
5648 Unresolved.String = Blob;
5649 UnresolvedModuleRefs.push_back(Unresolved);
5650 break;
5651 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005652
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005653 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005654 if (!ContextObj)
5655 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005656 SmallVector<uint32_t, 16> Inits;
5657 for (auto &ID : Record)
5658 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005659 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005660 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005661 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005662
5663 case SUBMODULE_EXPORT_AS:
5664 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005665 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005666 break;
5667 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 }
5669}
5670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005671/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005672/// structure.
5673///
5674/// This routine parses the language options from the AST file and then gives
5675/// them to the AST listener if one is set.
5676///
5677/// \returns true if the listener deems the file unacceptable, false otherwise.
5678bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5679 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005680 ASTReaderListener &Listener,
5681 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 LangOptions LangOpts;
5683 unsigned Idx = 0;
5684#define LANGOPT(Name, Bits, Default, Description) \
5685 LangOpts.Name = Record[Idx++];
5686#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5687 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5688#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005689#define SANITIZER(NAME, ID) \
5690 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005691#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005692
Ben Langmuircd98cb72015-06-23 18:20:18 +00005693 for (unsigned N = Record[Idx++]; N; --N)
5694 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5695
Vedant Kumar48b4f762018-04-14 01:40:48 +00005696 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005697 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5698 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005699
Ben Langmuird4a667a2015-06-23 18:20:23 +00005700 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005701
5702 // Comment options.
5703 for (unsigned N = Record[Idx++]; N; --N) {
5704 LangOpts.CommentOpts.BlockCommandNames.push_back(
5705 ReadString(Record, Idx));
5706 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005707 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005708
Samuel Antaoee8fb302016-01-06 13:42:12 +00005709 // OpenMP offloading options.
5710 for (unsigned N = Record[Idx++]; N; --N) {
5711 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5712 }
5713
5714 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5715
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005716 return Listener.ReadLanguageOptions(LangOpts, Complain,
5717 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005718}
5719
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005720bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5721 ASTReaderListener &Listener,
5722 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 unsigned Idx = 0;
5724 TargetOptions TargetOpts;
5725 TargetOpts.Triple = ReadString(Record, Idx);
5726 TargetOpts.CPU = ReadString(Record, Idx);
5727 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 for (unsigned N = Record[Idx++]; N; --N) {
5729 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5730 }
5731 for (unsigned N = Record[Idx++]; N; --N) {
5732 TargetOpts.Features.push_back(ReadString(Record, Idx));
5733 }
5734
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005735 return Listener.ReadTargetOptions(TargetOpts, Complain,
5736 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737}
5738
5739bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5740 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005741 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005742 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005743#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005744#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005745 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005746#include "clang/Basic/DiagnosticOptions.def"
5747
Richard Smith3be1cb22014-08-07 00:24:21 +00005748 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005749 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005750 for (unsigned N = Record[Idx++]; N; --N)
5751 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005752
5753 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5754}
5755
5756bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5757 ASTReaderListener &Listener) {
5758 FileSystemOptions FSOpts;
5759 unsigned Idx = 0;
5760 FSOpts.WorkingDir = ReadString(Record, Idx);
5761 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5762}
5763
5764bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5765 bool Complain,
5766 ASTReaderListener &Listener) {
5767 HeaderSearchOptions HSOpts;
5768 unsigned Idx = 0;
5769 HSOpts.Sysroot = ReadString(Record, Idx);
5770
5771 // Include entries.
5772 for (unsigned N = Record[Idx++]; N; --N) {
5773 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005774 frontend::IncludeDirGroup Group
5775 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 bool IsFramework = Record[Idx++];
5777 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005778 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5779 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 }
5781
5782 // System header prefixes.
5783 for (unsigned N = Record[Idx++]; N; --N) {
5784 std::string Prefix = ReadString(Record, Idx);
5785 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005786 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 }
5788
5789 HSOpts.ResourceDir = ReadString(Record, Idx);
5790 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005791 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005793 HSOpts.ImplicitModuleMaps = Record[Idx++];
5794 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 HSOpts.UseBuiltinIncludes = Record[Idx++];
5796 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5797 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5798 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005799 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005800
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005801 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5802 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005803}
5804
5805bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5806 bool Complain,
5807 ASTReaderListener &Listener,
5808 std::string &SuggestedPredefines) {
5809 PreprocessorOptions PPOpts;
5810 unsigned Idx = 0;
5811
5812 // Macro definitions/undefs
5813 for (unsigned N = Record[Idx++]; N; --N) {
5814 std::string Macro = ReadString(Record, Idx);
5815 bool IsUndef = Record[Idx++];
5816 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5817 }
5818
5819 // Includes
5820 for (unsigned N = Record[Idx++]; N; --N) {
5821 PPOpts.Includes.push_back(ReadString(Record, Idx));
5822 }
5823
5824 // Macro Includes
5825 for (unsigned N = Record[Idx++]; N; --N) {
5826 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5827 }
5828
5829 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005830 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 PPOpts.ObjCXXARCStandardLibrary =
5833 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5834 SuggestedPredefines.clear();
5835 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5836 SuggestedPredefines);
5837}
5838
5839std::pair<ModuleFile *, unsigned>
5840ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5841 GlobalPreprocessedEntityMapType::iterator
5842 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005843 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 "Corrupted global preprocessed entity map");
5845 ModuleFile *M = I->second;
5846 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5847 return std::make_pair(M, LocalIndex);
5848}
5849
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005850llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005851ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5852 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5853 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5854 Mod.NumPreprocessedEntities);
5855
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005856 return llvm::make_range(PreprocessingRecord::iterator(),
5857 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005858}
5859
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005860llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005861ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005862 return llvm::make_range(
5863 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5864 ModuleDeclIterator(this, &Mod,
5865 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005866}
5867
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005868SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5869 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5870 assert(I != GlobalSkippedRangeMap.end() &&
5871 "Corrupted global skipped range map");
5872 ModuleFile *M = I->second;
5873 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5874 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5875 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5876 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5877 TranslateSourceLocation(*M, RawRange.getEnd()));
5878 assert(Range.isValid());
5879 return Range;
5880}
5881
Guy Benyei11169dd2012-12-18 14:30:41 +00005882PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5883 PreprocessedEntityID PPID = Index+1;
5884 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5885 ModuleFile &M = *PPInfo.first;
5886 unsigned LocalIndex = PPInfo.second;
5887 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5888
Guy Benyei11169dd2012-12-18 14:30:41 +00005889 if (!PP.getPreprocessingRecord()) {
5890 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005891 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005893
5894 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005895 if (llvm::Error Err =
5896 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5897 Error(std::move(Err));
5898 return nullptr;
5899 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005900
JF Bastien0e828952019-06-26 19:50:12 +00005901 Expected<llvm::BitstreamEntry> MaybeEntry =
5902 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5903 if (!MaybeEntry) {
5904 Error(MaybeEntry.takeError());
5905 return nullptr;
5906 }
5907 llvm::BitstreamEntry Entry = MaybeEntry.get();
5908
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005909 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005910 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005911
Guy Benyei11169dd2012-12-18 14:30:41 +00005912 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005913 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5914 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005915 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005916 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005917 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005918 Expected<unsigned> MaybeRecType =
5919 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5920 if (!MaybeRecType) {
5921 Error(MaybeRecType.takeError());
5922 return nullptr;
5923 }
5924 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005925 case PPD_MACRO_EXPANSION: {
5926 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005927 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005928 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005929 if (isBuiltin)
5930 Name = getLocalIdentifier(M, Record[1]);
5931 else {
Richard Smith66a81862015-05-04 02:25:31 +00005932 PreprocessedEntityID GlobalID =
5933 getGlobalPreprocessedEntityID(M, Record[1]);
5934 Def = cast<MacroDefinitionRecord>(
5935 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 }
5937
5938 MacroExpansion *ME;
5939 if (isBuiltin)
5940 ME = new (PPRec) MacroExpansion(Name, Range);
5941 else
5942 ME = new (PPRec) MacroExpansion(Def, Range);
5943
5944 return ME;
5945 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005946
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 case PPD_MACRO_DEFINITION: {
5948 // Decode the identifier info and then check again; if the macro is
5949 // still defined and associated with the identifier,
5950 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005951 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005952
5953 if (DeserializationListener)
5954 DeserializationListener->MacroDefinitionRead(PPID, MD);
5955
5956 return MD;
5957 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005958
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005960 const char *FullFileNameStart = Blob.data() + Record[0];
5961 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005962 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005964 if (auto FE = PP.getFileManager().getFile(FullFileName))
5965 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005968 InclusionDirective::InclusionKind Kind
5969 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5970 InclusionDirective *ID
5971 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005972 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 Record[1], Record[3],
5974 File,
5975 Range);
5976 return ID;
5977 }
5978 }
5979
5980 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5981}
5982
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005983/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005984/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005985///
5986/// \param SLocMapI points at a chunk of a module that contains no
5987/// preprocessed entities or the entities it contains are not the ones we are
5988/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005989PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5990 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5991 ++SLocMapI;
5992 for (GlobalSLocOffsetMapType::const_iterator
5993 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5994 ModuleFile &M = *SLocMapI->second;
5995 if (M.NumPreprocessedEntities)
5996 return M.BasePreprocessedEntityID;
5997 }
5998
5999 return getTotalNumPreprocessedEntities();
6000}
6001
6002namespace {
6003
Guy Benyei11169dd2012-12-18 14:30:41 +00006004struct PPEntityComp {
6005 const ASTReader &Reader;
6006 ModuleFile &M;
6007
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006008 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006009
6010 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6011 SourceLocation LHS = getLoc(L);
6012 SourceLocation RHS = getLoc(R);
6013 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6014 }
6015
6016 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6017 SourceLocation LHS = getLoc(L);
6018 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6019 }
6020
6021 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6022 SourceLocation RHS = getLoc(R);
6023 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6024 }
6025
6026 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006027 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 }
6029};
6030
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006031} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006032
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006033PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6034 bool EndsAfter) const {
6035 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 return getTotalNumPreprocessedEntities();
6037
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006038 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6039 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6041 "Corrupted global sloc offset map");
6042
6043 if (SLocMapI->second->NumPreprocessedEntities == 0)
6044 return findNextPreprocessedEntity(SLocMapI);
6045
6046 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006047
6048 using pp_iterator = const PPEntityOffset *;
6049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6051 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6052
6053 size_t Count = M.NumPreprocessedEntities;
6054 size_t Half;
6055 pp_iterator First = pp_begin;
6056 pp_iterator PPI;
6057
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006058 if (EndsAfter) {
6059 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006060 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006061 } else {
6062 // Do a binary search manually instead of using std::lower_bound because
6063 // The end locations of entities may be unordered (when a macro expansion
6064 // is inside another macro argument), but for this case it is not important
6065 // whether we get the first macro expansion or its containing macro.
6066 while (Count > 0) {
6067 Half = Count / 2;
6068 PPI = First;
6069 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006070 if (SourceMgr.isBeforeInTranslationUnit(
6071 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006072 First = PPI;
6073 ++First;
6074 Count = Count - Half - 1;
6075 } else
6076 Count = Half;
6077 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 }
6079
6080 if (PPI == pp_end)
6081 return findNextPreprocessedEntity(SLocMapI);
6082
6083 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6084}
6085
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006086/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006087/// preprocessed entities that \arg Range encompasses.
6088std::pair<unsigned, unsigned>
6089 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6090 if (Range.isInvalid())
6091 return std::make_pair(0,0);
6092 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6093
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006094 PreprocessedEntityID BeginID =
6095 findPreprocessedEntity(Range.getBegin(), false);
6096 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 return std::make_pair(BeginID, EndID);
6098}
6099
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006100/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006101/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006102Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 FileID FID) {
6104 if (FID.isInvalid())
6105 return false;
6106
6107 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6108 ModuleFile &M = *PPInfo.first;
6109 unsigned LocalIndex = PPInfo.second;
6110 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006111
Richard Smithcb34bd32016-03-27 07:28:06 +00006112 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 if (Loc.isInvalid())
6114 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006115
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6117 return true;
6118 else
6119 return false;
6120}
6121
6122namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006124 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006127 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006130 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006131
6132 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006133 HeaderFileInfoLookupTable *Table
6134 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 if (!Table)
6136 return false;
6137
6138 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006139 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 if (Pos == Table->end())
6141 return false;
6142
Richard Smithbdf2d932015-07-30 03:37:16 +00006143 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 return true;
6145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006146
David Blaikie05785d12013-02-20 22:23:23 +00006147 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006148 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006149
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006150} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006151
6152HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006153 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006154 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006155 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006157
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 return HeaderFileInfo();
6159}
6160
6161void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006162 using DiagState = DiagnosticsEngine::DiagState;
6163 SmallVector<DiagState *, 32> DiagStates;
6164
Vedant Kumar48b4f762018-04-14 01:40:48 +00006165 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006167 auto &Record = F.PragmaDiagMappings;
6168 if (Record.empty())
6169 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006170
Richard Smithd230de22017-01-26 01:01:01 +00006171 DiagStates.clear();
6172
6173 auto ReadDiagState =
6174 [&](const DiagState &BasedOn, SourceLocation Loc,
6175 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6176 unsigned BackrefID = Record[Idx++];
6177 if (BackrefID != 0)
6178 return DiagStates[BackrefID - 1];
6179
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006181 Diag.DiagStates.push_back(BasedOn);
6182 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006184 unsigned Size = Record[Idx++];
6185 assert(Idx + Size * 2 <= Record.size() &&
6186 "Invalid data, not enough diag/map pairs");
6187 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006188 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006189 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006190 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006191 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6192 continue;
6193
6194 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6195
6196 // If this mapping was specified as a warning but the severity was
6197 // upgraded due to diagnostic settings, simulate the current diagnostic
6198 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006199 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6200 NewMapping.setSeverity(diag::Severity::Warning);
6201 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006202 }
6203
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006204 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006205 }
Richard Smithd230de22017-01-26 01:01:01 +00006206 return NewState;
6207 };
6208
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006209 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006210 DiagState *FirstState;
6211 if (F.Kind == MK_ImplicitModule) {
6212 // Implicitly-built modules are reused with different diagnostic
6213 // settings. Use the initial diagnostic state from Diag to simulate this
6214 // compilation's diagnostic settings.
6215 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6216 DiagStates.push_back(FirstState);
6217
6218 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006219 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006220 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006221 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006222 assert(Idx < Record.size() &&
6223 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006224 } else if (F.isModule()) {
6225 // For an explicit module, preserve the flags from the module build
6226 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6227 // -Wblah flags.
6228 unsigned Flags = Record[Idx++];
6229 DiagState Initial;
6230 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6231 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6232 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6233 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6234 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6235 Initial.ExtBehavior = (diag::Severity)Flags;
6236 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006237
Richard Smith6c2b5a82018-02-09 01:15:13 +00006238 assert(F.OriginalSourceFileID.isValid());
6239
Richard Smithe37391c2017-05-03 00:28:49 +00006240 // Set up the root buffer of the module to start with the initial
6241 // diagnostic state of the module itself, to cover files that contain no
6242 // explicit transitions (for which we did not serialize anything).
6243 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6244 .StateTransitions.push_back({FirstState, 0});
6245 } else {
6246 // For prefix ASTs, start with whatever the user configured on the
6247 // command line.
6248 Idx++; // Skip flags.
6249 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6250 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006251 }
Richard Smithd230de22017-01-26 01:01:01 +00006252
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006253 // Read the state transitions.
6254 unsigned NumLocations = Record[Idx++];
6255 while (NumLocations--) {
6256 assert(Idx < Record.size() &&
6257 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006258 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6259 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006260 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006261 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6262 unsigned Transitions = Record[Idx++];
6263
6264 // Note that we don't need to set up Parent/ParentOffset here, because
6265 // we won't be changing the diagnostic state within imported FileIDs
6266 // (other than perhaps appending to the main source file, which has no
6267 // parent).
6268 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6269 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6270 for (unsigned I = 0; I != Transitions; ++I) {
6271 unsigned Offset = Record[Idx++];
6272 auto *State =
6273 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6274 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006275 }
6276 }
Richard Smithd230de22017-01-26 01:01:01 +00006277
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006278 // Read the final state.
6279 assert(Idx < Record.size() &&
6280 "Invalid data, missing final pragma diagnostic state");
6281 SourceLocation CurStateLoc =
6282 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6283 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6284
6285 if (!F.isModule()) {
6286 Diag.DiagStatesByLoc.CurDiagState = CurState;
6287 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6288
6289 // Preserve the property that the imaginary root file describes the
6290 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006291 FileID NullFile;
6292 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006293 if (T.empty())
6294 T.push_back({CurState, 0});
6295 else
6296 T[0].State = CurState;
6297 }
6298
Richard Smithd230de22017-01-26 01:01:01 +00006299 // Don't try to read these mappings again.
6300 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 }
6302}
6303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006304/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006305ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6306 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6307 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6308 ModuleFile *M = I->second;
6309 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6310}
6311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006312/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006313///
6314/// The index is the type ID, shifted and minus the number of predefs. This
6315/// routine actually reads the record corresponding to the type at the given
6316/// location. It is a helper routine for GetType, which deals with reading type
6317/// IDs.
6318QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006319 assert(ContextObj && "reading type with no AST context");
6320 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006322 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006323
6324 // Keep track of where we are in the stream, then jump back there
6325 // after reading this type.
6326 SavedStreamPosition SavedPosition(DeclsCursor);
6327
6328 ReadingKindTracker ReadingKind(Read_Type, *this);
6329
6330 // Note that we are loading a type record.
6331 Deserializing AType(this);
6332
6333 unsigned Idx = 0;
JF Bastien0e828952019-06-26 19:50:12 +00006334 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6335 Error(std::move(Err));
6336 return QualType();
6337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006338 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00006339 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
6340 if (!MaybeCode) {
6341 Error(MaybeCode.takeError());
6342 return QualType();
6343 }
6344 unsigned Code = MaybeCode.get();
6345
6346 Expected<unsigned> MaybeTypeCode = DeclsCursor.readRecord(Code, Record);
6347 if (!MaybeTypeCode) {
6348 Error(MaybeTypeCode.takeError());
6349 return QualType();
6350 }
6351 switch ((TypeCode)MaybeTypeCode.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 case TYPE_EXT_QUAL: {
6353 if (Record.size() != 2) {
6354 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006355 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 }
6357 QualType Base = readType(*Loc.F, Record, Idx);
6358 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
6359 return Context.getQualifiedType(Base, Quals);
6360 }
6361
6362 case TYPE_COMPLEX: {
6363 if (Record.size() != 1) {
6364 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006365 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006366 }
6367 QualType ElemType = readType(*Loc.F, Record, Idx);
6368 return Context.getComplexType(ElemType);
6369 }
6370
6371 case TYPE_POINTER: {
6372 if (Record.size() != 1) {
6373 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006374 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 }
6376 QualType PointeeType = readType(*Loc.F, Record, Idx);
6377 return Context.getPointerType(PointeeType);
6378 }
6379
Reid Kleckner8a365022013-06-24 17:51:48 +00006380 case TYPE_DECAYED: {
6381 if (Record.size() != 1) {
6382 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006383 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00006384 }
6385 QualType OriginalType = readType(*Loc.F, Record, Idx);
6386 QualType DT = Context.getAdjustedParameterType(OriginalType);
6387 if (!isa<DecayedType>(DT))
6388 Error("Decayed type does not decay");
6389 return DT;
6390 }
6391
Reid Kleckner0503a872013-12-05 01:23:43 +00006392 case TYPE_ADJUSTED: {
6393 if (Record.size() != 2) {
6394 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006395 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00006396 }
6397 QualType OriginalTy = readType(*Loc.F, Record, Idx);
6398 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
6399 return Context.getAdjustedType(OriginalTy, AdjustedTy);
6400 }
6401
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 case TYPE_BLOCK_POINTER: {
6403 if (Record.size() != 1) {
6404 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006405 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 }
6407 QualType PointeeType = readType(*Loc.F, Record, Idx);
6408 return Context.getBlockPointerType(PointeeType);
6409 }
6410
6411 case TYPE_LVALUE_REFERENCE: {
6412 if (Record.size() != 2) {
6413 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006414 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 }
6416 QualType PointeeType = readType(*Loc.F, Record, Idx);
6417 return Context.getLValueReferenceType(PointeeType, Record[1]);
6418 }
6419
6420 case TYPE_RVALUE_REFERENCE: {
6421 if (Record.size() != 1) {
6422 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006423 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 }
6425 QualType PointeeType = readType(*Loc.F, Record, Idx);
6426 return Context.getRValueReferenceType(PointeeType);
6427 }
6428
6429 case TYPE_MEMBER_POINTER: {
6430 if (Record.size() != 2) {
6431 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006432 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 }
6434 QualType PointeeType = readType(*Loc.F, Record, Idx);
6435 QualType ClassType = readType(*Loc.F, Record, Idx);
6436 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006437 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
6440 }
6441
6442 case TYPE_CONSTANT_ARRAY: {
6443 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006444 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 unsigned IndexTypeQuals = Record[2];
6446 unsigned Idx = 3;
6447 llvm::APInt Size = ReadAPInt(Record, Idx);
Richard Smith772e2662019-10-04 01:25:59 +00006448 Expr *SizeExpr = ReadExpr(*Loc.F);
6449 return Context.getConstantArrayType(ElementType, Size, SizeExpr,
Guy Benyei11169dd2012-12-18 14:30:41 +00006450 ASM, IndexTypeQuals);
6451 }
6452
6453 case TYPE_INCOMPLETE_ARRAY: {
6454 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006455 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006456 unsigned IndexTypeQuals = Record[2];
6457 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6458 }
6459
6460 case TYPE_VARIABLE_ARRAY: {
6461 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006462 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 unsigned IndexTypeQuals = Record[2];
6464 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6465 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6466 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6467 ASM, IndexTypeQuals,
6468 SourceRange(LBLoc, RBLoc));
6469 }
6470
6471 case TYPE_VECTOR: {
6472 if (Record.size() != 3) {
6473 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006474 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 }
6476
6477 QualType ElementType = readType(*Loc.F, Record, Idx);
6478 unsigned NumElements = Record[1];
6479 unsigned VecKind = Record[2];
6480 return Context.getVectorType(ElementType, NumElements,
6481 (VectorType::VectorKind)VecKind);
6482 }
6483
6484 case TYPE_EXT_VECTOR: {
6485 if (Record.size() != 3) {
6486 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006487 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 }
6489
6490 QualType ElementType = readType(*Loc.F, Record, Idx);
6491 unsigned NumElements = Record[1];
6492 return Context.getExtVectorType(ElementType, NumElements);
6493 }
6494
6495 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006496 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006498 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 }
6500 QualType ResultType = readType(*Loc.F, Record, Idx);
6501 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006502 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006503 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006504 return Context.getFunctionNoProtoType(ResultType, Info);
6505 }
6506
6507 case TYPE_FUNCTION_PROTO: {
6508 QualType ResultType = readType(*Loc.F, Record, Idx);
6509
6510 FunctionProtoType::ExtProtoInfo EPI;
6511 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6512 /*hasregparm*/ Record[2],
6513 /*regparm*/ Record[3],
6514 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006515 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006516 /*nocallersavedregs*/ Record[6],
6517 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006518
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006519 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
6521 EPI.Variadic = Record[Idx++];
6522 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006523 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006525 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006526 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006527
6528 unsigned NumParams = Record[Idx++];
6529 SmallVector<QualType, 16> ParamTypes;
6530 for (unsigned I = 0; I != NumParams; ++I)
6531 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6532
John McCall18afab72016-03-01 00:49:02 +00006533 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6534 if (Idx != Record.size()) {
6535 for (unsigned I = 0; I != NumParams; ++I)
6536 ExtParameterInfos.push_back(
6537 FunctionProtoType::ExtParameterInfo
6538 ::getFromOpaqueValue(Record[Idx++]));
6539 EPI.ExtParameterInfos = ExtParameterInfos.data();
6540 }
6541
6542 assert(Idx == Record.size());
6543
Jordan Rose5c382722013-03-08 21:51:21 +00006544 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 }
6546
6547 case TYPE_UNRESOLVED_USING: {
6548 unsigned Idx = 0;
6549 return Context.getTypeDeclType(
6550 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6551 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006552
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 case TYPE_TYPEDEF: {
6554 if (Record.size() != 2) {
6555 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006556 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 }
6558 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006559 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006560 QualType Canonical = readType(*Loc.F, Record, Idx);
6561 if (!Canonical.isNull())
6562 Canonical = Context.getCanonicalType(Canonical);
6563 return Context.getTypedefType(Decl, Canonical);
6564 }
6565
6566 case TYPE_TYPEOF_EXPR:
6567 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6568
6569 case TYPE_TYPEOF: {
6570 if (Record.size() != 1) {
6571 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006572 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 }
6574 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6575 return Context.getTypeOfType(UnderlyingType);
6576 }
6577
6578 case TYPE_DECLTYPE: {
6579 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6580 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6581 }
6582
6583 case TYPE_UNARY_TRANSFORM: {
6584 QualType BaseType = readType(*Loc.F, Record, Idx);
6585 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006586 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6588 }
6589
Richard Smith74aeef52013-04-26 16:15:35 +00006590 case TYPE_AUTO: {
6591 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006592 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006593 bool IsDependent = false, IsPack = false;
6594 if (Deduced.isNull()) {
6595 IsDependent = Record[Idx] > 0;
6596 IsPack = Record[Idx] > 1;
6597 ++Idx;
6598 }
6599 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006601
Richard Smith600b5262017-01-26 20:40:47 +00006602 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6603 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6604 QualType Deduced = readType(*Loc.F, Record, Idx);
6605 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6606 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6607 IsDependent);
6608 }
6609
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 case TYPE_RECORD: {
6611 if (Record.size() != 2) {
6612 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006613 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 }
6615 unsigned Idx = 0;
6616 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006617 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6619 QualType T = Context.getRecordType(RD);
6620 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6621 return T;
6622 }
6623
6624 case TYPE_ENUM: {
6625 if (Record.size() != 2) {
6626 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006627 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 }
6629 unsigned Idx = 0;
6630 bool IsDependent = Record[Idx++];
6631 QualType T
6632 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6633 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6634 return T;
6635 }
6636
6637 case TYPE_ATTRIBUTED: {
6638 if (Record.size() != 3) {
6639 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006640 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006641 }
6642 QualType modifiedType = readType(*Loc.F, Record, Idx);
6643 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006644 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 return Context.getAttributedType(kind, modifiedType, equivalentType);
6646 }
6647
6648 case TYPE_PAREN: {
6649 if (Record.size() != 1) {
6650 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006651 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 }
6653 QualType InnerType = readType(*Loc.F, Record, Idx);
6654 return Context.getParenType(InnerType);
6655 }
6656
Leonard Chanc72aaf62019-05-07 03:20:17 +00006657 case TYPE_MACRO_QUALIFIED: {
6658 if (Record.size() != 2) {
6659 Error("incorrect encoding of macro defined type");
6660 return QualType();
6661 }
6662 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6663 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6664 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6665 }
6666
Guy Benyei11169dd2012-12-18 14:30:41 +00006667 case TYPE_PACK_EXPANSION: {
6668 if (Record.size() != 2) {
6669 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006670 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 }
6672 QualType Pattern = readType(*Loc.F, Record, Idx);
6673 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006674 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006675 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006676 if (Record[1])
6677 NumExpansions = Record[1] - 1;
6678 return Context.getPackExpansionType(Pattern, NumExpansions);
6679 }
6680
6681 case TYPE_ELABORATED: {
6682 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006683 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6685 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006686 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6687 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 }
6689
6690 case TYPE_OBJC_INTERFACE: {
6691 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006692 ObjCInterfaceDecl *ItfD
6693 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6695 }
6696
Manman Rene6be26c2016-09-13 17:25:08 +00006697 case TYPE_OBJC_TYPE_PARAM: {
6698 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006699 ObjCTypeParamDecl *Decl
6700 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006701 unsigned NumProtos = Record[Idx++];
6702 SmallVector<ObjCProtocolDecl*, 4> Protos;
6703 for (unsigned I = 0; I != NumProtos; ++I)
6704 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6705 return Context.getObjCTypeParamType(Decl, Protos);
6706 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 case TYPE_OBJC_OBJECT: {
6709 unsigned Idx = 0;
6710 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006711 unsigned NumTypeArgs = Record[Idx++];
6712 SmallVector<QualType, 4> TypeArgs;
6713 for (unsigned I = 0; I != NumTypeArgs; ++I)
6714 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 unsigned NumProtos = Record[Idx++];
6716 SmallVector<ObjCProtocolDecl*, 4> Protos;
6717 for (unsigned I = 0; I != NumProtos; ++I)
6718 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006719 bool IsKindOf = Record[Idx++];
6720 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 }
6722
6723 case TYPE_OBJC_OBJECT_POINTER: {
6724 unsigned Idx = 0;
6725 QualType Pointee = readType(*Loc.F, Record, Idx);
6726 return Context.getObjCObjectPointerType(Pointee);
6727 }
6728
6729 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6730 unsigned Idx = 0;
6731 QualType Parm = readType(*Loc.F, Record, Idx);
6732 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006733 return Context.getSubstTemplateTypeParmType(
6734 cast<TemplateTypeParmType>(Parm),
6735 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 }
6737
6738 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6739 unsigned Idx = 0;
6740 QualType Parm = readType(*Loc.F, Record, Idx);
6741 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6742 return Context.getSubstTemplateTypeParmPackType(
6743 cast<TemplateTypeParmType>(Parm),
6744 ArgPack);
6745 }
6746
6747 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006748 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6750 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6751 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006752 const Type *T = nullptr;
6753 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6754 if (const Type *Existing = DI->getTypeForDecl()) {
6755 T = Existing;
6756 break;
6757 }
6758 }
6759 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006760 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006761 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6762 DI->setTypeForDecl(T);
6763 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006764 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 }
6766
6767 case TYPE_TEMPLATE_TYPE_PARM: {
6768 unsigned Idx = 0;
6769 unsigned Depth = Record[Idx++];
6770 unsigned Index = Record[Idx++];
6771 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006772 TemplateTypeParmDecl *D
6773 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006774 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6775 }
6776
6777 case TYPE_DEPENDENT_NAME: {
6778 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006779 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006781 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 QualType Canon = readType(*Loc.F, Record, Idx);
6783 if (!Canon.isNull())
6784 Canon = Context.getCanonicalType(Canon);
6785 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6786 }
6787
6788 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6789 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006790 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006792 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 unsigned NumArgs = Record[Idx++];
6794 SmallVector<TemplateArgument, 8> Args;
6795 Args.reserve(NumArgs);
6796 while (NumArgs--)
6797 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6798 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006799 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006800 }
6801
6802 case TYPE_DEPENDENT_SIZED_ARRAY: {
6803 unsigned Idx = 0;
6804
6805 // ArrayType
6806 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006807 ArrayType::ArraySizeModifier ASM
6808 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006809 unsigned IndexTypeQuals = Record[Idx++];
6810
6811 // DependentSizedArrayType
6812 Expr *NumElts = ReadExpr(*Loc.F);
6813 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6814
6815 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6816 IndexTypeQuals, Brackets);
6817 }
6818
6819 case TYPE_TEMPLATE_SPECIALIZATION: {
6820 unsigned Idx = 0;
6821 bool IsDependent = Record[Idx++];
6822 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6823 SmallVector<TemplateArgument, 8> Args;
6824 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6825 QualType Underlying = readType(*Loc.F, Record, Idx);
6826 QualType T;
6827 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006828 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006830 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6832 return T;
6833 }
6834
6835 case TYPE_ATOMIC: {
6836 if (Record.size() != 1) {
6837 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006838 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006839 }
6840 QualType ValueType = readType(*Loc.F, Record, Idx);
6841 return Context.getAtomicType(ValueType);
6842 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006843
Joey Goulye3c85de2016-12-01 11:30:49 +00006844 case TYPE_PIPE: {
6845 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006846 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006847 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006848 }
6849
6850 // Reading the pipe element type.
6851 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006852 unsigned ReadOnly = Record[1];
6853 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006854 }
6855
Erich Keanef702b022018-07-13 19:46:04 +00006856 case TYPE_DEPENDENT_SIZED_VECTOR: {
6857 unsigned Idx = 0;
6858 QualType ElementType = readType(*Loc.F, Record, Idx);
6859 Expr *SizeExpr = ReadExpr(*Loc.F);
6860 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6861 unsigned VecKind = Record[Idx];
6862
6863 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6864 (VectorType::VectorKind)VecKind);
6865 }
6866
Alex Lorenz00aee432017-03-22 10:04:48 +00006867 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6868 unsigned Idx = 0;
6869
6870 // DependentSizedExtVectorType
6871 QualType ElementType = readType(*Loc.F, Record, Idx);
6872 Expr *SizeExpr = ReadExpr(*Loc.F);
6873 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6874
6875 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6876 AttrLoc);
6877 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006878
6879 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6880 unsigned Idx = 0;
6881
6882 // DependentAddressSpaceType
6883 QualType PointeeType = readType(*Loc.F, Record, Idx);
6884 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6885 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6886
6887 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6888 AttrLoc);
6889 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 }
6891 llvm_unreachable("Invalid TypeCode!");
6892}
6893
Richard Smith564417a2014-03-20 21:47:22 +00006894void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6895 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006896 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006897 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006898 ExceptionSpecificationType EST =
6899 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006900 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006901 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006902 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006903 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006904 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006905 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006906 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006907 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006908 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6909 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006910 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006911 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006912 }
6913}
6914
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006915namespace clang {
6916
6917class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006918 ModuleFile *F;
6919 ASTReader *Reader;
6920 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 unsigned &Idx;
6922
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006923 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006924 return Reader->ReadSourceLocation(*F, Record, Idx);
6925 }
6926
6927 TypeSourceInfo *GetTypeSourceInfo() {
6928 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6929 }
6930
6931 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6932 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 }
6934
Richard Smithe43e2b32018-08-20 21:47:29 +00006935 Attr *ReadAttr() {
6936 return Reader->ReadAttr(*F, Record, Idx);
6937 }
6938
Guy Benyei11169dd2012-12-18 14:30:41 +00006939public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006940 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006942 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006943
6944 // We want compile-time assurance that we've enumerated all of
6945 // these, so unfortunately we have to declare them first, then
6946 // define them out-of-line.
6947#define ABSTRACT_TYPELOC(CLASS, PARENT)
6948#define TYPELOC(CLASS, PARENT) \
6949 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6950#include "clang/AST/TypeLocNodes.def"
6951
6952 void VisitFunctionTypeLoc(FunctionTypeLoc);
6953 void VisitArrayTypeLoc(ArrayTypeLoc);
6954};
6955
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006956} // namespace clang
6957
Guy Benyei11169dd2012-12-18 14:30:41 +00006958void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6959 // nothing to do
6960}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006961
Guy Benyei11169dd2012-12-18 14:30:41 +00006962void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006963 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006965 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6966 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6967 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6968 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 }
6970}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006971
Guy Benyei11169dd2012-12-18 14:30:41 +00006972void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006973 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006974}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006975
Guy Benyei11169dd2012-12-18 14:30:41 +00006976void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006977 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006978}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006979
Reid Kleckner8a365022013-06-24 17:51:48 +00006980void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6981 // nothing to do
6982}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006983
Reid Kleckner0503a872013-12-05 01:23:43 +00006984void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6985 // nothing to do
6986}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006987
Leonard Chanc72aaf62019-05-07 03:20:17 +00006988void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6989 TL.setExpansionLoc(ReadSourceLocation());
6990}
6991
Guy Benyei11169dd2012-12-18 14:30:41 +00006992void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006993 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006994}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006995
Guy Benyei11169dd2012-12-18 14:30:41 +00006996void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006997 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006998}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006999
Guy Benyei11169dd2012-12-18 14:30:41 +00007000void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007001 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007002}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007003
Guy Benyei11169dd2012-12-18 14:30:41 +00007004void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007005 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007006 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007007}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007008
Guy Benyei11169dd2012-12-18 14:30:41 +00007009void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007010 TL.setLBracketLoc(ReadSourceLocation());
7011 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007012 if (Record[Idx++])
7013 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 else
Craig Toppera13603a2014-05-22 05:54:18 +00007015 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007016}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7019 VisitArrayTypeLoc(TL);
7020}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007021
Guy Benyei11169dd2012-12-18 14:30:41 +00007022void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7023 VisitArrayTypeLoc(TL);
7024}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7027 VisitArrayTypeLoc(TL);
7028}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007029
Guy Benyei11169dd2012-12-18 14:30:41 +00007030void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7031 DependentSizedArrayTypeLoc TL) {
7032 VisitArrayTypeLoc(TL);
7033}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007034
Andrew Gozillon572bbb02017-10-02 06:25:51 +00007035void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7036 DependentAddressSpaceTypeLoc TL) {
7037
7038 TL.setAttrNameLoc(ReadSourceLocation());
7039 SourceRange range;
7040 range.setBegin(ReadSourceLocation());
7041 range.setEnd(ReadSourceLocation());
7042 TL.setAttrOperandParensRange(range);
7043 TL.setAttrExprOperand(Reader->ReadExpr(*F));
7044}
7045
Guy Benyei11169dd2012-12-18 14:30:41 +00007046void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7047 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007048 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007049}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007050
Guy Benyei11169dd2012-12-18 14:30:41 +00007051void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007052 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007053}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007054
Erich Keanef702b022018-07-13 19:46:04 +00007055void TypeLocReader::VisitDependentVectorTypeLoc(
7056 DependentVectorTypeLoc TL) {
7057 TL.setNameLoc(ReadSourceLocation());
7058}
7059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007061 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007062}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007063
Guy Benyei11169dd2012-12-18 14:30:41 +00007064void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007065 TL.setLocalRangeBegin(ReadSourceLocation());
7066 TL.setLParenLoc(ReadSourceLocation());
7067 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00007068 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
7069 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007070 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007071 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007072 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 }
7074}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007075
Guy Benyei11169dd2012-12-18 14:30:41 +00007076void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7077 VisitFunctionTypeLoc(TL);
7078}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007079
Guy Benyei11169dd2012-12-18 14:30:41 +00007080void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7081 VisitFunctionTypeLoc(TL);
7082}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007083
Guy Benyei11169dd2012-12-18 14:30:41 +00007084void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007085 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007086}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007087
Guy Benyei11169dd2012-12-18 14:30:41 +00007088void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007089 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007090}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007091
Guy Benyei11169dd2012-12-18 14:30:41 +00007092void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007093 TL.setTypeofLoc(ReadSourceLocation());
7094 TL.setLParenLoc(ReadSourceLocation());
7095 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007096}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007097
Guy Benyei11169dd2012-12-18 14:30:41 +00007098void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007099 TL.setTypeofLoc(ReadSourceLocation());
7100 TL.setLParenLoc(ReadSourceLocation());
7101 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007102 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007103}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007104
Guy Benyei11169dd2012-12-18 14:30:41 +00007105void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007106 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007107}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007108
Guy Benyei11169dd2012-12-18 14:30:41 +00007109void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007110 TL.setKWLoc(ReadSourceLocation());
7111 TL.setLParenLoc(ReadSourceLocation());
7112 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007113 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007115
Guy Benyei11169dd2012-12-18 14:30:41 +00007116void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007117 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007118}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007119
Richard Smith600b5262017-01-26 20:40:47 +00007120void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7121 DeducedTemplateSpecializationTypeLoc TL) {
7122 TL.setTemplateNameLoc(ReadSourceLocation());
7123}
7124
Guy Benyei11169dd2012-12-18 14:30:41 +00007125void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007126 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007127}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007128
Guy Benyei11169dd2012-12-18 14:30:41 +00007129void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007130 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007132
Guy Benyei11169dd2012-12-18 14:30:41 +00007133void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00007134 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00007135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007136
Guy Benyei11169dd2012-12-18 14:30:41 +00007137void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007138 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007139}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7142 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007143 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007144}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007145
Guy Benyei11169dd2012-12-18 14:30:41 +00007146void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7147 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007148 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007149}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007150
Guy Benyei11169dd2012-12-18 14:30:41 +00007151void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7152 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007153 TL.setTemplateKeywordLoc(ReadSourceLocation());
7154 TL.setTemplateNameLoc(ReadSourceLocation());
7155 TL.setLAngleLoc(ReadSourceLocation());
7156 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007158 TL.setArgLocInfo(
7159 i,
7160 Reader->GetTemplateArgumentLocInfo(
7161 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007162}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007163
Guy Benyei11169dd2012-12-18 14:30:41 +00007164void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007165 TL.setLParenLoc(ReadSourceLocation());
7166 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007167}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007168
Guy Benyei11169dd2012-12-18 14:30:41 +00007169void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007170 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007171 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007172}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007173
Guy Benyei11169dd2012-12-18 14:30:41 +00007174void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007175 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007176}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007177
Guy Benyei11169dd2012-12-18 14:30:41 +00007178void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007179 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007180 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007181 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007183
Guy Benyei11169dd2012-12-18 14:30:41 +00007184void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7185 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007186 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007187 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007188 TL.setTemplateKeywordLoc(ReadSourceLocation());
7189 TL.setTemplateNameLoc(ReadSourceLocation());
7190 TL.setLAngleLoc(ReadSourceLocation());
7191 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007193 TL.setArgLocInfo(
7194 I,
7195 Reader->GetTemplateArgumentLocInfo(
7196 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007197}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007198
Guy Benyei11169dd2012-12-18 14:30:41 +00007199void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007200 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007201}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007202
Guy Benyei11169dd2012-12-18 14:30:41 +00007203void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007204 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007205}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007206
Manman Rene6be26c2016-09-13 17:25:08 +00007207void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7208 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007209 TL.setProtocolLAngleLoc(ReadSourceLocation());
7210 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007211 }
7212 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007213 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007214}
7215
Guy Benyei11169dd2012-12-18 14:30:41 +00007216void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007217 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007218 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
7219 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00007220 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007221 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007222 TL.setProtocolLAngleLoc(ReadSourceLocation());
7223 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007225 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007226}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007229 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007230}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007233 TL.setKWLoc(ReadSourceLocation());
7234 TL.setLParenLoc(ReadSourceLocation());
7235 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007236}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007237
Xiuli Pan9c14e282016-01-09 12:53:17 +00007238void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007239 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00007240}
Guy Benyei11169dd2012-12-18 14:30:41 +00007241
Richard Smithc23d7342018-06-29 20:46:25 +00007242void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
7243 unsigned &Idx, TypeLoc TL) {
7244 TypeLocReader TLR(F, *this, Record, Idx);
7245 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7246 TLR.Visit(TL);
7247}
7248
David L. Jonesbe1557a2016-12-21 00:17:49 +00007249TypeSourceInfo *
7250ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
7251 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 QualType InfoTy = readType(F, Record, Idx);
7253 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00007254 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007255
7256 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00007257 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 return TInfo;
7259}
7260
7261QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007262 assert(ContextObj && "reading type with no AST context");
7263 ASTContext &Context = *ContextObj;
7264
Guy Benyei11169dd2012-12-18 14:30:41 +00007265 unsigned FastQuals = ID & Qualifiers::FastMask;
7266 unsigned Index = ID >> Qualifiers::FastWidth;
7267
7268 if (Index < NUM_PREDEF_TYPE_IDS) {
7269 QualType T;
7270 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00007271 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00007272 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00007273 case PREDEF_TYPE_VOID_ID:
7274 T = Context.VoidTy;
7275 break;
7276 case PREDEF_TYPE_BOOL_ID:
7277 T = Context.BoolTy;
7278 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 case PREDEF_TYPE_CHAR_U_ID:
7280 case PREDEF_TYPE_CHAR_S_ID:
7281 // FIXME: Check that the signedness of CharTy is correct!
7282 T = Context.CharTy;
7283 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007284 case PREDEF_TYPE_UCHAR_ID:
7285 T = Context.UnsignedCharTy;
7286 break;
7287 case PREDEF_TYPE_USHORT_ID:
7288 T = Context.UnsignedShortTy;
7289 break;
7290 case PREDEF_TYPE_UINT_ID:
7291 T = Context.UnsignedIntTy;
7292 break;
7293 case PREDEF_TYPE_ULONG_ID:
7294 T = Context.UnsignedLongTy;
7295 break;
7296 case PREDEF_TYPE_ULONGLONG_ID:
7297 T = Context.UnsignedLongLongTy;
7298 break;
7299 case PREDEF_TYPE_UINT128_ID:
7300 T = Context.UnsignedInt128Ty;
7301 break;
7302 case PREDEF_TYPE_SCHAR_ID:
7303 T = Context.SignedCharTy;
7304 break;
7305 case PREDEF_TYPE_WCHAR_ID:
7306 T = Context.WCharTy;
7307 break;
7308 case PREDEF_TYPE_SHORT_ID:
7309 T = Context.ShortTy;
7310 break;
7311 case PREDEF_TYPE_INT_ID:
7312 T = Context.IntTy;
7313 break;
7314 case PREDEF_TYPE_LONG_ID:
7315 T = Context.LongTy;
7316 break;
7317 case PREDEF_TYPE_LONGLONG_ID:
7318 T = Context.LongLongTy;
7319 break;
7320 case PREDEF_TYPE_INT128_ID:
7321 T = Context.Int128Ty;
7322 break;
7323 case PREDEF_TYPE_HALF_ID:
7324 T = Context.HalfTy;
7325 break;
7326 case PREDEF_TYPE_FLOAT_ID:
7327 T = Context.FloatTy;
7328 break;
7329 case PREDEF_TYPE_DOUBLE_ID:
7330 T = Context.DoubleTy;
7331 break;
7332 case PREDEF_TYPE_LONGDOUBLE_ID:
7333 T = Context.LongDoubleTy;
7334 break;
Leonard Chanf921d852018-06-04 16:07:52 +00007335 case PREDEF_TYPE_SHORT_ACCUM_ID:
7336 T = Context.ShortAccumTy;
7337 break;
7338 case PREDEF_TYPE_ACCUM_ID:
7339 T = Context.AccumTy;
7340 break;
7341 case PREDEF_TYPE_LONG_ACCUM_ID:
7342 T = Context.LongAccumTy;
7343 break;
7344 case PREDEF_TYPE_USHORT_ACCUM_ID:
7345 T = Context.UnsignedShortAccumTy;
7346 break;
7347 case PREDEF_TYPE_UACCUM_ID:
7348 T = Context.UnsignedAccumTy;
7349 break;
7350 case PREDEF_TYPE_ULONG_ACCUM_ID:
7351 T = Context.UnsignedLongAccumTy;
7352 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00007353 case PREDEF_TYPE_SHORT_FRACT_ID:
7354 T = Context.ShortFractTy;
7355 break;
7356 case PREDEF_TYPE_FRACT_ID:
7357 T = Context.FractTy;
7358 break;
7359 case PREDEF_TYPE_LONG_FRACT_ID:
7360 T = Context.LongFractTy;
7361 break;
7362 case PREDEF_TYPE_USHORT_FRACT_ID:
7363 T = Context.UnsignedShortFractTy;
7364 break;
7365 case PREDEF_TYPE_UFRACT_ID:
7366 T = Context.UnsignedFractTy;
7367 break;
7368 case PREDEF_TYPE_ULONG_FRACT_ID:
7369 T = Context.UnsignedLongFractTy;
7370 break;
7371 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7372 T = Context.SatShortAccumTy;
7373 break;
7374 case PREDEF_TYPE_SAT_ACCUM_ID:
7375 T = Context.SatAccumTy;
7376 break;
7377 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7378 T = Context.SatLongAccumTy;
7379 break;
7380 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7381 T = Context.SatUnsignedShortAccumTy;
7382 break;
7383 case PREDEF_TYPE_SAT_UACCUM_ID:
7384 T = Context.SatUnsignedAccumTy;
7385 break;
7386 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7387 T = Context.SatUnsignedLongAccumTy;
7388 break;
7389 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7390 T = Context.SatShortFractTy;
7391 break;
7392 case PREDEF_TYPE_SAT_FRACT_ID:
7393 T = Context.SatFractTy;
7394 break;
7395 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7396 T = Context.SatLongFractTy;
7397 break;
7398 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7399 T = Context.SatUnsignedShortFractTy;
7400 break;
7401 case PREDEF_TYPE_SAT_UFRACT_ID:
7402 T = Context.SatUnsignedFractTy;
7403 break;
7404 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7405 T = Context.SatUnsignedLongFractTy;
7406 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00007407 case PREDEF_TYPE_FLOAT16_ID:
7408 T = Context.Float16Ty;
7409 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007410 case PREDEF_TYPE_FLOAT128_ID:
7411 T = Context.Float128Ty;
7412 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007413 case PREDEF_TYPE_OVERLOAD_ID:
7414 T = Context.OverloadTy;
7415 break;
7416 case PREDEF_TYPE_BOUND_MEMBER:
7417 T = Context.BoundMemberTy;
7418 break;
7419 case PREDEF_TYPE_PSEUDO_OBJECT:
7420 T = Context.PseudoObjectTy;
7421 break;
7422 case PREDEF_TYPE_DEPENDENT_ID:
7423 T = Context.DependentTy;
7424 break;
7425 case PREDEF_TYPE_UNKNOWN_ANY:
7426 T = Context.UnknownAnyTy;
7427 break;
7428 case PREDEF_TYPE_NULLPTR_ID:
7429 T = Context.NullPtrTy;
7430 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007431 case PREDEF_TYPE_CHAR8_ID:
7432 T = Context.Char8Ty;
7433 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007434 case PREDEF_TYPE_CHAR16_ID:
7435 T = Context.Char16Ty;
7436 break;
7437 case PREDEF_TYPE_CHAR32_ID:
7438 T = Context.Char32Ty;
7439 break;
7440 case PREDEF_TYPE_OBJC_ID:
7441 T = Context.ObjCBuiltinIdTy;
7442 break;
7443 case PREDEF_TYPE_OBJC_CLASS:
7444 T = Context.ObjCBuiltinClassTy;
7445 break;
7446 case PREDEF_TYPE_OBJC_SEL:
7447 T = Context.ObjCBuiltinSelTy;
7448 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007449#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7450 case PREDEF_TYPE_##Id##_ID: \
7451 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007452 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007453#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007454#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7455 case PREDEF_TYPE_##Id##_ID: \
7456 T = Context.Id##Ty; \
7457 break;
7458#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007459 case PREDEF_TYPE_SAMPLER_ID:
7460 T = Context.OCLSamplerTy;
7461 break;
7462 case PREDEF_TYPE_EVENT_ID:
7463 T = Context.OCLEventTy;
7464 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007465 case PREDEF_TYPE_CLK_EVENT_ID:
7466 T = Context.OCLClkEventTy;
7467 break;
7468 case PREDEF_TYPE_QUEUE_ID:
7469 T = Context.OCLQueueTy;
7470 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007471 case PREDEF_TYPE_RESERVE_ID_ID:
7472 T = Context.OCLReserveIDTy;
7473 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007474 case PREDEF_TYPE_AUTO_DEDUCT:
7475 T = Context.getAutoDeductType();
7476 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007477 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7478 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7481 T = Context.ARCUnbridgedCastTy;
7482 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483 case PREDEF_TYPE_BUILTIN_FN:
7484 T = Context.BuiltinFnTy;
7485 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007486 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7487 T = Context.OMPArraySectionTy;
7488 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00007489#define SVE_TYPE(Name, Id, SingletonId) \
7490 case PREDEF_TYPE_##Id##_ID: \
7491 T = Context.SingletonId; \
7492 break;
7493#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 }
7495
7496 assert(!T.isNull() && "Unknown predefined type");
7497 return T.withFastQualifiers(FastQuals);
7498 }
7499
7500 Index -= NUM_PREDEF_TYPE_IDS;
7501 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7502 if (TypesLoaded[Index].isNull()) {
7503 TypesLoaded[Index] = readTypeRecord(Index);
7504 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007505 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007506
7507 TypesLoaded[Index]->setFromAST();
7508 if (DeserializationListener)
7509 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7510 TypesLoaded[Index]);
7511 }
7512
7513 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7514}
7515
7516QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7517 return GetType(getGlobalTypeID(F, LocalID));
7518}
7519
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007520serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007521ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7522 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7523 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007524
Guy Benyei11169dd2012-12-18 14:30:41 +00007525 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7526 return LocalID;
7527
Richard Smith37a93df2017-02-18 00:32:02 +00007528 if (!F.ModuleOffsetMap.empty())
7529 ReadModuleOffsetMap(F);
7530
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7532 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7533 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007534
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 unsigned GlobalIndex = LocalIndex + I->second;
7536 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7537}
7538
7539TemplateArgumentLocInfo
7540ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7541 TemplateArgument::ArgKind Kind,
7542 const RecordData &Record,
7543 unsigned &Index) {
7544 switch (Kind) {
7545 case TemplateArgument::Expression:
7546 return ReadExpr(F);
7547 case TemplateArgument::Type:
7548 return GetTypeSourceInfo(F, Record, Index);
7549 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007550 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 Index);
7552 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7553 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7554 SourceLocation());
7555 }
7556 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007557 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007558 Index);
7559 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7560 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007561 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007562 EllipsisLoc);
7563 }
7564 case TemplateArgument::Null:
7565 case TemplateArgument::Integral:
7566 case TemplateArgument::Declaration:
7567 case TemplateArgument::NullPtr:
7568 case TemplateArgument::Pack:
7569 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007570 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 }
7572 llvm_unreachable("unexpected template argument loc");
7573}
7574
7575TemplateArgumentLoc
7576ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7577 const RecordData &Record, unsigned &Index) {
7578 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7579
7580 if (Arg.getKind() == TemplateArgument::Expression) {
7581 if (Record[Index++]) // bool InfoHasSameExpr.
7582 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7583 }
7584 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7585 Record, Index));
7586}
7587
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007588const ASTTemplateArgumentListInfo*
7589ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7590 const RecordData &Record,
7591 unsigned &Index) {
7592 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7593 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7594 unsigned NumArgsAsWritten = Record[Index++];
7595 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7596 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7597 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7598 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7599}
7600
Guy Benyei11169dd2012-12-18 14:30:41 +00007601Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7602 return GetDecl(ID);
7603}
7604
Richard Smith053f6c62014-05-16 23:01:30 +00007605void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007606 if (NumCurrentElementsDeserializing) {
7607 // We arrange to not care about the complete redeclaration chain while we're
7608 // deserializing. Just remember that the AST has marked this one as complete
7609 // but that it's not actually complete yet, so we know we still need to
7610 // complete it later.
7611 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7612 return;
7613 }
7614
Richard Smith053f6c62014-05-16 23:01:30 +00007615 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7616
Richard Smith053f6c62014-05-16 23:01:30 +00007617 // If this is a named declaration, complete it by looking it up
7618 // within its context.
7619 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007620 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007621 // all mergeable entities within it.
7622 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7623 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7624 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007625 if (!getContext().getLangOpts().CPlusPlus &&
7626 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007627 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007628 // the identifier instead. (For C++ modules, we don't store decls
7629 // in the serialized identifier table, so we do the lookup in the TU.)
7630 auto *II = Name.getAsIdentifierInfo();
7631 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007632 if (II->isOutOfDate())
7633 updateOutOfDateIdentifier(*II);
7634 } else
7635 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007636 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007637 // Find all declarations of this kind from the relevant context.
7638 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7639 auto *DC = cast<DeclContext>(DCDecl);
7640 SmallVector<Decl*, 8> Decls;
7641 FindExternalLexicalDecls(
7642 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7643 }
Richard Smith053f6c62014-05-16 23:01:30 +00007644 }
7645 }
Richard Smith50895422015-01-31 03:04:55 +00007646
7647 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7648 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7649 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7650 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7651 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7652 if (auto *Template = FD->getPrimaryTemplate())
7653 Template->LoadLazySpecializations();
7654 }
Richard Smith053f6c62014-05-16 23:01:30 +00007655}
7656
Richard Smithc2bb8182015-03-24 06:36:48 +00007657CXXCtorInitializer **
7658ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7659 RecordLocation Loc = getLocalBitOffset(Offset);
7660 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7661 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007662 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7663 Error(std::move(Err));
7664 return nullptr;
7665 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007666 ReadingKindTracker ReadingKind(Read_Decl, *this);
7667
7668 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007669 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7670 if (!MaybeCode) {
7671 Error(MaybeCode.takeError());
7672 return nullptr;
7673 }
7674 unsigned Code = MaybeCode.get();
7675
7676 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7677 if (!MaybeRecCode) {
7678 Error(MaybeRecCode.takeError());
7679 return nullptr;
7680 }
7681 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007682 Error("malformed AST file: missing C++ ctor initializers");
7683 return nullptr;
7684 }
7685
7686 unsigned Idx = 0;
7687 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7688}
7689
Guy Benyei11169dd2012-12-18 14:30:41 +00007690CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007691 assert(ContextObj && "reading base specifiers with no AST context");
7692 ASTContext &Context = *ContextObj;
7693
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007695 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007697 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7698 Error(std::move(Err));
7699 return nullptr;
7700 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 ReadingKindTracker ReadingKind(Read_Decl, *this);
7702 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007703
7704 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7705 if (!MaybeCode) {
7706 Error(MaybeCode.takeError());
7707 return nullptr;
7708 }
7709 unsigned Code = MaybeCode.get();
7710
7711 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7712 if (!MaybeRecCode) {
7713 Error(MaybeCode.takeError());
7714 return nullptr;
7715 }
7716 unsigned RecCode = MaybeRecCode.get();
7717
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007719 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007720 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 }
7722
7723 unsigned Idx = 0;
7724 unsigned NumBases = Record[Idx++];
7725 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007726 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007727 for (unsigned I = 0; I != NumBases; ++I)
7728 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7729 return Bases;
7730}
7731
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007732serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007733ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7734 if (LocalID < NUM_PREDEF_DECL_IDS)
7735 return LocalID;
7736
Richard Smith37a93df2017-02-18 00:32:02 +00007737 if (!F.ModuleOffsetMap.empty())
7738 ReadModuleOffsetMap(F);
7739
Guy Benyei11169dd2012-12-18 14:30:41 +00007740 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7741 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7742 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007743
Guy Benyei11169dd2012-12-18 14:30:41 +00007744 return LocalID + I->second;
7745}
7746
7747bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7748 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007749 // Predefined decls aren't from any module.
7750 if (ID < NUM_PREDEF_DECL_IDS)
7751 return false;
7752
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007753 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007754 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755}
7756
Douglas Gregor9f782892013-01-21 15:25:38 +00007757ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007758 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007759 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7761 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7762 return I->second;
7763}
7764
7765SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7766 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007767 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007768
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7770
7771 if (Index > DeclsLoaded.size()) {
7772 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007773 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007775
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 if (Decl *D = DeclsLoaded[Index])
7777 return D->getLocation();
7778
Richard Smithcb34bd32016-03-27 07:28:06 +00007779 SourceLocation Loc;
7780 DeclCursorForID(ID, Loc);
7781 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007782}
7783
Richard Smithfe620d22015-03-05 23:24:12 +00007784static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7785 switch (ID) {
7786 case PREDEF_DECL_NULL_ID:
7787 return nullptr;
7788
7789 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7790 return Context.getTranslationUnitDecl();
7791
7792 case PREDEF_DECL_OBJC_ID_ID:
7793 return Context.getObjCIdDecl();
7794
7795 case PREDEF_DECL_OBJC_SEL_ID:
7796 return Context.getObjCSelDecl();
7797
7798 case PREDEF_DECL_OBJC_CLASS_ID:
7799 return Context.getObjCClassDecl();
7800
7801 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7802 return Context.getObjCProtocolDecl();
7803
7804 case PREDEF_DECL_INT_128_ID:
7805 return Context.getInt128Decl();
7806
7807 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7808 return Context.getUInt128Decl();
7809
7810 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7811 return Context.getObjCInstanceTypeDecl();
7812
7813 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7814 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007815
Richard Smith9b88a4c2015-07-27 05:40:23 +00007816 case PREDEF_DECL_VA_LIST_TAG:
7817 return Context.getVaListTagDecl();
7818
Charles Davisc7d5c942015-09-17 20:55:33 +00007819 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7820 return Context.getBuiltinMSVaListDecl();
7821
Richard Smithf19e1272015-03-07 00:04:49 +00007822 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7823 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007824
7825 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7826 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007827
7828 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7829 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007830
7831 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7832 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007833
7834 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7835 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007836 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007837 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007838}
7839
Richard Smithcd45dbc2014-04-19 03:48:30 +00007840Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007841 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007842 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007843 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007844 if (D) {
7845 // Track that we have merged the declaration with ID \p ID into the
7846 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007847 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007848 if (Merged.empty())
7849 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007850 }
Richard Smithfe620d22015-03-05 23:24:12 +00007851 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007853
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7855
7856 if (Index >= DeclsLoaded.size()) {
7857 assert(0 && "declaration ID out-of-range for AST file");
7858 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007859 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007861
7862 return DeclsLoaded[Index];
7863}
7864
7865Decl *ASTReader::GetDecl(DeclID ID) {
7866 if (ID < NUM_PREDEF_DECL_IDS)
7867 return GetExistingDecl(ID);
7868
7869 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7870
7871 if (Index >= DeclsLoaded.size()) {
7872 assert(0 && "declaration ID out-of-range for AST file");
7873 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007874 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007875 }
7876
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 if (!DeclsLoaded[Index]) {
7878 ReadDeclRecord(ID);
7879 if (DeserializationListener)
7880 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7881 }
7882
7883 return DeclsLoaded[Index];
7884}
7885
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007886DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 DeclID GlobalID) {
7888 if (GlobalID < NUM_PREDEF_DECL_IDS)
7889 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007890
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7892 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7893 ModuleFile *Owner = I->second;
7894
7895 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7896 = M.GlobalToLocalDeclIDs.find(Owner);
7897 if (Pos == M.GlobalToLocalDeclIDs.end())
7898 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007899
Guy Benyei11169dd2012-12-18 14:30:41 +00007900 return GlobalID - Owner->BaseDeclID + Pos->second;
7901}
7902
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007903serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 const RecordData &Record,
7905 unsigned &Idx) {
7906 if (Idx >= Record.size()) {
7907 Error("Corrupted AST file");
7908 return 0;
7909 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007910
Guy Benyei11169dd2012-12-18 14:30:41 +00007911 return getGlobalDeclID(F, Record[Idx++]);
7912}
7913
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007914/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007915///
7916/// This operation will read a new statement from the external
7917/// source each time it is called, and is meant to be used via a
7918/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7919Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7920 // Switch case IDs are per Decl.
7921 ClearSwitchCaseIDs();
7922
7923 // Offset here is a global offset across the entire chain.
7924 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007925 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7926 Error(std::move(Err));
7927 return nullptr;
7928 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007929 assert(NumCurrentElementsDeserializing == 0 &&
7930 "should not be called while already deserializing");
7931 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007932 return ReadStmtFromStream(*Loc.F);
7933}
7934
Richard Smith3cb15722015-08-05 22:41:45 +00007935void ASTReader::FindExternalLexicalDecls(
7936 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7937 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007938 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7939
Richard Smith9ccdd932015-08-06 22:14:12 +00007940 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007941 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7942 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7943 auto K = (Decl::Kind)+LexicalDecls[I];
7944 if (!IsKindWeWant(K))
7945 continue;
7946
7947 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7948
7949 // Don't add predefined declarations to the lexical context more
7950 // than once.
7951 if (ID < NUM_PREDEF_DECL_IDS) {
7952 if (PredefsVisited[ID])
7953 continue;
7954
7955 PredefsVisited[ID] = true;
7956 }
7957
7958 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007959 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007960 if (!DC->isDeclInLexicalTraversal(D))
7961 Decls.push_back(D);
7962 }
7963 }
7964 };
7965
7966 if (isa<TranslationUnitDecl>(DC)) {
7967 for (auto Lexical : TULexicalDecls)
7968 Visit(Lexical.first, Lexical.second);
7969 } else {
7970 auto I = LexicalDecls.find(DC);
7971 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007972 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007973 }
7974
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007976}
7977
7978namespace {
7979
7980class DeclIDComp {
7981 ASTReader &Reader;
7982 ModuleFile &Mod;
7983
7984public:
7985 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7986
7987 bool operator()(LocalDeclID L, LocalDeclID R) const {
7988 SourceLocation LHS = getLocation(L);
7989 SourceLocation RHS = getLocation(R);
7990 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7991 }
7992
7993 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7994 SourceLocation RHS = getLocation(R);
7995 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7996 }
7997
7998 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7999 SourceLocation LHS = getLocation(L);
8000 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8001 }
8002
8003 SourceLocation getLocation(LocalDeclID ID) const {
8004 return Reader.getSourceManager().getFileLoc(
8005 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
8006 }
8007};
8008
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008009} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00008010
8011void ASTReader::FindFileRegionDecls(FileID File,
8012 unsigned Offset, unsigned Length,
8013 SmallVectorImpl<Decl *> &Decls) {
8014 SourceManager &SM = getSourceManager();
8015
8016 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8017 if (I == FileDeclIDs.end())
8018 return;
8019
8020 FileDeclsInfo &DInfo = I->second;
8021 if (DInfo.Decls.empty())
8022 return;
8023
8024 SourceLocation
8025 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8026 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8027
8028 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00008029 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
8030 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 if (BeginIt != DInfo.Decls.begin())
8032 --BeginIt;
8033
8034 // If we are pointing at a top-level decl inside an objc container, we need
8035 // to backtrack until we find it otherwise we will fail to report that the
8036 // region overlaps with an objc container.
8037 while (BeginIt != DInfo.Decls.begin() &&
8038 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
8039 ->isTopLevelDeclInObjCContainer())
8040 --BeginIt;
8041
Fangrui Song7264a472019-07-03 08:13:17 +00008042 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
8043 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 if (EndIt != DInfo.Decls.end())
8045 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008046
Guy Benyei11169dd2012-12-18 14:30:41 +00008047 for (ArrayRef<serialization::LocalDeclID>::iterator
8048 DIt = BeginIt; DIt != EndIt; ++DIt)
8049 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
8050}
8051
Richard Smith9ce12e32013-02-07 03:30:24 +00008052bool
Guy Benyei11169dd2012-12-18 14:30:41 +00008053ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
8054 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00008055 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 "DeclContext has no visible decls in storage");
8057 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00008058 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00008059
Richard Smithd88a7f12015-09-01 20:35:42 +00008060 auto It = Lookups.find(DC);
8061 if (It == Lookups.end())
8062 return false;
8063
Richard Smith8c913ec2014-08-14 02:21:01 +00008064 Deserializing LookupResults(this);
8065
Richard Smithd88a7f12015-09-01 20:35:42 +00008066 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008068 for (DeclID ID : It->second.Table.find(Name)) {
8069 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008070 if (ND->getDeclName() == Name)
8071 Decls.push_back(ND);
8072 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008073
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 ++NumVisibleDeclContextsRead;
8075 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00008076 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008077}
8078
Guy Benyei11169dd2012-12-18 14:30:41 +00008079void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8080 if (!DC->hasExternalVisibleStorage())
8081 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00008082
8083 auto It = Lookups.find(DC);
8084 assert(It != Lookups.end() &&
8085 "have external visible storage but no lookup tables");
8086
Craig Topper79be4cd2013-07-05 04:33:53 +00008087 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00008088
Vedant Kumar48b4f762018-04-14 01:40:48 +00008089 for (DeclID ID : It->second.Table.findAll()) {
8090 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008091 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00008092 }
8093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 ++NumVisibleDeclContextsRead;
8095
Vedant Kumar48b4f762018-04-14 01:40:48 +00008096 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8097 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8098 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8100}
8101
Richard Smithd88a7f12015-09-01 20:35:42 +00008102const serialization::reader::DeclContextLookupTable *
8103ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8104 auto I = Lookups.find(Primary);
8105 return I == Lookups.end() ? nullptr : &I->second;
8106}
8107
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008108/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00008109/// before receiving the implementation, and codegen depends on this.
8110/// We simulate this by deserializing and passing to consumer the methods of the
8111/// implementation before passing the deserialized implementation decl.
8112static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8113 ASTConsumer *Consumer) {
8114 assert(ImplD && Consumer);
8115
Aaron Ballmanaff18c02014-03-13 19:03:34 +00008116 for (auto *I : ImplD->methods())
8117 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00008118
8119 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8120}
8121
Guy Benyei11169dd2012-12-18 14:30:41 +00008122void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008123 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 PassObjCImplDeclToConsumer(ImplD, Consumer);
8125 else
8126 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8127}
8128
8129void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8130 this->Consumer = Consumer;
8131
Richard Smith9e2341d2015-03-23 03:25:59 +00008132 if (Consumer)
8133 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00008134
8135 if (DeserializationListener)
8136 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00008137}
8138
8139void ASTReader::PrintStats() {
8140 std::fprintf(stderr, "*** AST File Statistics:\n");
8141
8142 unsigned NumTypesLoaded
8143 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
8144 QualType());
8145 unsigned NumDeclsLoaded
8146 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008147 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 unsigned NumIdentifiersLoaded
8149 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
8150 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008151 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008152 unsigned NumMacrosLoaded
8153 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
8154 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008155 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 unsigned NumSelectorsLoaded
8157 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
8158 SelectorsLoaded.end(),
8159 Selector());
8160
8161 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8162 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8163 NumSLocEntriesRead, TotalNumSLocEntries,
8164 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8165 if (!TypesLoaded.empty())
8166 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8167 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8168 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8169 if (!DeclsLoaded.empty())
8170 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8171 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8172 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8173 if (!IdentifiersLoaded.empty())
8174 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8175 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8176 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8177 if (!MacrosLoaded.empty())
8178 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8179 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8180 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8181 if (!SelectorsLoaded.empty())
8182 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8183 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8184 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8185 if (TotalNumStatements)
8186 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8187 NumStatementsRead, TotalNumStatements,
8188 ((float)NumStatementsRead/TotalNumStatements * 100));
8189 if (TotalNumMacros)
8190 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8191 NumMacrosRead, TotalNumMacros,
8192 ((float)NumMacrosRead/TotalNumMacros * 100));
8193 if (TotalLexicalDeclContexts)
8194 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8195 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8196 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8197 * 100));
8198 if (TotalVisibleDeclContexts)
8199 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8200 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8201 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8202 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008203 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8205 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8206 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8207 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008208 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008209 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8210 NumMethodPoolHits, NumMethodPoolLookups,
8211 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008212 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008213 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8214 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8215 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8216 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008217 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00008218 std::fprintf(stderr,
8219 " %u / %u identifier table lookups succeeded (%f%%)\n",
8220 NumIdentifierLookupHits, NumIdentifierLookups,
8221 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00008222
Douglas Gregore060e572013-01-25 01:03:03 +00008223 if (GlobalIndex) {
8224 std::fprintf(stderr, "\n");
8225 GlobalIndex->printStats();
8226 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008227
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 std::fprintf(stderr, "\n");
8229 dump();
8230 std::fprintf(stderr, "\n");
8231}
8232
8233template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00008234LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00008235dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008236 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 InitialCapacity> &Map) {
8238 if (Map.begin() == Map.end())
8239 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008240
Vedant Kumar48b4f762018-04-14 01:40:48 +00008241 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8242
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008244 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8245 I != IEnd; ++I) {
8246 llvm::errs() << " " << I->first << " -> " << I->second->FileName
8247 << "\n";
8248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008249}
8250
Yaron Kerencdae9412016-01-29 19:38:18 +00008251LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8253 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8254 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8255 dumpModuleIDMap("Global type map", GlobalTypeMap);
8256 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8257 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8258 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8259 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8260 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008261 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00008262 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008263
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008265 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00008266 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00008267}
8268
8269/// Return the amount of memory used by memory buffers, breaking down
8270/// by heap-backed versus mmap'ed memory.
8271void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008272 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00008273 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008274 size_t bytes = buf->getBufferSize();
8275 switch (buf->getBufferKind()) {
8276 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8277 sizes.malloc_bytes += bytes;
8278 break;
8279 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8280 sizes.mmap_bytes += bytes;
8281 break;
8282 }
8283 }
8284 }
8285}
8286
8287void ASTReader::InitializeSema(Sema &S) {
8288 SemaObj = &S;
8289 S.addExternalSource(this);
8290
8291 // Makes sure any declarations that were deserialized "too early"
8292 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008293 for (uint64_t ID : PreloadedDeclIDs) {
8294 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00008295 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008297 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008298
Richard Smith3d8e97e2013-10-18 06:54:39 +00008299 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 if (!FPPragmaOptions.empty()) {
8301 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00008302 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008303 }
8304
Yaxun Liu5b746652016-12-18 05:18:55 +00008305 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
8306 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
8307 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00008308
8309 UpdateSema();
8310}
8311
8312void ASTReader::UpdateSema() {
8313 assert(SemaObj && "no Sema to update");
8314
8315 // Load the offsets of the declarations that Sema references.
8316 // They will be lazily deserialized when needed.
8317 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00008318 assert(SemaDeclRefs.size() % 3 == 0);
8319 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00008320 if (!SemaObj->StdNamespace)
8321 SemaObj->StdNamespace = SemaDeclRefs[I];
8322 if (!SemaObj->StdBadAlloc)
8323 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00008324 if (!SemaObj->StdAlignValT)
8325 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00008326 }
8327 SemaDeclRefs.clear();
8328 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00008329
Nico Weber779355f2016-03-02 23:22:00 +00008330 // Update the state of pragmas. Use the same API as if we had encountered the
8331 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00008332 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00008333 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00008334 if (PragmaMSStructState != -1)
8335 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00008336 if (PointersToMembersPragmaLocation.isValid()) {
8337 SemaObj->ActOnPragmaMSPointersToMembers(
8338 (LangOptions::PragmaMSPointersToMembersKind)
8339 PragmaMSPointersToMembersState,
8340 PointersToMembersPragmaLocation);
8341 }
Justin Lebar67a78a62016-10-08 22:15:58 +00008342 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008343
8344 if (PragmaPackCurrentValue) {
8345 // The bottom of the stack might have a default value. It must be adjusted
8346 // to the current value to ensure that the packing state is preserved after
8347 // popping entries that were included/imported from a PCH/module.
8348 bool DropFirst = false;
8349 if (!PragmaPackStack.empty() &&
8350 PragmaPackStack.front().Location.isInvalid()) {
8351 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
8352 "Expected a default alignment value");
8353 SemaObj->PackStack.Stack.emplace_back(
8354 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00008355 SemaObj->PackStack.CurrentPragmaLocation,
8356 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008357 DropFirst = true;
8358 }
8359 for (const auto &Entry :
8360 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
8361 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00008362 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008363 if (PragmaPackCurrentLocation.isInvalid()) {
8364 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
8365 "Expected a default alignment value");
8366 // Keep the current values.
8367 } else {
8368 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
8369 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
8370 }
8371 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008372}
8373
Richard Smitha8d5b6a2015-07-17 19:51:03 +00008374IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 // Note that we are loading an identifier.
8376 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00008377
Douglas Gregor7211ac12013-01-25 23:32:03 +00008378 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00008379 NumIdentifierLookups,
8380 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008381
8382 // We don't need to do identifier table lookups in C++ modules (we preload
8383 // all interesting declarations, and don't need to use the scope for name
8384 // lookups). Perform the lookup in PCH files, though, since we don't build
8385 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00008386 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00008387 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008388 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00008389 break;
8390 } else {
8391 // If there is a global index, look there first to determine which modules
8392 // provably do not have any results for this identifier.
8393 GlobalModuleIndex::HitSet Hits;
8394 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8395 if (!loadGlobalIndex()) {
8396 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8397 HitsPtr = &Hits;
8398 }
8399 }
8400
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008401 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008402 }
8403
Guy Benyei11169dd2012-12-18 14:30:41 +00008404 IdentifierInfo *II = Visitor.getIdentifierInfo();
8405 markIdentifierUpToDate(II);
8406 return II;
8407}
8408
8409namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008411 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 /// identifiers stored within a set of AST files.
8413 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008414 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00008415 const ASTReader &Reader;
8416
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008417 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 /// the AST reader.
8419 unsigned Index;
8420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008421 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00008422 /// of the current AST file.
8423 ASTIdentifierLookupTable::key_iterator Current;
8424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008425 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00008426 /// the current AST file.
8427 ASTIdentifierLookupTable::key_iterator End;
8428
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008429 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00008430 bool SkipModules;
8431
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00008433 explicit ASTIdentifierIterator(const ASTReader &Reader,
8434 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00008435
Craig Topper3e89dfe2014-03-13 02:13:41 +00008436 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008438
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008439} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008440
Ben Langmuir537c5b52016-05-04 00:53:13 +00008441ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8442 bool SkipModules)
8443 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008444}
8445
8446StringRef ASTIdentifierIterator::Next() {
8447 while (Current == End) {
8448 // If we have exhausted all of our AST files, we're done.
8449 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008450 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008451
8452 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008453 ModuleFile &F = Reader.ModuleMgr[Index];
8454 if (SkipModules && F.isModule())
8455 continue;
8456
Vedant Kumar48b4f762018-04-14 01:40:48 +00008457 ASTIdentifierLookupTable *IdTable =
8458 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 Current = IdTable->key_begin();
8460 End = IdTable->key_end();
8461 }
8462
8463 // We have any identifiers remaining in the current AST file; return
8464 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008465 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008467 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008468}
8469
Ben Langmuir537c5b52016-05-04 00:53:13 +00008470namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008471
Ben Langmuir537c5b52016-05-04 00:53:13 +00008472/// A utility for appending two IdentifierIterators.
8473class ChainedIdentifierIterator : public IdentifierIterator {
8474 std::unique_ptr<IdentifierIterator> Current;
8475 std::unique_ptr<IdentifierIterator> Queued;
8476
8477public:
8478 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8479 std::unique_ptr<IdentifierIterator> Second)
8480 : Current(std::move(First)), Queued(std::move(Second)) {}
8481
8482 StringRef Next() override {
8483 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008484 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008485
8486 StringRef result = Current->Next();
8487 if (!result.empty())
8488 return result;
8489
8490 // Try the queued iterator, which may itself be empty.
8491 Current.reset();
8492 std::swap(Current, Queued);
8493 return Next();
8494 }
8495};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008496
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008497} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008498
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008499IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008500 if (!loadGlobalIndex()) {
8501 std::unique_ptr<IdentifierIterator> ReaderIter(
8502 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8503 std::unique_ptr<IdentifierIterator> ModulesIter(
8504 GlobalIndex->createIdentifierIterator());
8505 return new ChainedIdentifierIterator(std::move(ReaderIter),
8506 std::move(ModulesIter));
8507 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008508
Guy Benyei11169dd2012-12-18 14:30:41 +00008509 return new ASTIdentifierIterator(*this);
8510}
8511
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008512namespace clang {
8513namespace serialization {
8514
Guy Benyei11169dd2012-12-18 14:30:41 +00008515 class ReadMethodPoolVisitor {
8516 ASTReader &Reader;
8517 Selector Sel;
8518 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008519 unsigned InstanceBits = 0;
8520 unsigned FactoryBits = 0;
8521 bool InstanceHasMoreThanOneDecl = false;
8522 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008523 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8524 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008525
8526 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008527 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008528 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008529 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008530
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008531 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008532 if (!M.SelectorLookupTable)
8533 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008534
Guy Benyei11169dd2012-12-18 14:30:41 +00008535 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008536 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 return true;
8538
Richard Smithbdf2d932015-07-30 03:37:16 +00008539 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008540 ASTSelectorLookupTable *PoolTable
8541 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008542 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008543 if (Pos == PoolTable->end())
8544 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008545
Richard Smithbdf2d932015-07-30 03:37:16 +00008546 ++Reader.NumMethodPoolTableHits;
8547 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 // FIXME: Not quite happy with the statistics here. We probably should
8549 // disable this tracking when called via LoadSelector.
8550 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008551 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008552 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008553 if (Reader.DeserializationListener)
8554 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008555
Richard Smithbdf2d932015-07-30 03:37:16 +00008556 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8557 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8558 InstanceBits = Data.InstanceBits;
8559 FactoryBits = Data.FactoryBits;
8560 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8561 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 return true;
8563 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008565 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008566 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8567 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008568 }
8569
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008570 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008571 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008572 return FactoryMethods;
8573 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008574
8575 unsigned getInstanceBits() const { return InstanceBits; }
8576 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008577
Nico Weberff4b35e2014-12-27 22:14:15 +00008578 bool instanceHasMoreThanOneDecl() const {
8579 return InstanceHasMoreThanOneDecl;
8580 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008581
Nico Weberff4b35e2014-12-27 22:14:15 +00008582 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008584
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008585} // namespace serialization
8586} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008587
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008588/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008589static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8590 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008591 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8592 S.addMethodToGlobalList(&List, Methods[I]);
8593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008594}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596void ASTReader::ReadMethodPool(Selector Sel) {
8597 // Get the selector generation and update it to the current generation.
8598 unsigned &Generation = SelectorGeneration[Sel];
8599 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008600 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008601 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008602
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008604 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008605 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008606 ModuleMgr.visit(Visitor);
8607
Guy Benyei11169dd2012-12-18 14:30:41 +00008608 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008609 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008611
8612 ++NumMethodPoolHits;
8613
Guy Benyei11169dd2012-12-18 14:30:41 +00008614 if (!getSema())
8615 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008616
Guy Benyei11169dd2012-12-18 14:30:41 +00008617 Sema &S = *getSema();
8618 Sema::GlobalMethodPool::iterator Pos
8619 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008620
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008621 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008622 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008623 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008624 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008625
8626 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8627 // when building a module we keep every method individually and may need to
8628 // update hasMoreThanOneDecl as we add the methods.
8629 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8630 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008631}
8632
Manman Rena0f31a02016-04-29 19:04:05 +00008633void ASTReader::updateOutOfDateSelector(Selector Sel) {
8634 if (SelectorOutOfDate[Sel])
8635 ReadMethodPool(Sel);
8636}
8637
Guy Benyei11169dd2012-12-18 14:30:41 +00008638void ASTReader::ReadKnownNamespaces(
8639 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8640 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008641
Vedant Kumar48b4f762018-04-14 01:40:48 +00008642 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8643 if (NamespaceDecl *Namespace
8644 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008645 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008646 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008647}
8648
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008649void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008650 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008651 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008652 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008653 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008654 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008655 Undefined.insert(std::make_pair(D, Loc));
8656 }
8657}
Nick Lewycky8334af82013-01-26 00:35:08 +00008658
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008659void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8660 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8661 Exprs) {
8662 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008663 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008664 uint64_t Count = DelayedDeleteExprs[Idx++];
8665 for (uint64_t C = 0; C < Count; ++C) {
8666 SourceLocation DeleteLoc =
8667 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8668 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8669 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8670 }
8671 }
8672}
8673
Guy Benyei11169dd2012-12-18 14:30:41 +00008674void ASTReader::ReadTentativeDefinitions(
8675 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008676 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8677 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008678 if (Var)
8679 TentativeDefs.push_back(Var);
8680 }
8681 TentativeDefinitions.clear();
8682}
8683
8684void ASTReader::ReadUnusedFileScopedDecls(
8685 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008686 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8687 DeclaratorDecl *D
8688 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008689 if (D)
8690 Decls.push_back(D);
8691 }
8692 UnusedFileScopedDecls.clear();
8693}
8694
8695void ASTReader::ReadDelegatingConstructors(
8696 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008697 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8698 CXXConstructorDecl *D
8699 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008700 if (D)
8701 Decls.push_back(D);
8702 }
8703 DelegatingCtorDecls.clear();
8704}
8705
8706void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008707 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8708 TypedefNameDecl *D
8709 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008710 if (D)
8711 Decls.push_back(D);
8712 }
8713 ExtVectorDecls.clear();
8714}
8715
Nico Weber72889432014-09-06 01:25:55 +00008716void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8717 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008718 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8719 ++I) {
8720 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8721 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008722 if (D)
8723 Decls.insert(D);
8724 }
8725 UnusedLocalTypedefNameCandidates.clear();
8726}
8727
Guy Benyei11169dd2012-12-18 14:30:41 +00008728void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008729 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 if (ReferencedSelectorsData.empty())
8731 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008732
Guy Benyei11169dd2012-12-18 14:30:41 +00008733 // If there are @selector references added them to its pool. This is for
8734 // implementation of -Wselector.
8735 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8736 unsigned I = 0;
8737 while (I < DataSize) {
8738 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8739 SourceLocation SelLoc
8740 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8741 Sels.push_back(std::make_pair(Sel, SelLoc));
8742 }
8743 ReferencedSelectorsData.clear();
8744}
8745
8746void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008747 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008748 if (WeakUndeclaredIdentifiers.empty())
8749 return;
8750
8751 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008752 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008753 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008754 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008755 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8756 SourceLocation Loc
8757 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8758 bool Used = WeakUndeclaredIdentifiers[I++];
8759 WeakInfo WI(AliasId, Loc);
8760 WI.setUsed(Used);
8761 WeakIDs.push_back(std::make_pair(WeakId, WI));
8762 }
8763 WeakUndeclaredIdentifiers.clear();
8764}
8765
8766void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8767 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8768 ExternalVTableUse VT;
8769 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8770 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8771 VT.DefinitionRequired = VTableUses[Idx++];
8772 VTables.push_back(VT);
8773 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008774
Guy Benyei11169dd2012-12-18 14:30:41 +00008775 VTableUses.clear();
8776}
8777
8778void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008779 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008780 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008781 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008782 SourceLocation Loc
8783 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8784
8785 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008787 PendingInstantiations.clear();
8788}
8789
Richard Smithe40f2ba2013-08-07 21:41:30 +00008790void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008791 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8792 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008793 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8794 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008795 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008796
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008797 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008798 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8799
8800 ModuleFile *F = getOwningModuleFile(LT->D);
8801 assert(F && "No module");
8802
8803 unsigned TokN = LateParsedTemplates[Idx++];
8804 LT->Toks.reserve(TokN);
8805 for (unsigned T = 0; T < TokN; ++T)
8806 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8807
Justin Lebar28f09c52016-10-10 16:26:08 +00008808 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008809 }
8810
8811 LateParsedTemplates.clear();
8812}
8813
Guy Benyei11169dd2012-12-18 14:30:41 +00008814void ASTReader::LoadSelector(Selector Sel) {
8815 // It would be complicated to avoid reading the methods anyway. So don't.
8816 ReadMethodPool(Sel);
8817}
8818
8819void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8820 assert(ID && "Non-zero identifier ID required");
8821 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8822 IdentifiersLoaded[ID - 1] = II;
8823 if (DeserializationListener)
8824 DeserializationListener->IdentifierRead(ID, II);
8825}
8826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008827/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008828/// identifier.
8829///
8830/// If the AST reader is currently in a state where the given declaration IDs
8831/// cannot safely be resolved, they are queued until it is safe to resolve
8832/// them.
8833///
8834/// \param II an IdentifierInfo that refers to one or more globally-visible
8835/// declarations.
8836///
8837/// \param DeclIDs the set of declaration IDs with the name @p II that are
8838/// visible at global scope.
8839///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008840/// \param Decls if non-null, this vector will be populated with the set of
8841/// deserialized declarations. These declarations will not be pushed into
8842/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008843void
8844ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8845 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008846 SmallVectorImpl<Decl *> *Decls) {
8847 if (NumCurrentElementsDeserializing && !Decls) {
8848 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 return;
8850 }
8851
Vedant Kumar48b4f762018-04-14 01:40:48 +00008852 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008853 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008854 // Queue this declaration so that it will be added to the
8855 // translation unit scope and identifier's declaration chain
8856 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008857 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008858 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008859 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008860
Vedant Kumar48b4f762018-04-14 01:40:48 +00008861 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008862
8863 // If we're simply supposed to record the declarations, do so now.
8864 if (Decls) {
8865 Decls->push_back(D);
8866 continue;
8867 }
8868
8869 // Introduce this declaration into the translation-unit scope
8870 // and add it to the declaration chain for this identifier, so
8871 // that (unqualified) name lookup will find it.
8872 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008873 }
8874}
8875
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008876IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008877 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008878 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008879
8880 if (IdentifiersLoaded.empty()) {
8881 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008882 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008883 }
8884
8885 ID -= 1;
8886 if (!IdentifiersLoaded[ID]) {
8887 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8888 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8889 ModuleFile *M = I->second;
8890 unsigned Index = ID - M->BaseIdentifierID;
8891 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8892
8893 // All of the strings in the AST file are preceded by a 16-bit length.
8894 // Extract that 16-bit length to avoid having to execute strlen().
8895 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8896 // unsigned integers. This is important to avoid integer overflow when
8897 // we cast them to 'unsigned'.
8898 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8899 unsigned StrLen = (((unsigned) StrLenPtr[0])
8900 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008901 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8902 IdentifiersLoaded[ID] = &II;
8903 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008904 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008905 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008906 }
8907
8908 return IdentifiersLoaded[ID];
8909}
8910
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008911IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8912 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008913}
8914
8915IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8916 if (LocalID < NUM_PREDEF_IDENT_IDS)
8917 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008918
Richard Smith37a93df2017-02-18 00:32:02 +00008919 if (!M.ModuleOffsetMap.empty())
8920 ReadModuleOffsetMap(M);
8921
Guy Benyei11169dd2012-12-18 14:30:41 +00008922 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8923 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008924 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008925 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008926
Guy Benyei11169dd2012-12-18 14:30:41 +00008927 return LocalID + I->second;
8928}
8929
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008930MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008931 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008932 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008933
8934 if (MacrosLoaded.empty()) {
8935 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008936 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008937 }
8938
8939 ID -= NUM_PREDEF_MACRO_IDS;
8940 if (!MacrosLoaded[ID]) {
8941 GlobalMacroMapType::iterator I
8942 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8943 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8944 ModuleFile *M = I->second;
8945 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008946 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008947
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008948 if (DeserializationListener)
8949 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8950 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008951 }
8952
8953 return MacrosLoaded[ID];
8954}
8955
8956MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8957 if (LocalID < NUM_PREDEF_MACRO_IDS)
8958 return LocalID;
8959
Richard Smith37a93df2017-02-18 00:32:02 +00008960 if (!M.ModuleOffsetMap.empty())
8961 ReadModuleOffsetMap(M);
8962
Guy Benyei11169dd2012-12-18 14:30:41 +00008963 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8964 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8965 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8966
8967 return LocalID + I->second;
8968}
8969
8970serialization::SubmoduleID
8971ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8972 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8973 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008974
Richard Smith37a93df2017-02-18 00:32:02 +00008975 if (!M.ModuleOffsetMap.empty())
8976 ReadModuleOffsetMap(M);
8977
Guy Benyei11169dd2012-12-18 14:30:41 +00008978 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8979 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008980 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008981 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008982
Guy Benyei11169dd2012-12-18 14:30:41 +00008983 return LocalID + I->second;
8984}
8985
8986Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8987 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8988 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008989 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008990 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008991
Guy Benyei11169dd2012-12-18 14:30:41 +00008992 if (GlobalID > SubmodulesLoaded.size()) {
8993 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008994 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008995 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008996
Guy Benyei11169dd2012-12-18 14:30:41 +00008997 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8998}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008999
9000Module *ASTReader::getModule(unsigned ID) {
9001 return getSubmodule(ID);
9002}
9003
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009004bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
9005 ModuleFile *MF = getOwningModuleFile(D);
9006 return MF && MF->PCHHasObjectFile;
9007}
9008
Richard Smithd88a7f12015-09-01 20:35:42 +00009009ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
9010 if (ID & 1) {
9011 // It's a module, look it up by submodule ID.
9012 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
9013 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9014 } else {
9015 // It's a prefix (preamble, PCH, ...). Look it up by index.
9016 unsigned IndexFromEnd = ID >> 1;
9017 assert(IndexFromEnd && "got reference to unknown module file");
9018 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9019 }
9020}
9021
9022unsigned ASTReader::getModuleFileID(ModuleFile *F) {
9023 if (!F)
9024 return 1;
9025
9026 // For a file representing a module, use the submodule ID of the top-level
9027 // module as the file ID. For any other kind of file, the number of such
9028 // files loaded beforehand will be the same on reload.
9029 // FIXME: Is this true even if we have an explicit module file and a PCH?
9030 if (F->isModule())
9031 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9032
9033 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00009034 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00009035 assert(I != PCHModules.end() && "emitting reference to unknown file");
9036 return (I - PCHModules.end()) << 1;
9037}
9038
Adrian Prantl15bcf702015-06-30 17:39:43 +00009039llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
9040ASTReader::getSourceDescriptor(unsigned ID) {
9041 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00009042 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00009043
9044 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00009045 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00009046 const auto &PCHChain = ModuleMgr.pch_modules();
9047 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00009048 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00009049 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00009050 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9051 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
9052 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00009053 }
9054 return None;
9055}
9056
David Blaikie1ac9c982017-04-11 21:13:37 +00009057ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00009058 auto I = DefinitionSource.find(FD);
9059 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00009060 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00009061 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00009062}
9063
Guy Benyei11169dd2012-12-18 14:30:41 +00009064Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
9065 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9066}
9067
9068Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9069 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009070 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009071
9072 if (ID > SelectorsLoaded.size()) {
9073 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009074 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009075 }
9076
Craig Toppera13603a2014-05-22 05:54:18 +00009077 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009078 // Load this selector from the selector table.
9079 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9080 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9081 ModuleFile &M = *I->second;
9082 ASTSelectorLookupTrait Trait(*this, M);
9083 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9084 SelectorsLoaded[ID - 1] =
9085 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9086 if (DeserializationListener)
9087 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9088 }
9089
9090 return SelectorsLoaded[ID - 1];
9091}
9092
9093Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9094 return DecodeSelector(ID);
9095}
9096
9097uint32_t ASTReader::GetNumExternalSelectors() {
9098 // ID 0 (the null selector) is considered an external selector.
9099 return getTotalNumSelectors() + 1;
9100}
9101
9102serialization::SelectorID
9103ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9104 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9105 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009106
Richard Smith37a93df2017-02-18 00:32:02 +00009107 if (!M.ModuleOffsetMap.empty())
9108 ReadModuleOffsetMap(M);
9109
Guy Benyei11169dd2012-12-18 14:30:41 +00009110 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9111 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009112 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00009113 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009114
Guy Benyei11169dd2012-12-18 14:30:41 +00009115 return LocalID + I->second;
9116}
9117
9118DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009119ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009120 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009121 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009122 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009123 switch (Kind) {
9124 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00009125 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009126
9127 case DeclarationName::ObjCZeroArgSelector:
9128 case DeclarationName::ObjCOneArgSelector:
9129 case DeclarationName::ObjCMultiArgSelector:
9130 return DeclarationName(ReadSelector(F, Record, Idx));
9131
9132 case DeclarationName::CXXConstructorName:
9133 return Context.DeclarationNames.getCXXConstructorName(
9134 Context.getCanonicalType(readType(F, Record, Idx)));
9135
9136 case DeclarationName::CXXDestructorName:
9137 return Context.DeclarationNames.getCXXDestructorName(
9138 Context.getCanonicalType(readType(F, Record, Idx)));
9139
Richard Smith35845152017-02-07 01:37:30 +00009140 case DeclarationName::CXXDeductionGuideName:
9141 return Context.DeclarationNames.getCXXDeductionGuideName(
9142 ReadDeclAs<TemplateDecl>(F, Record, Idx));
9143
Guy Benyei11169dd2012-12-18 14:30:41 +00009144 case DeclarationName::CXXConversionFunctionName:
9145 return Context.DeclarationNames.getCXXConversionFunctionName(
9146 Context.getCanonicalType(readType(F, Record, Idx)));
9147
9148 case DeclarationName::CXXOperatorName:
9149 return Context.DeclarationNames.getCXXOperatorName(
9150 (OverloadedOperatorKind)Record[Idx++]);
9151
9152 case DeclarationName::CXXLiteralOperatorName:
9153 return Context.DeclarationNames.getCXXLiteralOperatorName(
9154 GetIdentifierInfo(F, Record, Idx));
9155
9156 case DeclarationName::CXXUsingDirective:
9157 return DeclarationName::getUsingDirectiveName();
9158 }
9159
9160 llvm_unreachable("Invalid NameKind!");
9161}
9162
9163void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
9164 DeclarationNameLoc &DNLoc,
9165 DeclarationName Name,
9166 const RecordData &Record, unsigned &Idx) {
9167 switch (Name.getNameKind()) {
9168 case DeclarationName::CXXConstructorName:
9169 case DeclarationName::CXXDestructorName:
9170 case DeclarationName::CXXConversionFunctionName:
9171 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
9172 break;
9173
9174 case DeclarationName::CXXOperatorName:
9175 DNLoc.CXXOperatorName.BeginOpNameLoc
9176 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9177 DNLoc.CXXOperatorName.EndOpNameLoc
9178 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9179 break;
9180
9181 case DeclarationName::CXXLiteralOperatorName:
9182 DNLoc.CXXLiteralOperatorName.OpNameLoc
9183 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9184 break;
9185
9186 case DeclarationName::Identifier:
9187 case DeclarationName::ObjCZeroArgSelector:
9188 case DeclarationName::ObjCOneArgSelector:
9189 case DeclarationName::ObjCMultiArgSelector:
9190 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00009191 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00009192 break;
9193 }
9194}
9195
9196void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
9197 DeclarationNameInfo &NameInfo,
9198 const RecordData &Record, unsigned &Idx) {
9199 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
9200 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
9201 DeclarationNameLoc DNLoc;
9202 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
9203 NameInfo.setInfo(DNLoc);
9204}
9205
9206void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
9207 const RecordData &Record, unsigned &Idx) {
9208 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
9209 unsigned NumTPLists = Record[Idx++];
9210 Info.NumTemplParamLists = NumTPLists;
9211 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009212 Info.TemplParamLists =
9213 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00009214 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00009215 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
9216 }
9217}
9218
9219TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009220ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009221 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009222 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009223 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009224 switch (Kind) {
9225 case TemplateName::Template:
9226 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
9227
9228 case TemplateName::OverloadedTemplate: {
9229 unsigned size = Record[Idx++];
9230 UnresolvedSet<8> Decls;
9231 while (size--)
9232 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
9233
9234 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
9235 }
9236
Richard Smithb23c5e82019-05-09 03:31:27 +00009237 case TemplateName::AssumedTemplate: {
9238 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
9239 return Context.getAssumedTemplateName(Name);
9240 }
9241
Guy Benyei11169dd2012-12-18 14:30:41 +00009242 case TemplateName::QualifiedTemplate: {
9243 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9244 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009245 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009246 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
9247 }
9248
9249 case TemplateName::DependentTemplate: {
9250 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9251 if (Record[Idx++]) // isIdentifier
9252 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009253 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009254 Idx));
9255 return Context.getDependentTemplateName(NNS,
9256 (OverloadedOperatorKind)Record[Idx++]);
9257 }
9258
9259 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009260 TemplateTemplateParmDecl *param
9261 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
9262 if (!param) return TemplateName();
9263 TemplateName replacement = ReadTemplateName(F, Record, Idx);
9264 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00009265 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009266
Guy Benyei11169dd2012-12-18 14:30:41 +00009267 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009268 TemplateTemplateParmDecl *Param
9269 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009270 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009271 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009272
Guy Benyei11169dd2012-12-18 14:30:41 +00009273 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
9274 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009275 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009276
Guy Benyei11169dd2012-12-18 14:30:41 +00009277 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
9278 }
9279 }
9280
9281 llvm_unreachable("Unhandled template name kind!");
9282}
9283
Richard Smith2bb3c342015-08-09 01:05:31 +00009284TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
9285 const RecordData &Record,
9286 unsigned &Idx,
9287 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009288 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00009289 if (Canonicalize) {
9290 // The caller wants a canonical template argument. Sometimes the AST only
9291 // wants template arguments in canonical form (particularly as the template
9292 // argument lists of template specializations) so ensure we preserve that
9293 // canonical form across serialization.
9294 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
9295 return Context.getCanonicalTemplateArgument(Arg);
9296 }
9297
Vedant Kumar48b4f762018-04-14 01:40:48 +00009298 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009299 switch (Kind) {
9300 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00009301 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00009302 case TemplateArgument::Type:
9303 return TemplateArgument(readType(F, Record, Idx));
9304 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009305 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00009306 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009307 }
9308 case TemplateArgument::NullPtr:
9309 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
9310 case TemplateArgument::Integral: {
9311 llvm::APSInt Value = ReadAPSInt(Record, Idx);
9312 QualType T = readType(F, Record, Idx);
9313 return TemplateArgument(Context, Value, T);
9314 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009315 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00009316 return TemplateArgument(ReadTemplateName(F, Record, Idx));
9317 case TemplateArgument::TemplateExpansion: {
9318 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00009319 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00009320 if (unsigned NumExpansions = Record[Idx++])
9321 NumTemplateExpansions = NumExpansions - 1;
9322 return TemplateArgument(Name, NumTemplateExpansions);
9323 }
9324 case TemplateArgument::Expression:
9325 return TemplateArgument(ReadExpr(F));
9326 case TemplateArgument::Pack: {
9327 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009328 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00009329 for (unsigned I = 0; I != NumArgs; ++I)
9330 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00009331 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00009332 }
9333 }
9334
9335 llvm_unreachable("Unhandled template argument kind!");
9336}
9337
9338TemplateParameterList *
9339ASTReader::ReadTemplateParameterList(ModuleFile &F,
9340 const RecordData &Record, unsigned &Idx) {
9341 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
9342 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
9343 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
9344
9345 unsigned NumParams = Record[Idx++];
9346 SmallVector<NamedDecl *, 16> Params;
9347 Params.reserve(NumParams);
9348 while (NumParams--)
9349 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
9350
Saar Raz0330fba2019-10-15 18:44:06 +00009351 bool HasRequiresClause = Record[Idx++];
9352 Expr *RequiresClause = HasRequiresClause ? ReadExpr(F) : nullptr;
9353
Richard Smithdbafb6c2017-06-29 23:23:46 +00009354 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00009355 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00009356 return TemplateParams;
9357}
9358
9359void
9360ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00009361ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00009362 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00009363 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009364 unsigned NumTemplateArgs = Record[Idx++];
9365 TemplArgs.reserve(NumTemplateArgs);
9366 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00009367 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00009368}
9369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009370/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00009371void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00009372 const RecordData &Record, unsigned &Idx) {
9373 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009374 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00009375 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00009376 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009377 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009378 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00009379 }
9380}
9381
9382CXXBaseSpecifier
9383ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
9384 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009385 bool isVirtual = static_cast<bool>(Record[Idx++]);
9386 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
9387 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
9388 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009389 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
9390 SourceRange Range = ReadSourceRange(F, Record, Idx);
9391 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009392 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00009393 EllipsisLoc);
9394 Result.setInheritConstructors(inheritConstructors);
9395 return Result;
9396}
9397
Richard Smithc2bb8182015-03-24 06:36:48 +00009398CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00009399ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
9400 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009401 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009402 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009403 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009404 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00009405 for (unsigned i = 0; i != NumInitializers; ++i) {
9406 TypeSourceInfo *TInfo = nullptr;
9407 bool IsBaseVirtual = false;
9408 FieldDecl *Member = nullptr;
9409 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009410
Vedant Kumar48b4f762018-04-14 01:40:48 +00009411 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009412 switch (Type) {
9413 case CTOR_INITIALIZER_BASE:
9414 TInfo = GetTypeSourceInfo(F, Record, Idx);
9415 IsBaseVirtual = Record[Idx++];
9416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009417
Richard Smithc2bb8182015-03-24 06:36:48 +00009418 case CTOR_INITIALIZER_DELEGATING:
9419 TInfo = GetTypeSourceInfo(F, Record, Idx);
9420 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009421
Richard Smithc2bb8182015-03-24 06:36:48 +00009422 case CTOR_INITIALIZER_MEMBER:
9423 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
9424 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009425
Richard Smithc2bb8182015-03-24 06:36:48 +00009426 case CTOR_INITIALIZER_INDIRECT_MEMBER:
9427 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
9428 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009429 }
Richard Smithc2bb8182015-03-24 06:36:48 +00009430
9431 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
9432 Expr *Init = ReadExpr(F);
9433 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
9434 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00009435
9436 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00009437 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00009438 BOMInit = new (Context)
9439 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9440 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009441 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00009442 BOMInit = new (Context)
9443 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009444 else if (Member)
9445 BOMInit = new (Context)
9446 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9447 Init, RParenLoc);
9448 else
9449 BOMInit = new (Context)
9450 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9451 LParenLoc, Init, RParenLoc);
9452
Richard Smith418ed822016-12-14 19:45:03 +00009453 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00009454 unsigned SourceOrder = Record[Idx++];
9455 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00009456 }
9457
Richard Smithc2bb8182015-03-24 06:36:48 +00009458 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00009459 }
9460
Richard Smithc2bb8182015-03-24 06:36:48 +00009461 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00009462}
9463
9464NestedNameSpecifier *
9465ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
9466 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009467 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009468 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00009469 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009470 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009471 NestedNameSpecifier::SpecifierKind Kind
9472 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009473 switch (Kind) {
9474 case NestedNameSpecifier::Identifier: {
9475 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
9476 NNS = NestedNameSpecifier::Create(Context, Prev, II);
9477 break;
9478 }
9479
9480 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009481 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009482 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
9483 break;
9484 }
9485
9486 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009487 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009488 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9489 break;
9490 }
9491
9492 case NestedNameSpecifier::TypeSpec:
9493 case NestedNameSpecifier::TypeSpecWithTemplate: {
9494 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9495 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009496 return nullptr;
9497
Guy Benyei11169dd2012-12-18 14:30:41 +00009498 bool Template = Record[Idx++];
9499 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9500 break;
9501 }
9502
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009503 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009504 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9505 // No associated value, and there can't be a prefix.
9506 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009507
9508 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009509 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009510 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9511 break;
9512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009513 }
9514 Prev = NNS;
9515 }
9516 return NNS;
9517}
9518
9519NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009520ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009521 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009522 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009523 unsigned N = Record[Idx++];
9524 NestedNameSpecifierLocBuilder Builder;
9525 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009526 NestedNameSpecifier::SpecifierKind Kind
9527 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009528 switch (Kind) {
9529 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009530 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009531 SourceRange Range = ReadSourceRange(F, Record, Idx);
9532 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9533 break;
9534 }
9535
9536 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009537 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009538 SourceRange Range = ReadSourceRange(F, Record, Idx);
9539 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9540 break;
9541 }
9542
9543 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009544 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009545 SourceRange Range = ReadSourceRange(F, Record, Idx);
9546 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9547 break;
9548 }
9549
9550 case NestedNameSpecifier::TypeSpec:
9551 case NestedNameSpecifier::TypeSpecWithTemplate: {
9552 bool Template = Record[Idx++];
9553 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9554 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009555 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009556 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9557
9558 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009559 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009560 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9561 T->getTypeLoc(), ColonColonLoc);
9562 break;
9563 }
9564
9565 case NestedNameSpecifier::Global: {
9566 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9567 Builder.MakeGlobal(Context, ColonColonLoc);
9568 break;
9569 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009570
9571 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009572 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009573 SourceRange Range = ReadSourceRange(F, Record, Idx);
9574 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9575 break;
9576 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009577 }
9578 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009579
Guy Benyei11169dd2012-12-18 14:30:41 +00009580 return Builder.getWithLocInContext(Context);
9581}
9582
9583SourceRange
9584ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9585 unsigned &Idx) {
9586 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9587 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9588 return SourceRange(beg, end);
9589}
9590
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009591static FixedPointSemantics
9592ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9593 unsigned &Idx) {
9594 unsigned Width = Record[Idx++];
9595 unsigned Scale = Record[Idx++];
9596 uint64_t Tmp = Record[Idx++];
9597 bool IsSigned = Tmp & 0x1;
9598 bool IsSaturated = Tmp & 0x2;
9599 bool HasUnsignedPadding = Tmp & 0x4;
9600 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9601 HasUnsignedPadding);
9602}
9603
9604APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9605 unsigned Kind = Record[Idx++];
9606 switch (Kind) {
9607 case APValue::None:
9608 return APValue();
9609 case APValue::Indeterminate:
9610 return APValue::IndeterminateValue();
9611 case APValue::Int:
9612 return APValue(ReadAPSInt(Record, Idx));
9613 case APValue::Float: {
9614 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9615 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9616 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9617 }
9618 case APValue::FixedPoint: {
9619 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9620 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9621 }
9622 case APValue::ComplexInt: {
9623 llvm::APSInt First = ReadAPSInt(Record, Idx);
9624 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9625 }
9626 case APValue::ComplexFloat: {
9627 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9628 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9629 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9630 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9631 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9632 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9633 }
9634 case APValue::LValue:
9635 case APValue::Vector:
9636 case APValue::Array:
9637 case APValue::Struct:
9638 case APValue::Union:
9639 case APValue::MemberPointer:
9640 case APValue::AddrLabelDiff:
9641 // TODO : Handle all these APValue::ValueKind.
9642 return APValue();
9643 }
9644 llvm_unreachable("Invalid APValue::ValueKind");
9645}
9646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009647/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009648llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9649 unsigned BitWidth = Record[Idx++];
9650 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9651 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9652 Idx += NumWords;
9653 return Result;
9654}
9655
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009656/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009657llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9658 bool isUnsigned = Record[Idx++];
9659 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9660}
9661
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009662/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009663llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9664 const llvm::fltSemantics &Sem,
9665 unsigned &Idx) {
9666 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009667}
9668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009669// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009670std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9671 unsigned Len = Record[Idx++];
9672 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9673 Idx += Len;
9674 return Result;
9675}
9676
Richard Smith7ed1bc92014-12-05 22:42:13 +00009677std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9678 unsigned &Idx) {
9679 std::string Filename = ReadString(Record, Idx);
9680 ResolveImportedPath(F, Filename);
9681 return Filename;
9682}
9683
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009684std::string ASTReader::ReadPath(StringRef BaseDirectory,
9685 const RecordData &Record, unsigned &Idx) {
9686 std::string Filename = ReadString(Record, Idx);
9687 if (!BaseDirectory.empty())
9688 ResolveImportedPath(Filename, BaseDirectory);
9689 return Filename;
9690}
9691
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009692VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009693 unsigned &Idx) {
9694 unsigned Major = Record[Idx++];
9695 unsigned Minor = Record[Idx++];
9696 unsigned Subminor = Record[Idx++];
9697 if (Minor == 0)
9698 return VersionTuple(Major);
9699 if (Subminor == 0)
9700 return VersionTuple(Major, Minor - 1);
9701 return VersionTuple(Major, Minor - 1, Subminor - 1);
9702}
9703
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009704CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009705 const RecordData &Record,
9706 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009707 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009708 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009709}
9710
Richard Smith37a93df2017-02-18 00:32:02 +00009711DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009712 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009713}
9714
Richard Smith37a93df2017-02-18 00:32:02 +00009715DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009716 return Diags.Report(Loc, DiagID);
9717}
9718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009719/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009720/// preprocessor.
9721IdentifierTable &ASTReader::getIdentifierTable() {
9722 return PP.getIdentifierTable();
9723}
9724
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009725/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009726/// statement.
9727void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009728 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009729 "Already have a SwitchCase with this ID");
9730 (*CurrSwitchCaseStmts)[ID] = SC;
9731}
9732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009733/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009734SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009735 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009736 return (*CurrSwitchCaseStmts)[ID];
9737}
9738
9739void ASTReader::ClearSwitchCaseIDs() {
9740 CurrSwitchCaseStmts->clear();
9741}
9742
9743void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009744 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009745 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009746 for (SmallVectorImpl<std::pair<BitstreamCursor,
9747 serialization::ModuleFile *>>::iterator
9748 I = CommentsCursors.begin(),
9749 E = CommentsCursors.end();
9750 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009751 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009752 BitstreamCursor &Cursor = I->first;
9753 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009754 SavedStreamPosition SavedPosition(Cursor);
9755
9756 RecordData Record;
9757 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009758 Expected<llvm::BitstreamEntry> MaybeEntry =
9759 Cursor.advanceSkippingSubblocks(
9760 BitstreamCursor::AF_DontPopBlockAtEnd);
9761 if (!MaybeEntry) {
9762 Error(MaybeEntry.takeError());
9763 return;
9764 }
9765 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009766
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009767 switch (Entry.Kind) {
9768 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9769 case llvm::BitstreamEntry::Error:
9770 Error("malformed block record in AST file");
9771 return;
9772 case llvm::BitstreamEntry::EndBlock:
9773 goto NextCursor;
9774 case llvm::BitstreamEntry::Record:
9775 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009776 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009777 }
9778
9779 // Read a record.
9780 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009781 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9782 if (!MaybeComment) {
9783 Error(MaybeComment.takeError());
9784 return;
9785 }
9786 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009787 case COMMENTS_RAW_COMMENT: {
9788 unsigned Idx = 0;
9789 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009790 RawComment::CommentKind Kind =
9791 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009792 bool IsTrailingComment = Record[Idx++];
9793 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009794 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009795 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009796 break;
9797 }
9798 }
9799 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009800 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009801 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9802 FileToOffsetToComment;
9803 for (RawComment *C : Comments) {
9804 SourceLocation CommentLoc = C->getBeginLoc();
9805 if (CommentLoc.isValid()) {
9806 std::pair<FileID, unsigned> Loc =
9807 SourceMgr.getDecomposedLoc(CommentLoc);
9808 if (Loc.first.isValid())
9809 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9810 }
9811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009812 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009813}
9814
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009815void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9816 bool IncludeSystem, bool Complain,
9817 llvm::function_ref<void(const serialization::InputFile &IF,
9818 bool isSystem)> Visitor) {
9819 unsigned NumUserInputs = MF.NumUserInputFiles;
9820 unsigned NumInputs = MF.InputFilesLoaded.size();
9821 assert(NumUserInputs <= NumInputs);
9822 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9823 for (unsigned I = 0; I < N; ++I) {
9824 bool IsSystem = I >= NumUserInputs;
9825 InputFile IF = getInputFile(MF, I+1, Complain);
9826 Visitor(IF, IsSystem);
9827 }
9828}
9829
Richard Smithf3f84612017-06-29 02:19:42 +00009830void ASTReader::visitTopLevelModuleMaps(
9831 serialization::ModuleFile &MF,
9832 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9833 unsigned NumInputs = MF.InputFilesLoaded.size();
9834 for (unsigned I = 0; I < NumInputs; ++I) {
9835 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9836 if (IFI.TopLevelModuleMap)
9837 // FIXME: This unnecessarily re-reads the InputFileInfo.
9838 if (auto *FE = getInputFile(MF, I + 1).getFile())
9839 Visitor(FE);
9840 }
9841}
9842
Richard Smithcd45dbc2014-04-19 03:48:30 +00009843std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9844 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009845 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009846 return M->getFullModuleName();
9847
9848 // Otherwise, use the name of the top-level module the decl is within.
9849 if (ModuleFile *M = getOwningModuleFile(D))
9850 return M->ModuleName;
9851
9852 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009853 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009854}
9855
Guy Benyei11169dd2012-12-18 14:30:41 +00009856void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009857 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009858 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009859 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009860 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009861 // If any identifiers with corresponding top-level declarations have
9862 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009863 using TopLevelDeclsMap =
9864 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009865 TopLevelDeclsMap TopLevelDecls;
9866
Guy Benyei11169dd2012-12-18 14:30:41 +00009867 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009868 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009869 SmallVector<uint32_t, 4> DeclIDs =
9870 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009871 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009872
9873 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009874 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009875
Richard Smitha62d1982018-08-03 01:00:01 +00009876 // Load each function type that we deferred loading because it was a
9877 // deduced type that might refer to a local type declared within itself.
9878 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9879 auto *FD = PendingFunctionTypes[I].first;
9880 FD->setType(GetType(PendingFunctionTypes[I].second));
9881
9882 // If we gave a function a deduced return type, remember that we need to
9883 // propagate that along the redeclaration chain.
9884 auto *DT = FD->getReturnType()->getContainedDeducedType();
9885 if (DT && DT->isDeduced())
9886 PendingDeducedTypeUpdates.insert(
9887 {FD->getCanonicalDecl(), FD->getReturnType()});
9888 }
9889 PendingFunctionTypes.clear();
9890
Richard Smith851072e2014-05-19 20:59:20 +00009891 // For each decl chain that we wanted to complete while deserializing, mark
9892 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009893 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9894 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9895 }
Richard Smith851072e2014-05-19 20:59:20 +00009896 PendingIncompleteDeclChains.clear();
9897
Guy Benyei11169dd2012-12-18 14:30:41 +00009898 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009899 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009900 loadPendingDeclChain(PendingDeclChains[I].first,
9901 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009902 PendingDeclChains.clear();
9903
Douglas Gregor6168bd22013-02-18 15:53:43 +00009904 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009905 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9906 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9907 IdentifierInfo *II = TLD->first;
9908 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9909 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009910 }
9911 }
9912
Guy Benyei11169dd2012-12-18 14:30:41 +00009913 // Load any pending macro definitions.
9914 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009915 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9916 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9917 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9918 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009919 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009920 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009921 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009922 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009923 resolvePendingMacro(II, Info);
9924 }
9925 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009926 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009927 ++IDIdx) {
9928 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009929 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009930 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009931 }
9932 }
9933 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009934
9935 // Wire up the DeclContexts for Decls that we delayed setting until
9936 // recursive loading is completed.
9937 while (!PendingDeclContextInfos.empty()) {
9938 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9939 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009940 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9941 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009942 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9943 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009944
Richard Smithd1c46742014-04-30 02:24:17 +00009945 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009946 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009947 auto Update = PendingUpdateRecords.pop_back_val();
9948 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009949 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009950 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009951 }
Richard Smith8a639892015-01-24 01:07:20 +00009952
9953 // At this point, all update records for loaded decls are in place, so any
9954 // fake class definitions should have become real.
9955 assert(PendingFakeDefinitionData.empty() &&
9956 "faked up a class definition but never saw the real one");
9957
Guy Benyei11169dd2012-12-18 14:30:41 +00009958 // If we deserialized any C++ or Objective-C class definitions, any
9959 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009960 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009961 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009962 for (Decl *D : PendingDefinitions) {
9963 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9964 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009965 // Make sure that the TagType points at the definition.
9966 const_cast<TagType*>(TagT)->decl = TD;
9967 }
Richard Smith8ce51082015-03-11 01:44:51 +00009968
Vedant Kumar48b4f762018-04-14 01:40:48 +00009969 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009970 for (auto *R = getMostRecentExistingDecl(RD); R;
9971 R = R->getPreviousDecl()) {
9972 assert((R == D) ==
9973 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009974 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009975 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009977 }
9978
9979 continue;
9980 }
Richard Smith8ce51082015-03-11 01:44:51 +00009981
Vedant Kumar48b4f762018-04-14 01:40:48 +00009982 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009983 // Make sure that the ObjCInterfaceType points at the definition.
9984 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9985 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009986
9987 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9988 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9989
Guy Benyei11169dd2012-12-18 14:30:41 +00009990 continue;
9991 }
Richard Smith8ce51082015-03-11 01:44:51 +00009992
Vedant Kumar48b4f762018-04-14 01:40:48 +00009993 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009994 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9995 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9996
Guy Benyei11169dd2012-12-18 14:30:41 +00009997 continue;
9998 }
Richard Smith8ce51082015-03-11 01:44:51 +00009999
Vedant Kumar48b4f762018-04-14 01:40:48 +000010000 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +000010001 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10002 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +000010003 }
10004 PendingDefinitions.clear();
10005
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010006 // Load the bodies of any functions or methods we've encountered. We do
10007 // this now (delayed) so that we can be sure that the declaration chains
10008 // have been fully wired up (hasBody relies on this).
10009 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +000010010 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10011 PBEnd = PendingBodies.end();
10012 PB != PBEnd; ++PB) {
10013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +000010014 // For a function defined inline within a class template, force the
10015 // canonical definition to be the one inside the canonical definition of
10016 // the template. This ensures that we instantiate from a correct view
10017 // of the template.
10018 //
10019 // Sadly we can't do this more generally: we can't be sure that all
10020 // copies of an arbitrary class definition will have the same members
10021 // defined (eg, some member functions may not be instantiated, and some
10022 // special members may or may not have been implicitly defined).
10023 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
10024 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
10025 continue;
10026
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010027 // FIXME: Check for =delete/=default?
10028 // FIXME: Complain about ODR violations here?
10029 const FunctionDecl *Defn = nullptr;
10030 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010031 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +000010032 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010033 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +000010034 mergeDefinitionVisibility(NonConstDefn, FD);
10035
10036 if (!FD->isLateTemplateParsed() &&
10037 !NonConstDefn->isLateTemplateParsed() &&
10038 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010039 if (!isa<CXXMethodDecl>(FD)) {
10040 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10041 } else if (FD->getLexicalParent()->isFileContext() &&
10042 NonConstDefn->getLexicalParent()->isFileContext()) {
10043 // Only diagnose out-of-line method definitions. If they are
10044 // in class definitions, then an error will be generated when
10045 // processing the class bodies.
10046 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10047 }
Richard Trieue6caa262017-12-23 00:41:01 +000010048 }
10049 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010050 continue;
10051 }
10052
Vedant Kumar48b4f762018-04-14 01:40:48 +000010053 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010054 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +000010055 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010056 }
10057 PendingBodies.clear();
10058
Richard Smith42413142015-05-15 20:05:43 +000010059 // Do some cleanup.
10060 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10061 getContext().deduplicateMergedDefinitonsFor(ND);
10062 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010063}
10064
10065void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +000010066 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +000010067 PendingFunctionOdrMergeFailures.empty() &&
10068 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +000010069 return;
10070
Richard Smitha0ce9c42014-07-29 23:23:27 +000010071 // Trigger the import of the full definition of each class that had any
10072 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +000010073 // These updates may in turn find and diagnose some ODR failures, so take
10074 // ownership of the set first.
10075 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10076 PendingOdrMergeFailures.clear();
10077 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010078 Merge.first->buildLookup();
10079 Merge.first->decls_begin();
10080 Merge.first->bases_begin();
10081 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +000010082 for (auto &RecordPair : Merge.second) {
10083 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010084 RD->decls_begin();
10085 RD->bases_begin();
10086 RD->vbases_begin();
10087 }
10088 }
10089
Richard Trieue6caa262017-12-23 00:41:01 +000010090 // Trigger the import of functions.
10091 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10092 PendingFunctionOdrMergeFailures.clear();
10093 for (auto &Merge : FunctionOdrMergeFailures) {
10094 Merge.first->buildLookup();
10095 Merge.first->decls_begin();
10096 Merge.first->getBody();
10097 for (auto &FD : Merge.second) {
10098 FD->buildLookup();
10099 FD->decls_begin();
10100 FD->getBody();
10101 }
10102 }
10103
Richard Trieuab4d7302018-07-25 22:52:05 +000010104 // Trigger the import of enums.
10105 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10106 PendingEnumOdrMergeFailures.clear();
10107 for (auto &Merge : EnumOdrMergeFailures) {
10108 Merge.first->decls_begin();
10109 for (auto &Enum : Merge.second) {
10110 Enum->decls_begin();
10111 }
10112 }
10113
Richard Smitha0ce9c42014-07-29 23:23:27 +000010114 // For each declaration from a merged context, check that the canonical
10115 // definition of that context also contains a declaration of the same
10116 // entity.
10117 //
10118 // Caution: this loop does things that might invalidate iterators into
10119 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10120 while (!PendingOdrMergeChecks.empty()) {
10121 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10122
10123 // FIXME: Skip over implicit declarations for now. This matters for things
10124 // like implicitly-declared special member functions. This isn't entirely
10125 // correct; we can end up with multiple unmerged declarations of the same
10126 // implicit entity.
10127 if (D->isImplicit())
10128 continue;
10129
10130 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010131
10132 bool Found = false;
10133 const Decl *DCanon = D->getCanonicalDecl();
10134
Richard Smith01bdb7a2014-08-28 05:44:07 +000010135 for (auto RI : D->redecls()) {
10136 if (RI->getLexicalDeclContext() == CanonDef) {
10137 Found = true;
10138 break;
10139 }
10140 }
10141 if (Found)
10142 continue;
10143
Richard Smith0f4e2c42015-08-06 04:23:48 +000010144 // Quick check failed, time to do the slow thing. Note, we can't just
10145 // look up the name of D in CanonDef here, because the member that is
10146 // in CanonDef might not be found by name lookup (it might have been
10147 // replaced by a more recent declaration in the lookup table), and we
10148 // can't necessarily find it in the redeclaration chain because it might
10149 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010150 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +000010151 for (auto *CanonMember : CanonDef->decls()) {
10152 if (CanonMember->getCanonicalDecl() == DCanon) {
10153 // This can happen if the declaration is merely mergeable and not
10154 // actually redeclarable (we looked for redeclarations earlier).
10155 //
10156 // FIXME: We should be able to detect this more efficiently, without
10157 // pulling in all of the members of CanonDef.
10158 Found = true;
10159 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010160 }
Richard Smith0f4e2c42015-08-06 04:23:48 +000010161 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10162 if (ND->getDeclName() == D->getDeclName())
10163 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010164 }
10165
10166 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +000010167 // The AST doesn't like TagDecls becoming invalid after they've been
10168 // completed. We only really need to mark FieldDecls as invalid here.
10169 if (!isa<TagDecl>(D))
10170 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010171
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010172 // Ensure we don't accidentally recursively enter deserialization while
10173 // we're producing our diagnostic.
10174 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010175
10176 std::string CanonDefModule =
10177 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
10178 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10179 << D << getOwningModuleNameForDiagnostic(D)
10180 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10181
10182 if (Candidates.empty())
10183 Diag(cast<Decl>(CanonDef)->getLocation(),
10184 diag::note_module_odr_violation_no_possible_decls) << D;
10185 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010186 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10187 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +000010188 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +000010189 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +000010190 }
10191
10192 DiagnosedOdrMergeFailures.insert(CanonDef);
10193 }
10194 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010195
Richard Trieuab4d7302018-07-25 22:52:05 +000010196 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
10197 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010198 return;
10199
10200 // Ensure we don't accidentally recursively enter deserialization while
10201 // we're producing our diagnostics.
10202 Deserializing RecursionGuard(this);
10203
Richard Trieue6caa262017-12-23 00:41:01 +000010204 // Common code for hashing helpers.
10205 ODRHash Hash;
10206 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
10207 Hash.clear();
10208 Hash.AddQualType(Ty);
10209 return Hash.CalculateHash();
10210 };
10211
10212 auto ComputeODRHash = [&Hash](const Stmt *S) {
10213 assert(S);
10214 Hash.clear();
10215 Hash.AddStmt(S);
10216 return Hash.CalculateHash();
10217 };
10218
10219 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
10220 assert(D);
10221 Hash.clear();
10222 Hash.AddSubDecl(D);
10223 return Hash.CalculateHash();
10224 };
10225
Richard Trieu7282d322018-04-25 00:31:15 +000010226 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
10227 Hash.clear();
10228 Hash.AddTemplateArgument(TA);
10229 return Hash.CalculateHash();
10230 };
10231
Richard Trieu9359e8f2018-05-30 01:12:26 +000010232 auto ComputeTemplateParameterListODRHash =
10233 [&Hash](const TemplateParameterList *TPL) {
10234 assert(TPL);
10235 Hash.clear();
10236 Hash.AddTemplateParameterList(TPL);
10237 return Hash.CalculateHash();
10238 };
10239
Richard Smithcd45dbc2014-04-19 03:48:30 +000010240 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010241 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010242 // If we've already pointed out a specific problem with this class, don't
10243 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010244 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010245 continue;
10246
10247 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010248 CXXRecordDecl *FirstRecord = Merge.first;
10249 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010250 for (auto &RecordPair : Merge.second) {
10251 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010252 // Multiple different declarations got merged together; tell the user
10253 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010254 if (FirstRecord == SecondRecord)
10255 continue;
10256
10257 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010258
10259 auto *FirstDD = FirstRecord->DefinitionData;
10260 auto *SecondDD = RecordPair.second;
10261
10262 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10263
10264 // Diagnostics from DefinitionData are emitted here.
10265 if (FirstDD != SecondDD) {
10266 enum ODRDefinitionDataDifference {
10267 NumBases,
10268 NumVBases,
10269 BaseType,
10270 BaseVirtual,
10271 BaseAccess,
10272 };
10273 auto ODRDiagError = [FirstRecord, &FirstModule,
10274 this](SourceLocation Loc, SourceRange Range,
10275 ODRDefinitionDataDifference DiffType) {
10276 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10277 << FirstRecord << FirstModule.empty() << FirstModule << Range
10278 << DiffType;
10279 };
10280 auto ODRDiagNote = [&SecondModule,
10281 this](SourceLocation Loc, SourceRange Range,
10282 ODRDefinitionDataDifference DiffType) {
10283 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10284 << SecondModule << Range << DiffType;
10285 };
10286
Richard Trieue13eabe2017-09-30 02:19:17 +000010287 unsigned FirstNumBases = FirstDD->NumBases;
10288 unsigned FirstNumVBases = FirstDD->NumVBases;
10289 unsigned SecondNumBases = SecondDD->NumBases;
10290 unsigned SecondNumVBases = SecondDD->NumVBases;
10291
10292 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10293 unsigned NumBases = DD->NumBases;
10294 if (NumBases == 0) return SourceRange();
10295 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010296 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010297 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010298 };
10299
10300 if (FirstNumBases != SecondNumBases) {
10301 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10302 NumBases)
10303 << FirstNumBases;
10304 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10305 NumBases)
10306 << SecondNumBases;
10307 Diagnosed = true;
10308 break;
10309 }
10310
10311 if (FirstNumVBases != SecondNumVBases) {
10312 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10313 NumVBases)
10314 << FirstNumVBases;
10315 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10316 NumVBases)
10317 << SecondNumVBases;
10318 Diagnosed = true;
10319 break;
10320 }
10321
10322 auto FirstBases = FirstDD->bases();
10323 auto SecondBases = SecondDD->bases();
10324 unsigned i = 0;
10325 for (i = 0; i < FirstNumBases; ++i) {
10326 auto FirstBase = FirstBases[i];
10327 auto SecondBase = SecondBases[i];
10328 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10329 ComputeQualTypeODRHash(SecondBase.getType())) {
10330 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10331 BaseType)
10332 << (i + 1) << FirstBase.getType();
10333 ODRDiagNote(SecondRecord->getLocation(),
10334 SecondBase.getSourceRange(), BaseType)
10335 << (i + 1) << SecondBase.getType();
10336 break;
10337 }
10338
10339 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10340 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10341 BaseVirtual)
10342 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10343 ODRDiagNote(SecondRecord->getLocation(),
10344 SecondBase.getSourceRange(), BaseVirtual)
10345 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10346 break;
10347 }
10348
10349 if (FirstBase.getAccessSpecifierAsWritten() !=
10350 SecondBase.getAccessSpecifierAsWritten()) {
10351 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10352 BaseAccess)
10353 << (i + 1) << FirstBase.getType()
10354 << (int)FirstBase.getAccessSpecifierAsWritten();
10355 ODRDiagNote(SecondRecord->getLocation(),
10356 SecondBase.getSourceRange(), BaseAccess)
10357 << (i + 1) << SecondBase.getType()
10358 << (int)SecondBase.getAccessSpecifierAsWritten();
10359 break;
10360 }
10361 }
10362
10363 if (i != FirstNumBases) {
10364 Diagnosed = true;
10365 break;
10366 }
10367 }
10368
Richard Trieue7f7ed22017-02-22 01:11:25 +000010369 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +000010370
10371 const ClassTemplateDecl *FirstTemplate =
10372 FirstRecord->getDescribedClassTemplate();
10373 const ClassTemplateDecl *SecondTemplate =
10374 SecondRecord->getDescribedClassTemplate();
10375
10376 assert(!FirstTemplate == !SecondTemplate &&
10377 "Both pointers should be null or non-null");
10378
10379 enum ODRTemplateDifference {
10380 ParamEmptyName,
10381 ParamName,
10382 ParamSingleDefaultArgument,
10383 ParamDifferentDefaultArgument,
10384 };
10385
10386 if (FirstTemplate && SecondTemplate) {
10387 DeclHashes FirstTemplateHashes;
10388 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010389
10390 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010391 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10392 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010393 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010394 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010395 }
10396 };
10397
10398 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10399 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10400
10401 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10402 "Number of template parameters should be equal.");
10403
10404 auto FirstIt = FirstTemplateHashes.begin();
10405 auto FirstEnd = FirstTemplateHashes.end();
10406 auto SecondIt = SecondTemplateHashes.begin();
10407 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10408 if (FirstIt->second == SecondIt->second)
10409 continue;
10410
10411 auto ODRDiagError = [FirstRecord, &FirstModule,
10412 this](SourceLocation Loc, SourceRange Range,
10413 ODRTemplateDifference DiffType) {
10414 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10415 << FirstRecord << FirstModule.empty() << FirstModule << Range
10416 << DiffType;
10417 };
10418 auto ODRDiagNote = [&SecondModule,
10419 this](SourceLocation Loc, SourceRange Range,
10420 ODRTemplateDifference DiffType) {
10421 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10422 << SecondModule << Range << DiffType;
10423 };
10424
Vedant Kumar48b4f762018-04-14 01:40:48 +000010425 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10426 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010427
10428 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10429 "Parameter Decl's should be the same kind.");
10430
10431 DeclarationName FirstName = FirstDecl->getDeclName();
10432 DeclarationName SecondName = SecondDecl->getDeclName();
10433
10434 if (FirstName != SecondName) {
10435 const bool FirstNameEmpty =
10436 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10437 const bool SecondNameEmpty =
10438 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10439 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10440 "Both template parameters cannot be unnamed.");
10441 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10442 FirstNameEmpty ? ParamEmptyName : ParamName)
10443 << FirstName;
10444 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10445 SecondNameEmpty ? ParamEmptyName : ParamName)
10446 << SecondName;
10447 break;
10448 }
10449
10450 switch (FirstDecl->getKind()) {
10451 default:
10452 llvm_unreachable("Invalid template parameter type.");
10453 case Decl::TemplateTypeParm: {
10454 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10455 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10456 const bool HasFirstDefaultArgument =
10457 FirstParam->hasDefaultArgument() &&
10458 !FirstParam->defaultArgumentWasInherited();
10459 const bool HasSecondDefaultArgument =
10460 SecondParam->hasDefaultArgument() &&
10461 !SecondParam->defaultArgumentWasInherited();
10462
10463 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10464 ODRDiagError(FirstDecl->getLocation(),
10465 FirstDecl->getSourceRange(),
10466 ParamSingleDefaultArgument)
10467 << HasFirstDefaultArgument;
10468 ODRDiagNote(SecondDecl->getLocation(),
10469 SecondDecl->getSourceRange(),
10470 ParamSingleDefaultArgument)
10471 << HasSecondDefaultArgument;
10472 break;
10473 }
10474
10475 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10476 "Expecting default arguments.");
10477
10478 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10479 ParamDifferentDefaultArgument);
10480 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10481 ParamDifferentDefaultArgument);
10482
10483 break;
10484 }
10485 case Decl::NonTypeTemplateParm: {
10486 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10487 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10488 const bool HasFirstDefaultArgument =
10489 FirstParam->hasDefaultArgument() &&
10490 !FirstParam->defaultArgumentWasInherited();
10491 const bool HasSecondDefaultArgument =
10492 SecondParam->hasDefaultArgument() &&
10493 !SecondParam->defaultArgumentWasInherited();
10494
10495 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10496 ODRDiagError(FirstDecl->getLocation(),
10497 FirstDecl->getSourceRange(),
10498 ParamSingleDefaultArgument)
10499 << HasFirstDefaultArgument;
10500 ODRDiagNote(SecondDecl->getLocation(),
10501 SecondDecl->getSourceRange(),
10502 ParamSingleDefaultArgument)
10503 << HasSecondDefaultArgument;
10504 break;
10505 }
10506
10507 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10508 "Expecting default arguments.");
10509
10510 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10511 ParamDifferentDefaultArgument);
10512 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10513 ParamDifferentDefaultArgument);
10514
10515 break;
10516 }
10517 case Decl::TemplateTemplateParm: {
10518 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10519 const auto *SecondParam =
10520 cast<TemplateTemplateParmDecl>(SecondDecl);
10521 const bool HasFirstDefaultArgument =
10522 FirstParam->hasDefaultArgument() &&
10523 !FirstParam->defaultArgumentWasInherited();
10524 const bool HasSecondDefaultArgument =
10525 SecondParam->hasDefaultArgument() &&
10526 !SecondParam->defaultArgumentWasInherited();
10527
10528 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10529 ODRDiagError(FirstDecl->getLocation(),
10530 FirstDecl->getSourceRange(),
10531 ParamSingleDefaultArgument)
10532 << HasFirstDefaultArgument;
10533 ODRDiagNote(SecondDecl->getLocation(),
10534 SecondDecl->getSourceRange(),
10535 ParamSingleDefaultArgument)
10536 << HasSecondDefaultArgument;
10537 break;
10538 }
10539
10540 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10541 "Expecting default arguments.");
10542
10543 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10544 ParamDifferentDefaultArgument);
10545 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10546 ParamDifferentDefaultArgument);
10547
10548 break;
10549 }
10550 }
10551
10552 break;
10553 }
10554
10555 if (FirstIt != FirstEnd) {
10556 Diagnosed = true;
10557 break;
10558 }
10559 }
10560
Richard Trieue7f7ed22017-02-22 01:11:25 +000010561 DeclHashes FirstHashes;
10562 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010563
Richard Trieue6caa262017-12-23 00:41:01 +000010564 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10565 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010566 for (auto *D : Record->decls()) {
10567 // Due to decl merging, the first CXXRecordDecl is the parent of
10568 // Decls in both records.
10569 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10570 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010571 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010572 }
10573 };
10574 PopulateHashes(FirstHashes, FirstRecord);
10575 PopulateHashes(SecondHashes, SecondRecord);
10576
10577 // Used with err_module_odr_violation_mismatch_decl and
10578 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010579 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010580 enum {
10581 EndOfClass,
10582 PublicSpecifer,
10583 PrivateSpecifer,
10584 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010585 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010586 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010587 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010588 TypeAlias,
10589 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010590 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010591 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010592 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010593 Other
10594 } FirstDiffType = Other,
10595 SecondDiffType = Other;
10596
10597 auto DifferenceSelector = [](Decl *D) {
10598 assert(D && "valid Decl required");
10599 switch (D->getKind()) {
10600 default:
10601 return Other;
10602 case Decl::AccessSpec:
10603 switch (D->getAccess()) {
10604 case AS_public:
10605 return PublicSpecifer;
10606 case AS_private:
10607 return PrivateSpecifer;
10608 case AS_protected:
10609 return ProtectedSpecifer;
10610 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010611 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010612 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010613 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010614 case Decl::StaticAssert:
10615 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010616 case Decl::Field:
10617 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010618 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010619 case Decl::CXXConstructor:
10620 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010621 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010622 case Decl::TypeAlias:
10623 return TypeAlias;
10624 case Decl::Typedef:
10625 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010626 case Decl::Var:
10627 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010628 case Decl::Friend:
10629 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010630 case Decl::FunctionTemplate:
10631 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010632 }
10633 };
10634
10635 Decl *FirstDecl = nullptr;
10636 Decl *SecondDecl = nullptr;
10637 auto FirstIt = FirstHashes.begin();
10638 auto SecondIt = SecondHashes.begin();
10639
10640 // If there is a diagnoseable difference, FirstDiffType and
10641 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10642 // filled in if not EndOfClass.
10643 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010644 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10645 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010646 ++FirstIt;
10647 ++SecondIt;
10648 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010649 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010650
Richard Trieue7f7ed22017-02-22 01:11:25 +000010651 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10652 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10653
10654 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10655 SecondDiffType =
10656 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10657
10658 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010659 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010660
10661 if (FirstDiffType == Other || SecondDiffType == Other) {
10662 // Reaching this point means an unexpected Decl was encountered
10663 // or no difference was detected. This causes a generic error
10664 // message to be emitted.
10665 Diag(FirstRecord->getLocation(),
10666 diag::err_module_odr_violation_different_definitions)
10667 << FirstRecord << FirstModule.empty() << FirstModule;
10668
Richard Trieuca48d362017-06-21 01:43:13 +000010669 if (FirstDecl) {
10670 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10671 << FirstRecord << FirstDecl->getSourceRange();
10672 }
10673
Richard Trieue7f7ed22017-02-22 01:11:25 +000010674 Diag(SecondRecord->getLocation(),
10675 diag::note_module_odr_violation_different_definitions)
10676 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010677
10678 if (SecondDecl) {
10679 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10680 << SecondDecl->getSourceRange();
10681 }
10682
Richard Trieue7f7ed22017-02-22 01:11:25 +000010683 Diagnosed = true;
10684 break;
10685 }
10686
10687 if (FirstDiffType != SecondDiffType) {
10688 SourceLocation FirstLoc;
10689 SourceRange FirstRange;
10690 if (FirstDiffType == EndOfClass) {
10691 FirstLoc = FirstRecord->getBraceRange().getEnd();
10692 } else {
10693 FirstLoc = FirstIt->first->getLocation();
10694 FirstRange = FirstIt->first->getSourceRange();
10695 }
10696 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10697 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10698 << FirstDiffType;
10699
10700 SourceLocation SecondLoc;
10701 SourceRange SecondRange;
10702 if (SecondDiffType == EndOfClass) {
10703 SecondLoc = SecondRecord->getBraceRange().getEnd();
10704 } else {
10705 SecondLoc = SecondDecl->getLocation();
10706 SecondRange = SecondDecl->getSourceRange();
10707 }
10708 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10709 << SecondModule << SecondRange << SecondDiffType;
10710 Diagnosed = true;
10711 break;
10712 }
10713
Richard Trieu639d7b62017-02-22 22:22:42 +000010714 assert(FirstDiffType == SecondDiffType);
10715
10716 // Used with err_module_odr_violation_mismatch_decl_diff and
10717 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010718 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010719 StaticAssertCondition,
10720 StaticAssertMessage,
10721 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010722 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010723 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010724 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010725 FieldDifferentWidthBitField,
10726 FieldSingleMutable,
10727 FieldSingleInitializer,
10728 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010729 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010730 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010731 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010732 MethodVirtual,
10733 MethodStatic,
10734 MethodVolatile,
10735 MethodConst,
10736 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010737 MethodNumberParameters,
10738 MethodParameterType,
10739 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010740 MethodParameterSingleDefaultArgument,
10741 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010742 MethodNoTemplateArguments,
10743 MethodDifferentNumberTemplateArguments,
10744 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010745 MethodSingleBody,
10746 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010747 TypedefName,
10748 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010749 VarName,
10750 VarType,
10751 VarSingleInitializer,
10752 VarDifferentInitializer,
10753 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010754 FriendTypeFunction,
10755 FriendType,
10756 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010757 FunctionTemplateDifferentNumberParameters,
10758 FunctionTemplateParameterDifferentKind,
10759 FunctionTemplateParameterName,
10760 FunctionTemplateParameterSingleDefaultArgument,
10761 FunctionTemplateParameterDifferentDefaultArgument,
10762 FunctionTemplateParameterDifferentType,
10763 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010764 };
10765
10766 // These lambdas have the common portions of the ODR diagnostics. This
10767 // has the same return as Diag(), so addition parameters can be passed
10768 // in with operator<<
10769 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10770 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10771 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10772 << FirstRecord << FirstModule.empty() << FirstModule << Range
10773 << DiffType;
10774 };
10775 auto ODRDiagNote = [&SecondModule, this](
10776 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10777 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10778 << SecondModule << Range << DiffType;
10779 };
10780
Richard Trieu639d7b62017-02-22 22:22:42 +000010781 switch (FirstDiffType) {
10782 case Other:
10783 case EndOfClass:
10784 case PublicSpecifer:
10785 case PrivateSpecifer:
10786 case ProtectedSpecifer:
10787 llvm_unreachable("Invalid diff type");
10788
10789 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010790 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10791 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010792
10793 Expr *FirstExpr = FirstSA->getAssertExpr();
10794 Expr *SecondExpr = SecondSA->getAssertExpr();
10795 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10796 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10797 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010798 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010799 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010800 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10801 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010802 Diagnosed = true;
10803 break;
10804 }
10805
10806 StringLiteral *FirstStr = FirstSA->getMessage();
10807 StringLiteral *SecondStr = SecondSA->getMessage();
10808 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10809 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10810 SourceLocation FirstLoc, SecondLoc;
10811 SourceRange FirstRange, SecondRange;
10812 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010813 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010814 FirstRange = FirstStr->getSourceRange();
10815 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010816 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010817 FirstRange = FirstSA->getSourceRange();
10818 }
10819 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010820 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010821 SecondRange = SecondStr->getSourceRange();
10822 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010823 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010824 SecondRange = SecondSA->getSourceRange();
10825 }
10826 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10827 << (FirstStr == nullptr);
10828 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10829 << (SecondStr == nullptr);
10830 Diagnosed = true;
10831 break;
10832 }
10833
10834 if (FirstStr && SecondStr &&
10835 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010836 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010837 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010838 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010839 StaticAssertMessage);
10840 Diagnosed = true;
10841 break;
10842 }
10843 break;
10844 }
Richard Trieud0786092017-02-23 00:23:01 +000010845 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010846 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10847 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010848 IdentifierInfo *FirstII = FirstField->getIdentifier();
10849 IdentifierInfo *SecondII = SecondField->getIdentifier();
10850 if (FirstII->getName() != SecondII->getName()) {
10851 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10852 FieldName)
10853 << FirstII;
10854 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10855 FieldName)
10856 << SecondII;
10857
10858 Diagnosed = true;
10859 break;
10860 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010861
Richard Smithdbafb6c2017-06-29 23:23:46 +000010862 assert(getContext().hasSameType(FirstField->getType(),
10863 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010864
10865 QualType FirstType = FirstField->getType();
10866 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010867 if (ComputeQualTypeODRHash(FirstType) !=
10868 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010869 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10870 FieldTypeName)
10871 << FirstII << FirstType;
10872 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10873 FieldTypeName)
10874 << SecondII << SecondType;
10875
10876 Diagnosed = true;
10877 break;
10878 }
10879
Richard Trieu93772fc2017-02-24 20:59:28 +000010880 const bool IsFirstBitField = FirstField->isBitField();
10881 const bool IsSecondBitField = SecondField->isBitField();
10882 if (IsFirstBitField != IsSecondBitField) {
10883 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10884 FieldSingleBitField)
10885 << FirstII << IsFirstBitField;
10886 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10887 FieldSingleBitField)
10888 << SecondII << IsSecondBitField;
10889 Diagnosed = true;
10890 break;
10891 }
10892
10893 if (IsFirstBitField && IsSecondBitField) {
10894 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10895 FieldDifferentWidthBitField)
10896 << FirstII << FirstField->getBitWidth()->getSourceRange();
10897 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10898 FieldDifferentWidthBitField)
10899 << SecondII << SecondField->getBitWidth()->getSourceRange();
10900 Diagnosed = true;
10901 break;
10902 }
10903
Richard Trieu8d543e22017-02-24 23:35:37 +000010904 const bool IsFirstMutable = FirstField->isMutable();
10905 const bool IsSecondMutable = SecondField->isMutable();
10906 if (IsFirstMutable != IsSecondMutable) {
10907 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10908 FieldSingleMutable)
10909 << FirstII << IsFirstMutable;
10910 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10911 FieldSingleMutable)
10912 << SecondII << IsSecondMutable;
10913 Diagnosed = true;
10914 break;
10915 }
10916
10917 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10918 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10919 if ((!FirstInitializer && SecondInitializer) ||
10920 (FirstInitializer && !SecondInitializer)) {
10921 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10922 FieldSingleInitializer)
10923 << FirstII << (FirstInitializer != nullptr);
10924 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10925 FieldSingleInitializer)
10926 << SecondII << (SecondInitializer != nullptr);
10927 Diagnosed = true;
10928 break;
10929 }
10930
10931 if (FirstInitializer && SecondInitializer) {
10932 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10933 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10934 if (FirstInitHash != SecondInitHash) {
10935 ODRDiagError(FirstField->getLocation(),
10936 FirstField->getSourceRange(),
10937 FieldDifferentInitializers)
10938 << FirstII << FirstInitializer->getSourceRange();
10939 ODRDiagNote(SecondField->getLocation(),
10940 SecondField->getSourceRange(),
10941 FieldDifferentInitializers)
10942 << SecondII << SecondInitializer->getSourceRange();
10943 Diagnosed = true;
10944 break;
10945 }
10946 }
10947
Richard Trieud0786092017-02-23 00:23:01 +000010948 break;
10949 }
Richard Trieu48143742017-02-28 21:24:38 +000010950 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010951 enum {
10952 DiagMethod,
10953 DiagConstructor,
10954 DiagDestructor,
10955 } FirstMethodType,
10956 SecondMethodType;
10957 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10958 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10959 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10960 return DiagMethod;
10961 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010962 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10963 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010964 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10965 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010966 auto FirstName = FirstMethod->getDeclName();
10967 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010968 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010969 ODRDiagError(FirstMethod->getLocation(),
10970 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010971 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010972 ODRDiagNote(SecondMethod->getLocation(),
10973 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010974 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010975
10976 Diagnosed = true;
10977 break;
10978 }
10979
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010980 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10981 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010982 if (FirstDeleted != SecondDeleted) {
10983 ODRDiagError(FirstMethod->getLocation(),
10984 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010985 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010986
10987 ODRDiagNote(SecondMethod->getLocation(),
10988 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010989 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010990 Diagnosed = true;
10991 break;
10992 }
10993
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010994 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10995 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10996 if (FirstDefaulted != SecondDefaulted) {
10997 ODRDiagError(FirstMethod->getLocation(),
10998 FirstMethod->getSourceRange(), MethodDefaulted)
10999 << FirstMethodType << FirstName << FirstDefaulted;
11000
11001 ODRDiagNote(SecondMethod->getLocation(),
11002 SecondMethod->getSourceRange(), MethodDefaulted)
11003 << SecondMethodType << SecondName << SecondDefaulted;
11004 Diagnosed = true;
11005 break;
11006 }
11007
Richard Trieu583e2c12017-03-04 00:08:58 +000011008 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
11009 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
11010 const bool FirstPure = FirstMethod->isPure();
11011 const bool SecondPure = SecondMethod->isPure();
11012 if ((FirstVirtual || SecondVirtual) &&
11013 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
11014 ODRDiagError(FirstMethod->getLocation(),
11015 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000011016 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000011017 ODRDiagNote(SecondMethod->getLocation(),
11018 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000011019 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000011020 Diagnosed = true;
11021 break;
11022 }
11023
11024 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
11025 // FirstDecl is the canonical Decl of SecondDecl, so the storage
11026 // class needs to be checked instead.
11027 const auto FirstStorage = FirstMethod->getStorageClass();
11028 const auto SecondStorage = SecondMethod->getStorageClass();
11029 const bool FirstStatic = FirstStorage == SC_Static;
11030 const bool SecondStatic = SecondStorage == SC_Static;
11031 if (FirstStatic != SecondStatic) {
11032 ODRDiagError(FirstMethod->getLocation(),
11033 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000011034 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000011035 ODRDiagNote(SecondMethod->getLocation(),
11036 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000011037 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000011038 Diagnosed = true;
11039 break;
11040 }
11041
11042 const bool FirstVolatile = FirstMethod->isVolatile();
11043 const bool SecondVolatile = SecondMethod->isVolatile();
11044 if (FirstVolatile != SecondVolatile) {
11045 ODRDiagError(FirstMethod->getLocation(),
11046 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000011047 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000011048 ODRDiagNote(SecondMethod->getLocation(),
11049 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000011050 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000011051 Diagnosed = true;
11052 break;
11053 }
11054
11055 const bool FirstConst = FirstMethod->isConst();
11056 const bool SecondConst = SecondMethod->isConst();
11057 if (FirstConst != SecondConst) {
11058 ODRDiagError(FirstMethod->getLocation(),
11059 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000011060 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000011061 ODRDiagNote(SecondMethod->getLocation(),
11062 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000011063 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000011064 Diagnosed = true;
11065 break;
11066 }
11067
11068 const bool FirstInline = FirstMethod->isInlineSpecified();
11069 const bool SecondInline = SecondMethod->isInlineSpecified();
11070 if (FirstInline != SecondInline) {
11071 ODRDiagError(FirstMethod->getLocation(),
11072 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011073 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011074 ODRDiagNote(SecondMethod->getLocation(),
11075 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011076 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011077 Diagnosed = true;
11078 break;
11079 }
11080
Richard Trieu02552272017-05-02 23:58:52 +000011081 const unsigned FirstNumParameters = FirstMethod->param_size();
11082 const unsigned SecondNumParameters = SecondMethod->param_size();
11083 if (FirstNumParameters != SecondNumParameters) {
11084 ODRDiagError(FirstMethod->getLocation(),
11085 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011086 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011087 ODRDiagNote(SecondMethod->getLocation(),
11088 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011089 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011090 Diagnosed = true;
11091 break;
11092 }
11093
11094 // Need this status boolean to know when break out of the switch.
11095 bool ParameterMismatch = false;
11096 for (unsigned I = 0; I < FirstNumParameters; ++I) {
11097 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
11098 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
11099
11100 QualType FirstParamType = FirstParam->getType();
11101 QualType SecondParamType = SecondParam->getType();
11102 if (FirstParamType != SecondParamType &&
11103 ComputeQualTypeODRHash(FirstParamType) !=
11104 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011105 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011106 FirstParamType->getAs<DecayedType>()) {
11107 ODRDiagError(FirstMethod->getLocation(),
11108 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011109 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11110 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000011111 } else {
11112 ODRDiagError(FirstMethod->getLocation(),
11113 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011114 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11115 << false;
Richard Trieu02552272017-05-02 23:58:52 +000011116 }
11117
Vedant Kumar48b4f762018-04-14 01:40:48 +000011118 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011119 SecondParamType->getAs<DecayedType>()) {
11120 ODRDiagNote(SecondMethod->getLocation(),
11121 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011122 << SecondMethodType << SecondName << (I + 1)
11123 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000011124 << ParamDecayedType->getOriginalType();
11125 } else {
11126 ODRDiagNote(SecondMethod->getLocation(),
11127 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011128 << SecondMethodType << SecondName << (I + 1)
11129 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000011130 }
11131 ParameterMismatch = true;
11132 break;
11133 }
11134
11135 DeclarationName FirstParamName = FirstParam->getDeclName();
11136 DeclarationName SecondParamName = SecondParam->getDeclName();
11137 if (FirstParamName != SecondParamName) {
11138 ODRDiagError(FirstMethod->getLocation(),
11139 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011140 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011141 ODRDiagNote(SecondMethod->getLocation(),
11142 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011143 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011144 ParameterMismatch = true;
11145 break;
11146 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011147
11148 const Expr *FirstInit = FirstParam->getInit();
11149 const Expr *SecondInit = SecondParam->getInit();
11150 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11151 ODRDiagError(FirstMethod->getLocation(),
11152 FirstMethod->getSourceRange(),
11153 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011154 << FirstMethodType << FirstName << (I + 1)
11155 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011156 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11157 ODRDiagNote(SecondMethod->getLocation(),
11158 SecondMethod->getSourceRange(),
11159 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011160 << SecondMethodType << SecondName << (I + 1)
11161 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011162 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11163 ParameterMismatch = true;
11164 break;
11165 }
11166
11167 if (FirstInit && SecondInit &&
11168 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11169 ODRDiagError(FirstMethod->getLocation(),
11170 FirstMethod->getSourceRange(),
11171 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011172 << FirstMethodType << FirstName << (I + 1)
11173 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011174 ODRDiagNote(SecondMethod->getLocation(),
11175 SecondMethod->getSourceRange(),
11176 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011177 << SecondMethodType << SecondName << (I + 1)
11178 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011179 ParameterMismatch = true;
11180 break;
11181
11182 }
Richard Trieu02552272017-05-02 23:58:52 +000011183 }
11184
11185 if (ParameterMismatch) {
11186 Diagnosed = true;
11187 break;
11188 }
11189
Richard Trieu7282d322018-04-25 00:31:15 +000011190 const auto *FirstTemplateArgs =
11191 FirstMethod->getTemplateSpecializationArgs();
11192 const auto *SecondTemplateArgs =
11193 SecondMethod->getTemplateSpecializationArgs();
11194
11195 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
11196 (!FirstTemplateArgs && SecondTemplateArgs)) {
11197 ODRDiagError(FirstMethod->getLocation(),
11198 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
11199 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
11200 ODRDiagNote(SecondMethod->getLocation(),
11201 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
11202 << SecondMethodType << SecondName
11203 << (SecondTemplateArgs != nullptr);
11204
11205 Diagnosed = true;
11206 break;
11207 }
11208
11209 if (FirstTemplateArgs && SecondTemplateArgs) {
11210 // Remove pack expansions from argument list.
11211 auto ExpandTemplateArgumentList =
11212 [](const TemplateArgumentList *TAL) {
11213 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
11214 for (const TemplateArgument &TA : TAL->asArray()) {
11215 if (TA.getKind() != TemplateArgument::Pack) {
11216 ExpandedList.push_back(&TA);
11217 continue;
11218 }
11219 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
11220 ExpandedList.push_back(&PackTA);
11221 }
11222 }
11223 return ExpandedList;
11224 };
11225 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
11226 ExpandTemplateArgumentList(FirstTemplateArgs);
11227 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
11228 ExpandTemplateArgumentList(SecondTemplateArgs);
11229
11230 if (FirstExpandedList.size() != SecondExpandedList.size()) {
11231 ODRDiagError(FirstMethod->getLocation(),
11232 FirstMethod->getSourceRange(),
11233 MethodDifferentNumberTemplateArguments)
11234 << FirstMethodType << FirstName
11235 << (unsigned)FirstExpandedList.size();
11236 ODRDiagNote(SecondMethod->getLocation(),
11237 SecondMethod->getSourceRange(),
11238 MethodDifferentNumberTemplateArguments)
11239 << SecondMethodType << SecondName
11240 << (unsigned)SecondExpandedList.size();
11241
11242 Diagnosed = true;
11243 break;
11244 }
11245
11246 bool TemplateArgumentMismatch = false;
11247 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
11248 const TemplateArgument &FirstTA = *FirstExpandedList[i],
11249 &SecondTA = *SecondExpandedList[i];
11250 if (ComputeTemplateArgumentODRHash(FirstTA) ==
11251 ComputeTemplateArgumentODRHash(SecondTA)) {
11252 continue;
11253 }
11254
11255 ODRDiagError(FirstMethod->getLocation(),
11256 FirstMethod->getSourceRange(),
11257 MethodDifferentTemplateArgument)
11258 << FirstMethodType << FirstName << FirstTA << i + 1;
11259 ODRDiagNote(SecondMethod->getLocation(),
11260 SecondMethod->getSourceRange(),
11261 MethodDifferentTemplateArgument)
11262 << SecondMethodType << SecondName << SecondTA << i + 1;
11263
11264 TemplateArgumentMismatch = true;
11265 break;
11266 }
11267
11268 if (TemplateArgumentMismatch) {
11269 Diagnosed = true;
11270 break;
11271 }
11272 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000011273
11274 // Compute the hash of the method as if it has no body.
11275 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
11276 Hash.clear();
11277 Hash.AddFunctionDecl(D, true /*SkipBody*/);
11278 return Hash.CalculateHash();
11279 };
11280
11281 // Compare the hash generated to the hash stored. A difference means
11282 // that a body was present in the original source. Due to merging,
11283 // the stardard way of detecting a body will not work.
11284 const bool HasFirstBody =
11285 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
11286 const bool HasSecondBody =
11287 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
11288
11289 if (HasFirstBody != HasSecondBody) {
11290 ODRDiagError(FirstMethod->getLocation(),
11291 FirstMethod->getSourceRange(), MethodSingleBody)
11292 << FirstMethodType << FirstName << HasFirstBody;
11293 ODRDiagNote(SecondMethod->getLocation(),
11294 SecondMethod->getSourceRange(), MethodSingleBody)
11295 << SecondMethodType << SecondName << HasSecondBody;
11296 Diagnosed = true;
11297 break;
11298 }
11299
11300 if (HasFirstBody && HasSecondBody) {
11301 ODRDiagError(FirstMethod->getLocation(),
11302 FirstMethod->getSourceRange(), MethodDifferentBody)
11303 << FirstMethodType << FirstName;
11304 ODRDiagNote(SecondMethod->getLocation(),
11305 SecondMethod->getSourceRange(), MethodDifferentBody)
11306 << SecondMethodType << SecondName;
11307 Diagnosed = true;
11308 break;
11309 }
11310
Richard Trieu48143742017-02-28 21:24:38 +000011311 break;
11312 }
Richard Trieu11d566a2017-06-12 21:58:22 +000011313 case TypeAlias:
11314 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011315 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
11316 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000011317 auto FirstName = FirstTD->getDeclName();
11318 auto SecondName = SecondTD->getDeclName();
11319 if (FirstName != SecondName) {
11320 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11321 TypedefName)
11322 << (FirstDiffType == TypeAlias) << FirstName;
11323 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11324 TypedefName)
11325 << (FirstDiffType == TypeAlias) << SecondName;
11326 Diagnosed = true;
11327 break;
11328 }
11329
11330 QualType FirstType = FirstTD->getUnderlyingType();
11331 QualType SecondType = SecondTD->getUnderlyingType();
11332 if (ComputeQualTypeODRHash(FirstType) !=
11333 ComputeQualTypeODRHash(SecondType)) {
11334 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11335 TypedefType)
11336 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
11337 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11338 TypedefType)
11339 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
11340 Diagnosed = true;
11341 break;
11342 }
11343 break;
11344 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011345 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011346 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
11347 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000011348 auto FirstName = FirstVD->getDeclName();
11349 auto SecondName = SecondVD->getDeclName();
11350 if (FirstName != SecondName) {
11351 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11352 VarName)
11353 << FirstName;
11354 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11355 VarName)
11356 << SecondName;
11357 Diagnosed = true;
11358 break;
11359 }
11360
11361 QualType FirstType = FirstVD->getType();
11362 QualType SecondType = SecondVD->getType();
11363 if (ComputeQualTypeODRHash(FirstType) !=
11364 ComputeQualTypeODRHash(SecondType)) {
11365 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11366 VarType)
11367 << FirstName << FirstType;
11368 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11369 VarType)
11370 << SecondName << SecondType;
11371 Diagnosed = true;
11372 break;
11373 }
11374
11375 const Expr *FirstInit = FirstVD->getInit();
11376 const Expr *SecondInit = SecondVD->getInit();
11377 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11378 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11379 VarSingleInitializer)
11380 << FirstName << (FirstInit == nullptr)
11381 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
11382 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11383 VarSingleInitializer)
11384 << SecondName << (SecondInit == nullptr)
11385 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11386 Diagnosed = true;
11387 break;
11388 }
11389
11390 if (FirstInit && SecondInit &&
11391 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11392 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11393 VarDifferentInitializer)
11394 << FirstName << FirstInit->getSourceRange();
11395 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11396 VarDifferentInitializer)
11397 << SecondName << SecondInit->getSourceRange();
11398 Diagnosed = true;
11399 break;
11400 }
11401
11402 const bool FirstIsConstexpr = FirstVD->isConstexpr();
11403 const bool SecondIsConstexpr = SecondVD->isConstexpr();
11404 if (FirstIsConstexpr != SecondIsConstexpr) {
11405 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11406 VarConstexpr)
11407 << FirstName << FirstIsConstexpr;
11408 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11409 VarConstexpr)
11410 << SecondName << SecondIsConstexpr;
11411 Diagnosed = true;
11412 break;
11413 }
11414 break;
11415 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000011416 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011417 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
11418 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000011419
11420 NamedDecl *FirstND = FirstFriend->getFriendDecl();
11421 NamedDecl *SecondND = SecondFriend->getFriendDecl();
11422
11423 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
11424 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
11425
11426 if (FirstND && SecondND) {
11427 ODRDiagError(FirstFriend->getFriendLoc(),
11428 FirstFriend->getSourceRange(), FriendFunction)
11429 << FirstND;
11430 ODRDiagNote(SecondFriend->getFriendLoc(),
11431 SecondFriend->getSourceRange(), FriendFunction)
11432 << SecondND;
11433
11434 Diagnosed = true;
11435 break;
11436 }
11437
11438 if (FirstTSI && SecondTSI) {
11439 QualType FirstFriendType = FirstTSI->getType();
11440 QualType SecondFriendType = SecondTSI->getType();
11441 assert(ComputeQualTypeODRHash(FirstFriendType) !=
11442 ComputeQualTypeODRHash(SecondFriendType));
11443 ODRDiagError(FirstFriend->getFriendLoc(),
11444 FirstFriend->getSourceRange(), FriendType)
11445 << FirstFriendType;
11446 ODRDiagNote(SecondFriend->getFriendLoc(),
11447 SecondFriend->getSourceRange(), FriendType)
11448 << SecondFriendType;
11449 Diagnosed = true;
11450 break;
11451 }
11452
11453 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
11454 FriendTypeFunction)
11455 << (FirstTSI == nullptr);
11456 ODRDiagNote(SecondFriend->getFriendLoc(),
11457 SecondFriend->getSourceRange(), FriendTypeFunction)
11458 << (SecondTSI == nullptr);
11459
11460 Diagnosed = true;
11461 break;
11462 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000011463 case FunctionTemplate: {
11464 FunctionTemplateDecl *FirstTemplate =
11465 cast<FunctionTemplateDecl>(FirstDecl);
11466 FunctionTemplateDecl *SecondTemplate =
11467 cast<FunctionTemplateDecl>(SecondDecl);
11468
11469 TemplateParameterList *FirstTPL =
11470 FirstTemplate->getTemplateParameters();
11471 TemplateParameterList *SecondTPL =
11472 SecondTemplate->getTemplateParameters();
11473
11474 if (FirstTPL->size() != SecondTPL->size()) {
11475 ODRDiagError(FirstTemplate->getLocation(),
11476 FirstTemplate->getSourceRange(),
11477 FunctionTemplateDifferentNumberParameters)
11478 << FirstTemplate << FirstTPL->size();
11479 ODRDiagNote(SecondTemplate->getLocation(),
11480 SecondTemplate->getSourceRange(),
11481 FunctionTemplateDifferentNumberParameters)
11482 << SecondTemplate << SecondTPL->size();
11483
11484 Diagnosed = true;
11485 break;
11486 }
11487
11488 bool ParameterMismatch = false;
11489 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
11490 NamedDecl *FirstParam = FirstTPL->getParam(i);
11491 NamedDecl *SecondParam = SecondTPL->getParam(i);
11492
11493 if (FirstParam->getKind() != SecondParam->getKind()) {
11494 enum {
11495 TemplateTypeParameter,
11496 NonTypeTemplateParameter,
11497 TemplateTemplateParameter,
11498 };
11499 auto GetParamType = [](NamedDecl *D) {
11500 switch (D->getKind()) {
11501 default:
11502 llvm_unreachable("Unexpected template parameter type");
11503 case Decl::TemplateTypeParm:
11504 return TemplateTypeParameter;
11505 case Decl::NonTypeTemplateParm:
11506 return NonTypeTemplateParameter;
11507 case Decl::TemplateTemplateParm:
11508 return TemplateTemplateParameter;
11509 }
11510 };
11511
11512 ODRDiagError(FirstTemplate->getLocation(),
11513 FirstTemplate->getSourceRange(),
11514 FunctionTemplateParameterDifferentKind)
11515 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11516 ODRDiagNote(SecondTemplate->getLocation(),
11517 SecondTemplate->getSourceRange(),
11518 FunctionTemplateParameterDifferentKind)
11519 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11520
11521 ParameterMismatch = true;
11522 break;
11523 }
11524
11525 if (FirstParam->getName() != SecondParam->getName()) {
11526 ODRDiagError(FirstTemplate->getLocation(),
11527 FirstTemplate->getSourceRange(),
11528 FunctionTemplateParameterName)
11529 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11530 << FirstParam;
11531 ODRDiagNote(SecondTemplate->getLocation(),
11532 SecondTemplate->getSourceRange(),
11533 FunctionTemplateParameterName)
11534 << SecondTemplate << (i + 1)
11535 << (bool)SecondParam->getIdentifier() << SecondParam;
11536 ParameterMismatch = true;
11537 break;
11538 }
11539
11540 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11541 isa<TemplateTypeParmDecl>(SecondParam)) {
11542 TemplateTypeParmDecl *FirstTTPD =
11543 cast<TemplateTypeParmDecl>(FirstParam);
11544 TemplateTypeParmDecl *SecondTTPD =
11545 cast<TemplateTypeParmDecl>(SecondParam);
11546 bool HasFirstDefaultArgument =
11547 FirstTTPD->hasDefaultArgument() &&
11548 !FirstTTPD->defaultArgumentWasInherited();
11549 bool HasSecondDefaultArgument =
11550 SecondTTPD->hasDefaultArgument() &&
11551 !SecondTTPD->defaultArgumentWasInherited();
11552 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11553 ODRDiagError(FirstTemplate->getLocation(),
11554 FirstTemplate->getSourceRange(),
11555 FunctionTemplateParameterSingleDefaultArgument)
11556 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11557 ODRDiagNote(SecondTemplate->getLocation(),
11558 SecondTemplate->getSourceRange(),
11559 FunctionTemplateParameterSingleDefaultArgument)
11560 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11561 ParameterMismatch = true;
11562 break;
11563 }
11564
11565 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11566 QualType FirstType = FirstTTPD->getDefaultArgument();
11567 QualType SecondType = SecondTTPD->getDefaultArgument();
11568 if (ComputeQualTypeODRHash(FirstType) !=
11569 ComputeQualTypeODRHash(SecondType)) {
11570 ODRDiagError(FirstTemplate->getLocation(),
11571 FirstTemplate->getSourceRange(),
11572 FunctionTemplateParameterDifferentDefaultArgument)
11573 << FirstTemplate << (i + 1) << FirstType;
11574 ODRDiagNote(SecondTemplate->getLocation(),
11575 SecondTemplate->getSourceRange(),
11576 FunctionTemplateParameterDifferentDefaultArgument)
11577 << SecondTemplate << (i + 1) << SecondType;
11578 ParameterMismatch = true;
11579 break;
11580 }
11581 }
11582
11583 if (FirstTTPD->isParameterPack() !=
11584 SecondTTPD->isParameterPack()) {
11585 ODRDiagError(FirstTemplate->getLocation(),
11586 FirstTemplate->getSourceRange(),
11587 FunctionTemplatePackParameter)
11588 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11589 ODRDiagNote(SecondTemplate->getLocation(),
11590 SecondTemplate->getSourceRange(),
11591 FunctionTemplatePackParameter)
11592 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11593 ParameterMismatch = true;
11594 break;
11595 }
11596 }
11597
11598 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11599 isa<TemplateTemplateParmDecl>(SecondParam)) {
11600 TemplateTemplateParmDecl *FirstTTPD =
11601 cast<TemplateTemplateParmDecl>(FirstParam);
11602 TemplateTemplateParmDecl *SecondTTPD =
11603 cast<TemplateTemplateParmDecl>(SecondParam);
11604
11605 TemplateParameterList *FirstTPL =
11606 FirstTTPD->getTemplateParameters();
11607 TemplateParameterList *SecondTPL =
11608 SecondTTPD->getTemplateParameters();
11609
11610 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11611 ComputeTemplateParameterListODRHash(SecondTPL)) {
11612 ODRDiagError(FirstTemplate->getLocation(),
11613 FirstTemplate->getSourceRange(),
11614 FunctionTemplateParameterDifferentType)
11615 << FirstTemplate << (i + 1);
11616 ODRDiagNote(SecondTemplate->getLocation(),
11617 SecondTemplate->getSourceRange(),
11618 FunctionTemplateParameterDifferentType)
11619 << SecondTemplate << (i + 1);
11620 ParameterMismatch = true;
11621 break;
11622 }
11623
11624 bool HasFirstDefaultArgument =
11625 FirstTTPD->hasDefaultArgument() &&
11626 !FirstTTPD->defaultArgumentWasInherited();
11627 bool HasSecondDefaultArgument =
11628 SecondTTPD->hasDefaultArgument() &&
11629 !SecondTTPD->defaultArgumentWasInherited();
11630 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11631 ODRDiagError(FirstTemplate->getLocation(),
11632 FirstTemplate->getSourceRange(),
11633 FunctionTemplateParameterSingleDefaultArgument)
11634 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11635 ODRDiagNote(SecondTemplate->getLocation(),
11636 SecondTemplate->getSourceRange(),
11637 FunctionTemplateParameterSingleDefaultArgument)
11638 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11639 ParameterMismatch = true;
11640 break;
11641 }
11642
11643 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11644 TemplateArgument FirstTA =
11645 FirstTTPD->getDefaultArgument().getArgument();
11646 TemplateArgument SecondTA =
11647 SecondTTPD->getDefaultArgument().getArgument();
11648 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11649 ComputeTemplateArgumentODRHash(SecondTA)) {
11650 ODRDiagError(FirstTemplate->getLocation(),
11651 FirstTemplate->getSourceRange(),
11652 FunctionTemplateParameterDifferentDefaultArgument)
11653 << FirstTemplate << (i + 1) << FirstTA;
11654 ODRDiagNote(SecondTemplate->getLocation(),
11655 SecondTemplate->getSourceRange(),
11656 FunctionTemplateParameterDifferentDefaultArgument)
11657 << SecondTemplate << (i + 1) << SecondTA;
11658 ParameterMismatch = true;
11659 break;
11660 }
11661 }
11662
11663 if (FirstTTPD->isParameterPack() !=
11664 SecondTTPD->isParameterPack()) {
11665 ODRDiagError(FirstTemplate->getLocation(),
11666 FirstTemplate->getSourceRange(),
11667 FunctionTemplatePackParameter)
11668 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11669 ODRDiagNote(SecondTemplate->getLocation(),
11670 SecondTemplate->getSourceRange(),
11671 FunctionTemplatePackParameter)
11672 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11673 ParameterMismatch = true;
11674 break;
11675 }
11676 }
11677
11678 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11679 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11680 NonTypeTemplateParmDecl *FirstNTTPD =
11681 cast<NonTypeTemplateParmDecl>(FirstParam);
11682 NonTypeTemplateParmDecl *SecondNTTPD =
11683 cast<NonTypeTemplateParmDecl>(SecondParam);
11684
11685 QualType FirstType = FirstNTTPD->getType();
11686 QualType SecondType = SecondNTTPD->getType();
11687 if (ComputeQualTypeODRHash(FirstType) !=
11688 ComputeQualTypeODRHash(SecondType)) {
11689 ODRDiagError(FirstTemplate->getLocation(),
11690 FirstTemplate->getSourceRange(),
11691 FunctionTemplateParameterDifferentType)
11692 << FirstTemplate << (i + 1);
11693 ODRDiagNote(SecondTemplate->getLocation(),
11694 SecondTemplate->getSourceRange(),
11695 FunctionTemplateParameterDifferentType)
11696 << SecondTemplate << (i + 1);
11697 ParameterMismatch = true;
11698 break;
11699 }
11700
11701 bool HasFirstDefaultArgument =
11702 FirstNTTPD->hasDefaultArgument() &&
11703 !FirstNTTPD->defaultArgumentWasInherited();
11704 bool HasSecondDefaultArgument =
11705 SecondNTTPD->hasDefaultArgument() &&
11706 !SecondNTTPD->defaultArgumentWasInherited();
11707 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11708 ODRDiagError(FirstTemplate->getLocation(),
11709 FirstTemplate->getSourceRange(),
11710 FunctionTemplateParameterSingleDefaultArgument)
11711 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11712 ODRDiagNote(SecondTemplate->getLocation(),
11713 SecondTemplate->getSourceRange(),
11714 FunctionTemplateParameterSingleDefaultArgument)
11715 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11716 ParameterMismatch = true;
11717 break;
11718 }
11719
11720 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11721 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11722 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11723 if (ComputeODRHash(FirstDefaultArgument) !=
11724 ComputeODRHash(SecondDefaultArgument)) {
11725 ODRDiagError(FirstTemplate->getLocation(),
11726 FirstTemplate->getSourceRange(),
11727 FunctionTemplateParameterDifferentDefaultArgument)
11728 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11729 ODRDiagNote(SecondTemplate->getLocation(),
11730 SecondTemplate->getSourceRange(),
11731 FunctionTemplateParameterDifferentDefaultArgument)
11732 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11733 ParameterMismatch = true;
11734 break;
11735 }
11736 }
11737
11738 if (FirstNTTPD->isParameterPack() !=
11739 SecondNTTPD->isParameterPack()) {
11740 ODRDiagError(FirstTemplate->getLocation(),
11741 FirstTemplate->getSourceRange(),
11742 FunctionTemplatePackParameter)
11743 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11744 ODRDiagNote(SecondTemplate->getLocation(),
11745 SecondTemplate->getSourceRange(),
11746 FunctionTemplatePackParameter)
11747 << SecondTemplate << (i + 1)
11748 << SecondNTTPD->isParameterPack();
11749 ParameterMismatch = true;
11750 break;
11751 }
11752 }
11753 }
11754
11755 if (ParameterMismatch) {
11756 Diagnosed = true;
11757 break;
11758 }
11759
11760 break;
11761 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011762 }
11763
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011764 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011765 continue;
11766
Richard Trieu708859a2017-06-08 00:56:21 +000011767 Diag(FirstDecl->getLocation(),
11768 diag::err_module_odr_violation_mismatch_decl_unknown)
11769 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11770 << FirstDecl->getSourceRange();
11771 Diag(SecondDecl->getLocation(),
11772 diag::note_module_odr_violation_mismatch_decl_unknown)
11773 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011774 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011775 }
11776
11777 if (!Diagnosed) {
11778 // All definitions are updates to the same declaration. This happens if a
11779 // module instantiates the declaration of a class template specialization
11780 // and two or more other modules instantiate its definition.
11781 //
11782 // FIXME: Indicate which modules had instantiations of this definition.
11783 // FIXME: How can this even happen?
11784 Diag(Merge.first->getLocation(),
11785 diag::err_module_odr_violation_different_instantiations)
11786 << Merge.first;
11787 }
11788 }
Richard Trieue6caa262017-12-23 00:41:01 +000011789
11790 // Issue ODR failures diagnostics for functions.
11791 for (auto &Merge : FunctionOdrMergeFailures) {
11792 enum ODRFunctionDifference {
11793 ReturnType,
11794 ParameterName,
11795 ParameterType,
11796 ParameterSingleDefaultArgument,
11797 ParameterDifferentDefaultArgument,
11798 FunctionBody,
11799 };
11800
11801 FunctionDecl *FirstFunction = Merge.first;
11802 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11803
11804 bool Diagnosed = false;
11805 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011806
Richard Trieue6caa262017-12-23 00:41:01 +000011807 if (FirstFunction == SecondFunction)
11808 continue;
11809
11810 std::string SecondModule =
11811 getOwningModuleNameForDiagnostic(SecondFunction);
11812
11813 auto ODRDiagError = [FirstFunction, &FirstModule,
11814 this](SourceLocation Loc, SourceRange Range,
11815 ODRFunctionDifference DiffType) {
11816 return Diag(Loc, diag::err_module_odr_violation_function)
11817 << FirstFunction << FirstModule.empty() << FirstModule << Range
11818 << DiffType;
11819 };
11820 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11821 SourceRange Range,
11822 ODRFunctionDifference DiffType) {
11823 return Diag(Loc, diag::note_module_odr_violation_function)
11824 << SecondModule << Range << DiffType;
11825 };
11826
11827 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11828 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11829 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11830 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11831 << FirstFunction->getReturnType();
11832 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11833 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11834 << SecondFunction->getReturnType();
11835 Diagnosed = true;
11836 break;
11837 }
11838
11839 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11840 "Merged functions with different number of parameters");
11841
11842 auto ParamSize = FirstFunction->param_size();
11843 bool ParameterMismatch = false;
11844 for (unsigned I = 0; I < ParamSize; ++I) {
11845 auto *FirstParam = FirstFunction->getParamDecl(I);
11846 auto *SecondParam = SecondFunction->getParamDecl(I);
11847
11848 assert(getContext().hasSameType(FirstParam->getType(),
11849 SecondParam->getType()) &&
11850 "Merged function has different parameter types.");
11851
11852 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11853 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11854 ParameterName)
11855 << I + 1 << FirstParam->getDeclName();
11856 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11857 ParameterName)
11858 << I + 1 << SecondParam->getDeclName();
11859 ParameterMismatch = true;
11860 break;
11861 };
11862
11863 QualType FirstParamType = FirstParam->getType();
11864 QualType SecondParamType = SecondParam->getType();
11865 if (FirstParamType != SecondParamType &&
11866 ComputeQualTypeODRHash(FirstParamType) !=
11867 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011868 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011869 FirstParamType->getAs<DecayedType>()) {
11870 ODRDiagError(FirstParam->getLocation(),
11871 FirstParam->getSourceRange(), ParameterType)
11872 << (I + 1) << FirstParamType << true
11873 << ParamDecayedType->getOriginalType();
11874 } else {
11875 ODRDiagError(FirstParam->getLocation(),
11876 FirstParam->getSourceRange(), ParameterType)
11877 << (I + 1) << FirstParamType << false;
11878 }
11879
Vedant Kumar48b4f762018-04-14 01:40:48 +000011880 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011881 SecondParamType->getAs<DecayedType>()) {
11882 ODRDiagNote(SecondParam->getLocation(),
11883 SecondParam->getSourceRange(), ParameterType)
11884 << (I + 1) << SecondParamType << true
11885 << ParamDecayedType->getOriginalType();
11886 } else {
11887 ODRDiagNote(SecondParam->getLocation(),
11888 SecondParam->getSourceRange(), ParameterType)
11889 << (I + 1) << SecondParamType << false;
11890 }
11891 ParameterMismatch = true;
11892 break;
11893 }
11894
11895 const Expr *FirstInit = FirstParam->getInit();
11896 const Expr *SecondInit = SecondParam->getInit();
11897 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11898 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11899 ParameterSingleDefaultArgument)
11900 << (I + 1) << (FirstInit == nullptr)
11901 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11902 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11903 ParameterSingleDefaultArgument)
11904 << (I + 1) << (SecondInit == nullptr)
11905 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11906 ParameterMismatch = true;
11907 break;
11908 }
11909
11910 if (FirstInit && SecondInit &&
11911 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11912 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11913 ParameterDifferentDefaultArgument)
11914 << (I + 1) << FirstInit->getSourceRange();
11915 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11916 ParameterDifferentDefaultArgument)
11917 << (I + 1) << SecondInit->getSourceRange();
11918 ParameterMismatch = true;
11919 break;
11920 }
11921
11922 assert(ComputeSubDeclODRHash(FirstParam) ==
11923 ComputeSubDeclODRHash(SecondParam) &&
11924 "Undiagnosed parameter difference.");
11925 }
11926
11927 if (ParameterMismatch) {
11928 Diagnosed = true;
11929 break;
11930 }
11931
11932 // If no error has been generated before now, assume the problem is in
11933 // the body and generate a message.
11934 ODRDiagError(FirstFunction->getLocation(),
11935 FirstFunction->getSourceRange(), FunctionBody);
11936 ODRDiagNote(SecondFunction->getLocation(),
11937 SecondFunction->getSourceRange(), FunctionBody);
11938 Diagnosed = true;
11939 break;
11940 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011941 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011942 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11943 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011944
11945 // Issue ODR failures diagnostics for enums.
11946 for (auto &Merge : EnumOdrMergeFailures) {
11947 enum ODREnumDifference {
11948 SingleScopedEnum,
11949 EnumTagKeywordMismatch,
11950 SingleSpecifiedType,
11951 DifferentSpecifiedTypes,
11952 DifferentNumberEnumConstants,
11953 EnumConstantName,
11954 EnumConstantSingleInitilizer,
11955 EnumConstantDifferentInitilizer,
11956 };
11957
11958 // If we've already pointed out a specific problem with this enum, don't
11959 // bother issuing a general "something's different" diagnostic.
11960 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11961 continue;
11962
11963 EnumDecl *FirstEnum = Merge.first;
11964 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11965
11966 using DeclHashes =
11967 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11968 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11969 DeclHashes &Hashes, EnumDecl *Enum) {
11970 for (auto *D : Enum->decls()) {
11971 // Due to decl merging, the first EnumDecl is the parent of
11972 // Decls in both records.
11973 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11974 continue;
11975 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11976 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11977 ComputeSubDeclODRHash(D));
11978 }
11979 };
11980 DeclHashes FirstHashes;
11981 PopulateHashes(FirstHashes, FirstEnum);
11982 bool Diagnosed = false;
11983 for (auto &SecondEnum : Merge.second) {
11984
11985 if (FirstEnum == SecondEnum)
11986 continue;
11987
11988 std::string SecondModule =
11989 getOwningModuleNameForDiagnostic(SecondEnum);
11990
11991 auto ODRDiagError = [FirstEnum, &FirstModule,
11992 this](SourceLocation Loc, SourceRange Range,
11993 ODREnumDifference DiffType) {
11994 return Diag(Loc, diag::err_module_odr_violation_enum)
11995 << FirstEnum << FirstModule.empty() << FirstModule << Range
11996 << DiffType;
11997 };
11998 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11999 SourceRange Range,
12000 ODREnumDifference DiffType) {
12001 return Diag(Loc, diag::note_module_odr_violation_enum)
12002 << SecondModule << Range << DiffType;
12003 };
12004
12005 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
12006 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12007 SingleScopedEnum)
12008 << FirstEnum->isScoped();
12009 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12010 SingleScopedEnum)
12011 << SecondEnum->isScoped();
12012 Diagnosed = true;
12013 continue;
12014 }
12015
12016 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
12017 if (FirstEnum->isScopedUsingClassTag() !=
12018 SecondEnum->isScopedUsingClassTag()) {
12019 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12020 EnumTagKeywordMismatch)
12021 << FirstEnum->isScopedUsingClassTag();
12022 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12023 EnumTagKeywordMismatch)
12024 << SecondEnum->isScopedUsingClassTag();
12025 Diagnosed = true;
12026 continue;
12027 }
12028 }
12029
12030 QualType FirstUnderlyingType =
12031 FirstEnum->getIntegerTypeSourceInfo()
12032 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
12033 : QualType();
12034 QualType SecondUnderlyingType =
12035 SecondEnum->getIntegerTypeSourceInfo()
12036 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
12037 : QualType();
12038 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
12039 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12040 SingleSpecifiedType)
12041 << !FirstUnderlyingType.isNull();
12042 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12043 SingleSpecifiedType)
12044 << !SecondUnderlyingType.isNull();
12045 Diagnosed = true;
12046 continue;
12047 }
12048
12049 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
12050 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
12051 ComputeQualTypeODRHash(SecondUnderlyingType)) {
12052 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12053 DifferentSpecifiedTypes)
12054 << FirstUnderlyingType;
12055 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12056 DifferentSpecifiedTypes)
12057 << SecondUnderlyingType;
12058 Diagnosed = true;
12059 continue;
12060 }
12061 }
12062
12063 DeclHashes SecondHashes;
12064 PopulateHashes(SecondHashes, SecondEnum);
12065
12066 if (FirstHashes.size() != SecondHashes.size()) {
12067 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12068 DifferentNumberEnumConstants)
12069 << (int)FirstHashes.size();
12070 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12071 DifferentNumberEnumConstants)
12072 << (int)SecondHashes.size();
12073 Diagnosed = true;
12074 continue;
12075 }
12076
12077 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
12078 if (FirstHashes[I].second == SecondHashes[I].second)
12079 continue;
12080 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
12081 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
12082
12083 if (FirstEnumConstant->getDeclName() !=
12084 SecondEnumConstant->getDeclName()) {
12085
12086 ODRDiagError(FirstEnumConstant->getLocation(),
12087 FirstEnumConstant->getSourceRange(), EnumConstantName)
12088 << I + 1 << FirstEnumConstant;
12089 ODRDiagNote(SecondEnumConstant->getLocation(),
12090 SecondEnumConstant->getSourceRange(), EnumConstantName)
12091 << I + 1 << SecondEnumConstant;
12092 Diagnosed = true;
12093 break;
12094 }
12095
12096 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
12097 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
12098 if (!FirstInit && !SecondInit)
12099 continue;
12100
12101 if (!FirstInit || !SecondInit) {
12102 ODRDiagError(FirstEnumConstant->getLocation(),
12103 FirstEnumConstant->getSourceRange(),
12104 EnumConstantSingleInitilizer)
12105 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
12106 ODRDiagNote(SecondEnumConstant->getLocation(),
12107 SecondEnumConstant->getSourceRange(),
12108 EnumConstantSingleInitilizer)
12109 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
12110 Diagnosed = true;
12111 break;
12112 }
12113
12114 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
12115 ODRDiagError(FirstEnumConstant->getLocation(),
12116 FirstEnumConstant->getSourceRange(),
12117 EnumConstantDifferentInitilizer)
12118 << I + 1 << FirstEnumConstant;
12119 ODRDiagNote(SecondEnumConstant->getLocation(),
12120 SecondEnumConstant->getSourceRange(),
12121 EnumConstantDifferentInitilizer)
12122 << I + 1 << SecondEnumConstant;
12123 Diagnosed = true;
12124 break;
12125 }
12126 }
12127 }
12128
12129 (void)Diagnosed;
12130 assert(Diagnosed && "Unable to emit ODR diagnostic.");
12131 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012132}
12133
Richard Smithce18a182015-07-14 00:26:00 +000012134void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000012135 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000012136 ReadTimer->startTimer();
12137}
12138
Guy Benyei11169dd2012-12-18 14:30:41 +000012139void ASTReader::FinishedDeserializing() {
12140 assert(NumCurrentElementsDeserializing &&
12141 "FinishedDeserializing not paired with StartedDeserializing");
12142 if (NumCurrentElementsDeserializing == 1) {
12143 // We decrease NumCurrentElementsDeserializing only after pending actions
12144 // are finished, to avoid recursively re-calling finishPendingActions().
12145 finishPendingActions();
12146 }
12147 --NumCurrentElementsDeserializing;
12148
Richard Smitha0ce9c42014-07-29 23:23:27 +000012149 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000012150 // Propagate exception specification and deduced type updates along
12151 // redeclaration chains.
12152 //
12153 // We do this now rather than in finishPendingActions because we want to
12154 // be able to walk the complete redeclaration chains of the updated decls.
12155 while (!PendingExceptionSpecUpdates.empty() ||
12156 !PendingDeducedTypeUpdates.empty()) {
12157 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000012158 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000012159 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000012160 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000012161 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000012162 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000012163 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000012164 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000012165 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000012166 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000012167 }
Richard Smitha62d1982018-08-03 01:00:01 +000012168
12169 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
12170 PendingDeducedTypeUpdates.clear();
12171 for (auto Update : DTUpdates) {
12172 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
12173 // FIXME: If the return type is already deduced, check that it matches.
12174 getContext().adjustDeducedFunctionResultType(Update.first,
12175 Update.second);
12176 }
Richard Smith9e2341d2015-03-23 03:25:59 +000012177 }
12178
Richard Smithce18a182015-07-14 00:26:00 +000012179 if (ReadTimer)
12180 ReadTimer->stopTimer();
12181
Richard Smith0f4e2c42015-08-06 04:23:48 +000012182 diagnoseOdrViolations();
12183
Richard Smith04d05b52014-03-23 00:27:18 +000012184 // We are not in recursive loading, so it's safe to pass the "interesting"
12185 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000012186 if (Consumer)
12187 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000012188 }
12189}
12190
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012191void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000012192 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
12193 // Remove any fake results before adding any real ones.
12194 auto It = PendingFakeLookupResults.find(II);
12195 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000012196 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000012197 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000012198 // FIXME: this works around module+PCH performance issue.
12199 // Rather than erase the result from the map, which is O(n), just clear
12200 // the vector of NamedDecls.
12201 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000012202 }
12203 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012204
12205 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
12206 SemaObj->TUScope->AddDecl(D);
12207 } else if (SemaObj->TUScope) {
12208 // Adding the decl to IdResolver may have failed because it was already in
12209 // (even though it was not added in scope). If it is already in, make sure
12210 // it gets in the scope as well.
12211 if (std::find(SemaObj->IdResolver.begin(Name),
12212 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
12213 SemaObj->TUScope->AddDecl(D);
12214 }
12215}
12216
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012217ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
12218 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000012219 const PCHContainerReader &PCHContainerRdr,
12220 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
12221 StringRef isysroot, bool DisableValidation,
12222 bool AllowASTWithCompilerErrors,
12223 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000012224 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000012225 std::unique_ptr<llvm::Timer> ReadTimer)
12226 : Listener(DisableValidation
12227 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
12228 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000012229 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012230 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012231 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
12232 PCHContainerRdr, PP.getHeaderSearchInfo()),
12233 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000012234 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000012235 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
12236 AllowConfigurationMismatch(AllowConfigurationMismatch),
12237 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000012238 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012239 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000012240 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000012241
12242 for (const auto &Ext : Extensions) {
12243 auto BlockName = Ext->getExtensionMetadata().BlockName;
12244 auto Known = ModuleFileExtensions.find(BlockName);
12245 if (Known != ModuleFileExtensions.end()) {
12246 Diags.Report(diag::warn_duplicate_module_file_extension)
12247 << BlockName;
12248 continue;
12249 }
12250
12251 ModuleFileExtensions.insert({BlockName, Ext});
12252 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012253}
12254
12255ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000012256 if (OwnsDeserializationListener)
12257 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000012258}
Richard Smith10379092016-05-06 23:14:07 +000012259
12260IdentifierResolver &ASTReader::getIdResolver() {
12261 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
12262}
David L. Jonesbe1557a2016-12-21 00:17:49 +000012263
JF Bastien0e828952019-06-26 19:50:12 +000012264Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
12265 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000012266 Idx = 0;
12267 Record.clear();
12268 return Cursor.readRecord(AbbrevID, Record);
12269}
Kelvin Libe286f52018-09-15 13:54:15 +000012270//===----------------------------------------------------------------------===//
12271//// OMPClauseReader implementation
12272////===----------------------------------------------------------------------===//
12273
12274OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012275 OMPClause *C = nullptr;
Kelvin Libe286f52018-09-15 13:54:15 +000012276 switch (Record.readInt()) {
12277 case OMPC_if:
12278 C = new (Context) OMPIfClause();
12279 break;
12280 case OMPC_final:
12281 C = new (Context) OMPFinalClause();
12282 break;
12283 case OMPC_num_threads:
12284 C = new (Context) OMPNumThreadsClause();
12285 break;
12286 case OMPC_safelen:
12287 C = new (Context) OMPSafelenClause();
12288 break;
12289 case OMPC_simdlen:
12290 C = new (Context) OMPSimdlenClause();
12291 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012292 case OMPC_allocator:
12293 C = new (Context) OMPAllocatorClause();
12294 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012295 case OMPC_collapse:
12296 C = new (Context) OMPCollapseClause();
12297 break;
12298 case OMPC_default:
12299 C = new (Context) OMPDefaultClause();
12300 break;
12301 case OMPC_proc_bind:
12302 C = new (Context) OMPProcBindClause();
12303 break;
12304 case OMPC_schedule:
12305 C = new (Context) OMPScheduleClause();
12306 break;
12307 case OMPC_ordered:
12308 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
12309 break;
12310 case OMPC_nowait:
12311 C = new (Context) OMPNowaitClause();
12312 break;
12313 case OMPC_untied:
12314 C = new (Context) OMPUntiedClause();
12315 break;
12316 case OMPC_mergeable:
12317 C = new (Context) OMPMergeableClause();
12318 break;
12319 case OMPC_read:
12320 C = new (Context) OMPReadClause();
12321 break;
12322 case OMPC_write:
12323 C = new (Context) OMPWriteClause();
12324 break;
12325 case OMPC_update:
12326 C = new (Context) OMPUpdateClause();
12327 break;
12328 case OMPC_capture:
12329 C = new (Context) OMPCaptureClause();
12330 break;
12331 case OMPC_seq_cst:
12332 C = new (Context) OMPSeqCstClause();
12333 break;
12334 case OMPC_threads:
12335 C = new (Context) OMPThreadsClause();
12336 break;
12337 case OMPC_simd:
12338 C = new (Context) OMPSIMDClause();
12339 break;
12340 case OMPC_nogroup:
12341 C = new (Context) OMPNogroupClause();
12342 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012343 case OMPC_unified_address:
12344 C = new (Context) OMPUnifiedAddressClause();
12345 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012346 case OMPC_unified_shared_memory:
12347 C = new (Context) OMPUnifiedSharedMemoryClause();
12348 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012349 case OMPC_reverse_offload:
12350 C = new (Context) OMPReverseOffloadClause();
12351 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012352 case OMPC_dynamic_allocators:
12353 C = new (Context) OMPDynamicAllocatorsClause();
12354 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012355 case OMPC_atomic_default_mem_order:
12356 C = new (Context) OMPAtomicDefaultMemOrderClause();
12357 break;
12358 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000012359 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
12360 break;
12361 case OMPC_firstprivate:
12362 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
12363 break;
12364 case OMPC_lastprivate:
12365 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
12366 break;
12367 case OMPC_shared:
12368 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
12369 break;
12370 case OMPC_reduction:
12371 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
12372 break;
12373 case OMPC_task_reduction:
12374 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
12375 break;
12376 case OMPC_in_reduction:
12377 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
12378 break;
12379 case OMPC_linear:
12380 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
12381 break;
12382 case OMPC_aligned:
12383 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
12384 break;
12385 case OMPC_copyin:
12386 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
12387 break;
12388 case OMPC_copyprivate:
12389 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
12390 break;
12391 case OMPC_flush:
12392 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
12393 break;
12394 case OMPC_depend: {
12395 unsigned NumVars = Record.readInt();
12396 unsigned NumLoops = Record.readInt();
12397 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
12398 break;
12399 }
12400 case OMPC_device:
12401 C = new (Context) OMPDeviceClause();
12402 break;
12403 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012404 OMPMappableExprListSizeTy Sizes;
12405 Sizes.NumVars = Record.readInt();
12406 Sizes.NumUniqueDeclarations = Record.readInt();
12407 Sizes.NumComponentLists = Record.readInt();
12408 Sizes.NumComponents = Record.readInt();
12409 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012410 break;
12411 }
12412 case OMPC_num_teams:
12413 C = new (Context) OMPNumTeamsClause();
12414 break;
12415 case OMPC_thread_limit:
12416 C = new (Context) OMPThreadLimitClause();
12417 break;
12418 case OMPC_priority:
12419 C = new (Context) OMPPriorityClause();
12420 break;
12421 case OMPC_grainsize:
12422 C = new (Context) OMPGrainsizeClause();
12423 break;
12424 case OMPC_num_tasks:
12425 C = new (Context) OMPNumTasksClause();
12426 break;
12427 case OMPC_hint:
12428 C = new (Context) OMPHintClause();
12429 break;
12430 case OMPC_dist_schedule:
12431 C = new (Context) OMPDistScheduleClause();
12432 break;
12433 case OMPC_defaultmap:
12434 C = new (Context) OMPDefaultmapClause();
12435 break;
12436 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012437 OMPMappableExprListSizeTy Sizes;
12438 Sizes.NumVars = Record.readInt();
12439 Sizes.NumUniqueDeclarations = Record.readInt();
12440 Sizes.NumComponentLists = Record.readInt();
12441 Sizes.NumComponents = Record.readInt();
12442 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012443 break;
12444 }
12445 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012446 OMPMappableExprListSizeTy Sizes;
12447 Sizes.NumVars = Record.readInt();
12448 Sizes.NumUniqueDeclarations = Record.readInt();
12449 Sizes.NumComponentLists = Record.readInt();
12450 Sizes.NumComponents = Record.readInt();
12451 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012452 break;
12453 }
12454 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012455 OMPMappableExprListSizeTy Sizes;
12456 Sizes.NumVars = Record.readInt();
12457 Sizes.NumUniqueDeclarations = Record.readInt();
12458 Sizes.NumComponentLists = Record.readInt();
12459 Sizes.NumComponents = Record.readInt();
12460 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012461 break;
12462 }
12463 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012464 OMPMappableExprListSizeTy Sizes;
12465 Sizes.NumVars = Record.readInt();
12466 Sizes.NumUniqueDeclarations = Record.readInt();
12467 Sizes.NumComponentLists = Record.readInt();
12468 Sizes.NumComponents = Record.readInt();
12469 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012470 break;
12471 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000012472 case OMPC_allocate:
12473 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
12474 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012475 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012476 assert(C && "Unknown OMPClause type");
12477
Kelvin Libe286f52018-09-15 13:54:15 +000012478 Visit(C);
12479 C->setLocStart(Record.readSourceLocation());
12480 C->setLocEnd(Record.readSourceLocation());
12481
12482 return C;
12483}
12484
12485void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12486 C->setPreInitStmt(Record.readSubStmt(),
12487 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12488}
12489
12490void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12491 VisitOMPClauseWithPreInit(C);
12492 C->setPostUpdateExpr(Record.readSubExpr());
12493}
12494
12495void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12496 VisitOMPClauseWithPreInit(C);
12497 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12498 C->setNameModifierLoc(Record.readSourceLocation());
12499 C->setColonLoc(Record.readSourceLocation());
12500 C->setCondition(Record.readSubExpr());
12501 C->setLParenLoc(Record.readSourceLocation());
12502}
12503
12504void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +000012505 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012506 C->setCondition(Record.readSubExpr());
12507 C->setLParenLoc(Record.readSourceLocation());
12508}
12509
12510void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12511 VisitOMPClauseWithPreInit(C);
12512 C->setNumThreads(Record.readSubExpr());
12513 C->setLParenLoc(Record.readSourceLocation());
12514}
12515
12516void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12517 C->setSafelen(Record.readSubExpr());
12518 C->setLParenLoc(Record.readSourceLocation());
12519}
12520
12521void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12522 C->setSimdlen(Record.readSubExpr());
12523 C->setLParenLoc(Record.readSourceLocation());
12524}
12525
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012526void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12527 C->setAllocator(Record.readExpr());
12528 C->setLParenLoc(Record.readSourceLocation());
12529}
12530
Kelvin Libe286f52018-09-15 13:54:15 +000012531void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12532 C->setNumForLoops(Record.readSubExpr());
12533 C->setLParenLoc(Record.readSourceLocation());
12534}
12535
12536void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12537 C->setDefaultKind(
12538 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12539 C->setLParenLoc(Record.readSourceLocation());
12540 C->setDefaultKindKwLoc(Record.readSourceLocation());
12541}
12542
12543void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12544 C->setProcBindKind(
12545 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12546 C->setLParenLoc(Record.readSourceLocation());
12547 C->setProcBindKindKwLoc(Record.readSourceLocation());
12548}
12549
12550void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12551 VisitOMPClauseWithPreInit(C);
12552 C->setScheduleKind(
12553 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12554 C->setFirstScheduleModifier(
12555 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12556 C->setSecondScheduleModifier(
12557 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12558 C->setChunkSize(Record.readSubExpr());
12559 C->setLParenLoc(Record.readSourceLocation());
12560 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12561 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12562 C->setScheduleKindLoc(Record.readSourceLocation());
12563 C->setCommaLoc(Record.readSourceLocation());
12564}
12565
12566void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12567 C->setNumForLoops(Record.readSubExpr());
12568 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12569 C->setLoopNumIterations(I, Record.readSubExpr());
12570 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12571 C->setLoopCounter(I, Record.readSubExpr());
12572 C->setLParenLoc(Record.readSourceLocation());
12573}
12574
12575void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12576
12577void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12578
12579void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12580
12581void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12582
12583void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12584
12585void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12586
12587void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12588
12589void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12590
12591void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12592
12593void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12594
12595void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12596
Kelvin Li1408f912018-09-26 04:28:39 +000012597void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12598
Patrick Lyster4a370b92018-10-01 13:47:43 +000012599void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12600 OMPUnifiedSharedMemoryClause *) {}
12601
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012602void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12603
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012604void
12605OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12606}
12607
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012608void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12609 OMPAtomicDefaultMemOrderClause *C) {
12610 C->setAtomicDefaultMemOrderKind(
12611 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12612 C->setLParenLoc(Record.readSourceLocation());
12613 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12614}
12615
Kelvin Libe286f52018-09-15 13:54:15 +000012616void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12617 C->setLParenLoc(Record.readSourceLocation());
12618 unsigned NumVars = C->varlist_size();
12619 SmallVector<Expr *, 16> Vars;
12620 Vars.reserve(NumVars);
12621 for (unsigned i = 0; i != NumVars; ++i)
12622 Vars.push_back(Record.readSubExpr());
12623 C->setVarRefs(Vars);
12624 Vars.clear();
12625 for (unsigned i = 0; i != NumVars; ++i)
12626 Vars.push_back(Record.readSubExpr());
12627 C->setPrivateCopies(Vars);
12628}
12629
12630void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12631 VisitOMPClauseWithPreInit(C);
12632 C->setLParenLoc(Record.readSourceLocation());
12633 unsigned NumVars = C->varlist_size();
12634 SmallVector<Expr *, 16> Vars;
12635 Vars.reserve(NumVars);
12636 for (unsigned i = 0; i != NumVars; ++i)
12637 Vars.push_back(Record.readSubExpr());
12638 C->setVarRefs(Vars);
12639 Vars.clear();
12640 for (unsigned i = 0; i != NumVars; ++i)
12641 Vars.push_back(Record.readSubExpr());
12642 C->setPrivateCopies(Vars);
12643 Vars.clear();
12644 for (unsigned i = 0; i != NumVars; ++i)
12645 Vars.push_back(Record.readSubExpr());
12646 C->setInits(Vars);
12647}
12648
12649void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12650 VisitOMPClauseWithPostUpdate(C);
12651 C->setLParenLoc(Record.readSourceLocation());
12652 unsigned NumVars = C->varlist_size();
12653 SmallVector<Expr *, 16> Vars;
12654 Vars.reserve(NumVars);
12655 for (unsigned i = 0; i != NumVars; ++i)
12656 Vars.push_back(Record.readSubExpr());
12657 C->setVarRefs(Vars);
12658 Vars.clear();
12659 for (unsigned i = 0; i != NumVars; ++i)
12660 Vars.push_back(Record.readSubExpr());
12661 C->setPrivateCopies(Vars);
12662 Vars.clear();
12663 for (unsigned i = 0; i != NumVars; ++i)
12664 Vars.push_back(Record.readSubExpr());
12665 C->setSourceExprs(Vars);
12666 Vars.clear();
12667 for (unsigned i = 0; i != NumVars; ++i)
12668 Vars.push_back(Record.readSubExpr());
12669 C->setDestinationExprs(Vars);
12670 Vars.clear();
12671 for (unsigned i = 0; i != NumVars; ++i)
12672 Vars.push_back(Record.readSubExpr());
12673 C->setAssignmentOps(Vars);
12674}
12675
12676void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12677 C->setLParenLoc(Record.readSourceLocation());
12678 unsigned NumVars = C->varlist_size();
12679 SmallVector<Expr *, 16> Vars;
12680 Vars.reserve(NumVars);
12681 for (unsigned i = 0; i != NumVars; ++i)
12682 Vars.push_back(Record.readSubExpr());
12683 C->setVarRefs(Vars);
12684}
12685
12686void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12687 VisitOMPClauseWithPostUpdate(C);
12688 C->setLParenLoc(Record.readSourceLocation());
12689 C->setColonLoc(Record.readSourceLocation());
12690 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12691 DeclarationNameInfo DNI;
12692 Record.readDeclarationNameInfo(DNI);
12693 C->setQualifierLoc(NNSL);
12694 C->setNameInfo(DNI);
12695
12696 unsigned NumVars = C->varlist_size();
12697 SmallVector<Expr *, 16> Vars;
12698 Vars.reserve(NumVars);
12699 for (unsigned i = 0; i != NumVars; ++i)
12700 Vars.push_back(Record.readSubExpr());
12701 C->setVarRefs(Vars);
12702 Vars.clear();
12703 for (unsigned i = 0; i != NumVars; ++i)
12704 Vars.push_back(Record.readSubExpr());
12705 C->setPrivates(Vars);
12706 Vars.clear();
12707 for (unsigned i = 0; i != NumVars; ++i)
12708 Vars.push_back(Record.readSubExpr());
12709 C->setLHSExprs(Vars);
12710 Vars.clear();
12711 for (unsigned i = 0; i != NumVars; ++i)
12712 Vars.push_back(Record.readSubExpr());
12713 C->setRHSExprs(Vars);
12714 Vars.clear();
12715 for (unsigned i = 0; i != NumVars; ++i)
12716 Vars.push_back(Record.readSubExpr());
12717 C->setReductionOps(Vars);
12718}
12719
12720void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12721 VisitOMPClauseWithPostUpdate(C);
12722 C->setLParenLoc(Record.readSourceLocation());
12723 C->setColonLoc(Record.readSourceLocation());
12724 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12725 DeclarationNameInfo DNI;
12726 Record.readDeclarationNameInfo(DNI);
12727 C->setQualifierLoc(NNSL);
12728 C->setNameInfo(DNI);
12729
12730 unsigned NumVars = C->varlist_size();
12731 SmallVector<Expr *, 16> Vars;
12732 Vars.reserve(NumVars);
12733 for (unsigned I = 0; I != NumVars; ++I)
12734 Vars.push_back(Record.readSubExpr());
12735 C->setVarRefs(Vars);
12736 Vars.clear();
12737 for (unsigned I = 0; I != NumVars; ++I)
12738 Vars.push_back(Record.readSubExpr());
12739 C->setPrivates(Vars);
12740 Vars.clear();
12741 for (unsigned I = 0; I != NumVars; ++I)
12742 Vars.push_back(Record.readSubExpr());
12743 C->setLHSExprs(Vars);
12744 Vars.clear();
12745 for (unsigned I = 0; I != NumVars; ++I)
12746 Vars.push_back(Record.readSubExpr());
12747 C->setRHSExprs(Vars);
12748 Vars.clear();
12749 for (unsigned I = 0; I != NumVars; ++I)
12750 Vars.push_back(Record.readSubExpr());
12751 C->setReductionOps(Vars);
12752}
12753
12754void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12755 VisitOMPClauseWithPostUpdate(C);
12756 C->setLParenLoc(Record.readSourceLocation());
12757 C->setColonLoc(Record.readSourceLocation());
12758 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12759 DeclarationNameInfo DNI;
12760 Record.readDeclarationNameInfo(DNI);
12761 C->setQualifierLoc(NNSL);
12762 C->setNameInfo(DNI);
12763
12764 unsigned NumVars = C->varlist_size();
12765 SmallVector<Expr *, 16> Vars;
12766 Vars.reserve(NumVars);
12767 for (unsigned I = 0; I != NumVars; ++I)
12768 Vars.push_back(Record.readSubExpr());
12769 C->setVarRefs(Vars);
12770 Vars.clear();
12771 for (unsigned I = 0; I != NumVars; ++I)
12772 Vars.push_back(Record.readSubExpr());
12773 C->setPrivates(Vars);
12774 Vars.clear();
12775 for (unsigned I = 0; I != NumVars; ++I)
12776 Vars.push_back(Record.readSubExpr());
12777 C->setLHSExprs(Vars);
12778 Vars.clear();
12779 for (unsigned I = 0; I != NumVars; ++I)
12780 Vars.push_back(Record.readSubExpr());
12781 C->setRHSExprs(Vars);
12782 Vars.clear();
12783 for (unsigned I = 0; I != NumVars; ++I)
12784 Vars.push_back(Record.readSubExpr());
12785 C->setReductionOps(Vars);
12786 Vars.clear();
12787 for (unsigned I = 0; I != NumVars; ++I)
12788 Vars.push_back(Record.readSubExpr());
12789 C->setTaskgroupDescriptors(Vars);
12790}
12791
12792void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12793 VisitOMPClauseWithPostUpdate(C);
12794 C->setLParenLoc(Record.readSourceLocation());
12795 C->setColonLoc(Record.readSourceLocation());
12796 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12797 C->setModifierLoc(Record.readSourceLocation());
12798 unsigned NumVars = C->varlist_size();
12799 SmallVector<Expr *, 16> Vars;
12800 Vars.reserve(NumVars);
12801 for (unsigned i = 0; i != NumVars; ++i)
12802 Vars.push_back(Record.readSubExpr());
12803 C->setVarRefs(Vars);
12804 Vars.clear();
12805 for (unsigned i = 0; i != NumVars; ++i)
12806 Vars.push_back(Record.readSubExpr());
12807 C->setPrivates(Vars);
12808 Vars.clear();
12809 for (unsigned i = 0; i != NumVars; ++i)
12810 Vars.push_back(Record.readSubExpr());
12811 C->setInits(Vars);
12812 Vars.clear();
12813 for (unsigned i = 0; i != NumVars; ++i)
12814 Vars.push_back(Record.readSubExpr());
12815 C->setUpdates(Vars);
12816 Vars.clear();
12817 for (unsigned i = 0; i != NumVars; ++i)
12818 Vars.push_back(Record.readSubExpr());
12819 C->setFinals(Vars);
12820 C->setStep(Record.readSubExpr());
12821 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012822 Vars.clear();
12823 for (unsigned I = 0; I != NumVars + 1; ++I)
12824 Vars.push_back(Record.readSubExpr());
12825 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012826}
12827
12828void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12829 C->setLParenLoc(Record.readSourceLocation());
12830 C->setColonLoc(Record.readSourceLocation());
12831 unsigned NumVars = C->varlist_size();
12832 SmallVector<Expr *, 16> Vars;
12833 Vars.reserve(NumVars);
12834 for (unsigned i = 0; i != NumVars; ++i)
12835 Vars.push_back(Record.readSubExpr());
12836 C->setVarRefs(Vars);
12837 C->setAlignment(Record.readSubExpr());
12838}
12839
12840void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12841 C->setLParenLoc(Record.readSourceLocation());
12842 unsigned NumVars = C->varlist_size();
12843 SmallVector<Expr *, 16> Exprs;
12844 Exprs.reserve(NumVars);
12845 for (unsigned i = 0; i != NumVars; ++i)
12846 Exprs.push_back(Record.readSubExpr());
12847 C->setVarRefs(Exprs);
12848 Exprs.clear();
12849 for (unsigned i = 0; i != NumVars; ++i)
12850 Exprs.push_back(Record.readSubExpr());
12851 C->setSourceExprs(Exprs);
12852 Exprs.clear();
12853 for (unsigned i = 0; i != NumVars; ++i)
12854 Exprs.push_back(Record.readSubExpr());
12855 C->setDestinationExprs(Exprs);
12856 Exprs.clear();
12857 for (unsigned i = 0; i != NumVars; ++i)
12858 Exprs.push_back(Record.readSubExpr());
12859 C->setAssignmentOps(Exprs);
12860}
12861
12862void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12863 C->setLParenLoc(Record.readSourceLocation());
12864 unsigned NumVars = C->varlist_size();
12865 SmallVector<Expr *, 16> Exprs;
12866 Exprs.reserve(NumVars);
12867 for (unsigned i = 0; i != NumVars; ++i)
12868 Exprs.push_back(Record.readSubExpr());
12869 C->setVarRefs(Exprs);
12870 Exprs.clear();
12871 for (unsigned i = 0; i != NumVars; ++i)
12872 Exprs.push_back(Record.readSubExpr());
12873 C->setSourceExprs(Exprs);
12874 Exprs.clear();
12875 for (unsigned i = 0; i != NumVars; ++i)
12876 Exprs.push_back(Record.readSubExpr());
12877 C->setDestinationExprs(Exprs);
12878 Exprs.clear();
12879 for (unsigned i = 0; i != NumVars; ++i)
12880 Exprs.push_back(Record.readSubExpr());
12881 C->setAssignmentOps(Exprs);
12882}
12883
12884void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12885 C->setLParenLoc(Record.readSourceLocation());
12886 unsigned NumVars = C->varlist_size();
12887 SmallVector<Expr *, 16> Vars;
12888 Vars.reserve(NumVars);
12889 for (unsigned i = 0; i != NumVars; ++i)
12890 Vars.push_back(Record.readSubExpr());
12891 C->setVarRefs(Vars);
12892}
12893
12894void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12895 C->setLParenLoc(Record.readSourceLocation());
12896 C->setDependencyKind(
12897 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12898 C->setDependencyLoc(Record.readSourceLocation());
12899 C->setColonLoc(Record.readSourceLocation());
12900 unsigned NumVars = C->varlist_size();
12901 SmallVector<Expr *, 16> Vars;
12902 Vars.reserve(NumVars);
12903 for (unsigned I = 0; I != NumVars; ++I)
12904 Vars.push_back(Record.readSubExpr());
12905 C->setVarRefs(Vars);
12906 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12907 C->setLoopData(I, Record.readSubExpr());
12908}
12909
12910void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12911 VisitOMPClauseWithPreInit(C);
12912 C->setDevice(Record.readSubExpr());
12913 C->setLParenLoc(Record.readSourceLocation());
12914}
12915
12916void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12917 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012918 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12919 C->setMapTypeModifier(
12920 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12921 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12922 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012923 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12924 DeclarationNameInfo DNI;
12925 Record.readDeclarationNameInfo(DNI);
12926 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012927 C->setMapType(
12928 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12929 C->setMapLoc(Record.readSourceLocation());
12930 C->setColonLoc(Record.readSourceLocation());
12931 auto NumVars = C->varlist_size();
12932 auto UniqueDecls = C->getUniqueDeclarationsNum();
12933 auto TotalLists = C->getTotalComponentListNum();
12934 auto TotalComponents = C->getTotalComponentsNum();
12935
12936 SmallVector<Expr *, 16> Vars;
12937 Vars.reserve(NumVars);
12938 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012939 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012940 C->setVarRefs(Vars);
12941
Michael Kruse4304e9d2019-02-19 16:38:20 +000012942 SmallVector<Expr *, 16> UDMappers;
12943 UDMappers.reserve(NumVars);
12944 for (unsigned I = 0; I < NumVars; ++I)
12945 UDMappers.push_back(Record.readExpr());
12946 C->setUDMapperRefs(UDMappers);
12947
Kelvin Libe286f52018-09-15 13:54:15 +000012948 SmallVector<ValueDecl *, 16> Decls;
12949 Decls.reserve(UniqueDecls);
12950 for (unsigned i = 0; i < UniqueDecls; ++i)
12951 Decls.push_back(Record.readDeclAs<ValueDecl>());
12952 C->setUniqueDecls(Decls);
12953
12954 SmallVector<unsigned, 16> ListsPerDecl;
12955 ListsPerDecl.reserve(UniqueDecls);
12956 for (unsigned i = 0; i < UniqueDecls; ++i)
12957 ListsPerDecl.push_back(Record.readInt());
12958 C->setDeclNumLists(ListsPerDecl);
12959
12960 SmallVector<unsigned, 32> ListSizes;
12961 ListSizes.reserve(TotalLists);
12962 for (unsigned i = 0; i < TotalLists; ++i)
12963 ListSizes.push_back(Record.readInt());
12964 C->setComponentListSizes(ListSizes);
12965
12966 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12967 Components.reserve(TotalComponents);
12968 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012969 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012970 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12971 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12972 AssociatedExpr, AssociatedDecl));
12973 }
12974 C->setComponents(Components, ListSizes);
12975}
12976
Alexey Bataeve04483e2019-03-27 14:14:31 +000012977void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12978 C->setLParenLoc(Record.readSourceLocation());
12979 C->setColonLoc(Record.readSourceLocation());
12980 C->setAllocator(Record.readSubExpr());
12981 unsigned NumVars = C->varlist_size();
12982 SmallVector<Expr *, 16> Vars;
12983 Vars.reserve(NumVars);
12984 for (unsigned i = 0; i != NumVars; ++i)
12985 Vars.push_back(Record.readSubExpr());
12986 C->setVarRefs(Vars);
12987}
12988
Kelvin Libe286f52018-09-15 13:54:15 +000012989void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12990 VisitOMPClauseWithPreInit(C);
12991 C->setNumTeams(Record.readSubExpr());
12992 C->setLParenLoc(Record.readSourceLocation());
12993}
12994
12995void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12996 VisitOMPClauseWithPreInit(C);
12997 C->setThreadLimit(Record.readSubExpr());
12998 C->setLParenLoc(Record.readSourceLocation());
12999}
13000
13001void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +000013002 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000013003 C->setPriority(Record.readSubExpr());
13004 C->setLParenLoc(Record.readSourceLocation());
13005}
13006
13007void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000013008 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000013009 C->setGrainsize(Record.readSubExpr());
13010 C->setLParenLoc(Record.readSourceLocation());
13011}
13012
13013void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000013014 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000013015 C->setNumTasks(Record.readSubExpr());
13016 C->setLParenLoc(Record.readSourceLocation());
13017}
13018
13019void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
13020 C->setHint(Record.readSubExpr());
13021 C->setLParenLoc(Record.readSourceLocation());
13022}
13023
13024void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
13025 VisitOMPClauseWithPreInit(C);
13026 C->setDistScheduleKind(
13027 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
13028 C->setChunkSize(Record.readSubExpr());
13029 C->setLParenLoc(Record.readSourceLocation());
13030 C->setDistScheduleKindLoc(Record.readSourceLocation());
13031 C->setCommaLoc(Record.readSourceLocation());
13032}
13033
13034void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
13035 C->setDefaultmapKind(
13036 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
13037 C->setDefaultmapModifier(
13038 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
13039 C->setLParenLoc(Record.readSourceLocation());
13040 C->setDefaultmapModifierLoc(Record.readSourceLocation());
13041 C->setDefaultmapKindLoc(Record.readSourceLocation());
13042}
13043
13044void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
13045 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000013046 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13047 DeclarationNameInfo DNI;
13048 Record.readDeclarationNameInfo(DNI);
13049 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013050 auto NumVars = C->varlist_size();
13051 auto UniqueDecls = C->getUniqueDeclarationsNum();
13052 auto TotalLists = C->getTotalComponentListNum();
13053 auto TotalComponents = C->getTotalComponentsNum();
13054
13055 SmallVector<Expr *, 16> Vars;
13056 Vars.reserve(NumVars);
13057 for (unsigned i = 0; i != NumVars; ++i)
13058 Vars.push_back(Record.readSubExpr());
13059 C->setVarRefs(Vars);
13060
Michael Kruse01f670d2019-02-22 22:29:42 +000013061 SmallVector<Expr *, 16> UDMappers;
13062 UDMappers.reserve(NumVars);
13063 for (unsigned I = 0; I < NumVars; ++I)
13064 UDMappers.push_back(Record.readSubExpr());
13065 C->setUDMapperRefs(UDMappers);
13066
Kelvin Libe286f52018-09-15 13:54:15 +000013067 SmallVector<ValueDecl *, 16> Decls;
13068 Decls.reserve(UniqueDecls);
13069 for (unsigned i = 0; i < UniqueDecls; ++i)
13070 Decls.push_back(Record.readDeclAs<ValueDecl>());
13071 C->setUniqueDecls(Decls);
13072
13073 SmallVector<unsigned, 16> ListsPerDecl;
13074 ListsPerDecl.reserve(UniqueDecls);
13075 for (unsigned i = 0; i < UniqueDecls; ++i)
13076 ListsPerDecl.push_back(Record.readInt());
13077 C->setDeclNumLists(ListsPerDecl);
13078
13079 SmallVector<unsigned, 32> ListSizes;
13080 ListSizes.reserve(TotalLists);
13081 for (unsigned i = 0; i < TotalLists; ++i)
13082 ListSizes.push_back(Record.readInt());
13083 C->setComponentListSizes(ListSizes);
13084
13085 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13086 Components.reserve(TotalComponents);
13087 for (unsigned i = 0; i < TotalComponents; ++i) {
13088 Expr *AssociatedExpr = Record.readSubExpr();
13089 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13090 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13091 AssociatedExpr, AssociatedDecl));
13092 }
13093 C->setComponents(Components, ListSizes);
13094}
13095
13096void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
13097 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000013098 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13099 DeclarationNameInfo DNI;
13100 Record.readDeclarationNameInfo(DNI);
13101 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013102 auto NumVars = C->varlist_size();
13103 auto UniqueDecls = C->getUniqueDeclarationsNum();
13104 auto TotalLists = C->getTotalComponentListNum();
13105 auto TotalComponents = C->getTotalComponentsNum();
13106
13107 SmallVector<Expr *, 16> Vars;
13108 Vars.reserve(NumVars);
13109 for (unsigned i = 0; i != NumVars; ++i)
13110 Vars.push_back(Record.readSubExpr());
13111 C->setVarRefs(Vars);
13112
Michael Kruse0336c752019-02-25 20:34:15 +000013113 SmallVector<Expr *, 16> UDMappers;
13114 UDMappers.reserve(NumVars);
13115 for (unsigned I = 0; I < NumVars; ++I)
13116 UDMappers.push_back(Record.readSubExpr());
13117 C->setUDMapperRefs(UDMappers);
13118
Kelvin Libe286f52018-09-15 13:54:15 +000013119 SmallVector<ValueDecl *, 16> Decls;
13120 Decls.reserve(UniqueDecls);
13121 for (unsigned i = 0; i < UniqueDecls; ++i)
13122 Decls.push_back(Record.readDeclAs<ValueDecl>());
13123 C->setUniqueDecls(Decls);
13124
13125 SmallVector<unsigned, 16> ListsPerDecl;
13126 ListsPerDecl.reserve(UniqueDecls);
13127 for (unsigned i = 0; i < UniqueDecls; ++i)
13128 ListsPerDecl.push_back(Record.readInt());
13129 C->setDeclNumLists(ListsPerDecl);
13130
13131 SmallVector<unsigned, 32> ListSizes;
13132 ListSizes.reserve(TotalLists);
13133 for (unsigned i = 0; i < TotalLists; ++i)
13134 ListSizes.push_back(Record.readInt());
13135 C->setComponentListSizes(ListSizes);
13136
13137 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13138 Components.reserve(TotalComponents);
13139 for (unsigned i = 0; i < TotalComponents; ++i) {
13140 Expr *AssociatedExpr = Record.readSubExpr();
13141 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13142 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13143 AssociatedExpr, AssociatedDecl));
13144 }
13145 C->setComponents(Components, ListSizes);
13146}
13147
13148void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13149 C->setLParenLoc(Record.readSourceLocation());
13150 auto NumVars = C->varlist_size();
13151 auto UniqueDecls = C->getUniqueDeclarationsNum();
13152 auto TotalLists = C->getTotalComponentListNum();
13153 auto TotalComponents = C->getTotalComponentsNum();
13154
13155 SmallVector<Expr *, 16> Vars;
13156 Vars.reserve(NumVars);
13157 for (unsigned i = 0; i != NumVars; ++i)
13158 Vars.push_back(Record.readSubExpr());
13159 C->setVarRefs(Vars);
13160 Vars.clear();
13161 for (unsigned i = 0; i != NumVars; ++i)
13162 Vars.push_back(Record.readSubExpr());
13163 C->setPrivateCopies(Vars);
13164 Vars.clear();
13165 for (unsigned i = 0; i != NumVars; ++i)
13166 Vars.push_back(Record.readSubExpr());
13167 C->setInits(Vars);
13168
13169 SmallVector<ValueDecl *, 16> Decls;
13170 Decls.reserve(UniqueDecls);
13171 for (unsigned i = 0; i < UniqueDecls; ++i)
13172 Decls.push_back(Record.readDeclAs<ValueDecl>());
13173 C->setUniqueDecls(Decls);
13174
13175 SmallVector<unsigned, 16> ListsPerDecl;
13176 ListsPerDecl.reserve(UniqueDecls);
13177 for (unsigned i = 0; i < UniqueDecls; ++i)
13178 ListsPerDecl.push_back(Record.readInt());
13179 C->setDeclNumLists(ListsPerDecl);
13180
13181 SmallVector<unsigned, 32> ListSizes;
13182 ListSizes.reserve(TotalLists);
13183 for (unsigned i = 0; i < TotalLists; ++i)
13184 ListSizes.push_back(Record.readInt());
13185 C->setComponentListSizes(ListSizes);
13186
13187 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13188 Components.reserve(TotalComponents);
13189 for (unsigned i = 0; i < TotalComponents; ++i) {
13190 Expr *AssociatedExpr = Record.readSubExpr();
13191 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13192 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13193 AssociatedExpr, AssociatedDecl));
13194 }
13195 C->setComponents(Components, ListSizes);
13196}
13197
13198void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13199 C->setLParenLoc(Record.readSourceLocation());
13200 auto NumVars = C->varlist_size();
13201 auto UniqueDecls = C->getUniqueDeclarationsNum();
13202 auto TotalLists = C->getTotalComponentListNum();
13203 auto TotalComponents = C->getTotalComponentsNum();
13204
13205 SmallVector<Expr *, 16> Vars;
13206 Vars.reserve(NumVars);
13207 for (unsigned i = 0; i != NumVars; ++i)
13208 Vars.push_back(Record.readSubExpr());
13209 C->setVarRefs(Vars);
13210 Vars.clear();
13211
13212 SmallVector<ValueDecl *, 16> Decls;
13213 Decls.reserve(UniqueDecls);
13214 for (unsigned i = 0; i < UniqueDecls; ++i)
13215 Decls.push_back(Record.readDeclAs<ValueDecl>());
13216 C->setUniqueDecls(Decls);
13217
13218 SmallVector<unsigned, 16> ListsPerDecl;
13219 ListsPerDecl.reserve(UniqueDecls);
13220 for (unsigned i = 0; i < UniqueDecls; ++i)
13221 ListsPerDecl.push_back(Record.readInt());
13222 C->setDeclNumLists(ListsPerDecl);
13223
13224 SmallVector<unsigned, 32> ListSizes;
13225 ListSizes.reserve(TotalLists);
13226 for (unsigned i = 0; i < TotalLists; ++i)
13227 ListSizes.push_back(Record.readInt());
13228 C->setComponentListSizes(ListSizes);
13229
13230 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13231 Components.reserve(TotalComponents);
13232 for (unsigned i = 0; i < TotalComponents; ++i) {
13233 Expr *AssociatedExpr = Record.readSubExpr();
13234 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13235 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13236 AssociatedExpr, AssociatedDecl));
13237 }
13238 C->setComponents(Components, ListSizes);
13239}