blob: d8790768cb39fbcf641a0cb322cb866eecbf8815 [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
1242void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001243 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 if (Diags.isDiagnosticInFlight())
1245 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1246 else
1247 Diag(DiagID) << Arg1 << Arg2;
1248}
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:
3411 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003412 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 break;
3414
3415 case SOURCE_LOCATION_PRELOADS: {
3416 // Need to transform from the local view (1-based IDs) to the global view,
3417 // which is based off F.SLocEntryBaseID.
3418 if (!F.PreloadSLocEntries.empty()) {
3419 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003420 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003422
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 F.PreloadSLocEntries.swap(Record);
3424 break;
3425 }
3426
3427 case EXT_VECTOR_DECLS:
3428 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3429 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3430 break;
3431
3432 case VTABLE_USES:
3433 if (Record.size() % 3 != 0) {
3434 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003435 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003437
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 // Later tables overwrite earlier ones.
3439 // FIXME: Modules will have some trouble with this. This is clearly not
3440 // the right way to do this.
3441 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003442
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3444 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3445 VTableUses.push_back(
3446 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3447 VTableUses.push_back(Record[Idx++]);
3448 }
3449 break;
3450
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 case PENDING_IMPLICIT_INSTANTIATIONS:
3452 if (PendingInstantiations.size() % 2 != 0) {
3453 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003454 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 }
3456
3457 if (Record.size() % 2 != 0) {
3458 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003459 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 }
3461
3462 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3463 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3464 PendingInstantiations.push_back(
3465 ReadSourceLocation(F, Record, I).getRawEncoding());
3466 }
3467 break;
3468
3469 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003470 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003471 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003472 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3475 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3476 break;
3477
3478 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003479 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3480 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3481 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003482
3483 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 unsigned StartingID;
3486 if (!PP.getPreprocessingRecord())
3487 PP.createPreprocessingRecord();
3488 if (!PP.getPreprocessingRecord()->getExternalSource())
3489 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003490 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003492 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 F.BasePreprocessedEntityID = StartingID;
3494
3495 if (F.NumPreprocessedEntities > 0) {
3496 // Introduce the global -> local mapping for preprocessed entities in
3497 // this module.
3498 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003499
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 // Introduce the local -> global mapping for preprocessed entities in
3501 // this module.
3502 F.PreprocessedEntityRemap.insertOrReplace(
3503 std::make_pair(LocalBasePreprocessedEntityID,
3504 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3505 }
3506
3507 break;
3508 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003509
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003510 case PPD_SKIPPED_RANGES: {
3511 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3512 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3513 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3514
3515 if (!PP.getPreprocessingRecord())
3516 PP.createPreprocessingRecord();
3517 if (!PP.getPreprocessingRecord()->getExternalSource())
3518 PP.getPreprocessingRecord()->SetExternalSource(*this);
3519 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3520 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003521
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003522 if (F.NumPreprocessedSkippedRanges > 0)
3523 GlobalSkippedRangeMap.insert(
3524 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3525 break;
3526 }
3527
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003528 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 if (Record.size() % 2 != 0) {
3530 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003531 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003533 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3534 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3535 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3536
3537 // If we've already loaded the decl, perform the updates when we finish
3538 // loading this block.
3539 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003540 PendingUpdateRecords.push_back(
3541 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003542 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003544
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003545 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 if (F.LocalNumObjCCategoriesInMap != 0) {
3547 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003548 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003550
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003552 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 case OBJC_CATEGORIES:
3556 F.ObjCCategories.swap(Record);
3557 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 case CUDA_SPECIAL_DECL_REFS:
3560 // Later tables overwrite earlier ones.
3561 // FIXME: Modules will have trouble with this.
3562 CUDASpecialDeclRefs.clear();
3563 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3564 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3565 break;
3566
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003567 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003568 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003569 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003570 if (Record[0]) {
3571 F.HeaderFileInfoTable
3572 = HeaderFileInfoLookupTable::Create(
3573 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3574 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003575 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003577 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003578
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 PP.getHeaderSearchInfo().SetExternalSource(this);
3580 if (!PP.getHeaderSearchInfo().getExternalLookup())
3581 PP.getHeaderSearchInfo().SetExternalLookup(this);
3582 }
3583 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003584
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 case FP_PRAGMA_OPTIONS:
3586 // Later tables overwrite earlier ones.
3587 FPPragmaOptions.swap(Record);
3588 break;
3589
3590 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003591 for (unsigned I = 0, E = Record.size(); I != E; ) {
3592 auto Name = ReadString(Record, I);
3593 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003594 Opt.Supported = Record[I++] != 0;
3595 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003596 Opt.Avail = Record[I++];
3597 Opt.Core = Record[I++];
3598 }
3599 break;
3600
3601 case OPENCL_EXTENSION_TYPES:
3602 for (unsigned I = 0, E = Record.size(); I != E;) {
3603 auto TypeID = static_cast<::TypeID>(Record[I++]);
3604 auto *Type = GetType(TypeID).getTypePtr();
3605 auto NumExt = static_cast<unsigned>(Record[I++]);
3606 for (unsigned II = 0; II != NumExt; ++II) {
3607 auto Ext = ReadString(Record, I);
3608 OpenCLTypeExtMap[Type].insert(Ext);
3609 }
3610 }
3611 break;
3612
3613 case OPENCL_EXTENSION_DECLS:
3614 for (unsigned I = 0, E = Record.size(); I != E;) {
3615 auto DeclID = static_cast<::DeclID>(Record[I++]);
3616 auto *Decl = GetDecl(DeclID);
3617 auto NumExt = static_cast<unsigned>(Record[I++]);
3618 for (unsigned II = 0; II != NumExt; ++II) {
3619 auto Ext = ReadString(Record, I);
3620 OpenCLDeclExtMap[Decl].insert(Ext);
3621 }
3622 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003623 break;
3624
3625 case TENTATIVE_DEFINITIONS:
3626 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3627 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3628 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003629
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 case KNOWN_NAMESPACES:
3631 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3632 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3633 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003634
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003635 case UNDEFINED_BUT_USED:
3636 if (UndefinedButUsed.size() % 2 != 0) {
3637 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003638 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003639 }
3640
3641 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003642 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003643 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003644 }
3645 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003646 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3647 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003648 ReadSourceLocation(F, Record, I).getRawEncoding());
3649 }
3650 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003651
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003652 case DELETE_EXPRS_TO_ANALYZE:
3653 for (unsigned I = 0, N = Record.size(); I != N;) {
3654 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3655 const uint64_t Count = Record[I++];
3656 DelayedDeleteExprs.push_back(Count);
3657 for (uint64_t C = 0; C < Count; ++C) {
3658 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3659 bool IsArrayForm = Record[I++] == 1;
3660 DelayedDeleteExprs.push_back(IsArrayForm);
3661 }
3662 }
3663 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003664
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003665 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003666 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 // If we aren't loading a module (which has its own exports), make
3668 // all of the imported modules visible.
3669 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003670 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3671 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3672 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003673 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003674 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003675 if (DeserializationListener)
3676 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3677 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 }
3679 }
3680 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003681
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 case MACRO_OFFSET: {
3683 if (F.LocalNumMacros != 0) {
3684 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003685 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003686 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003687 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 F.LocalNumMacros = Record[0];
3689 unsigned LocalBaseMacroID = Record[1];
3690 F.BaseMacroID = getTotalNumMacros();
3691
3692 if (F.LocalNumMacros > 0) {
3693 // Introduce the global -> local mapping for macros within this module.
3694 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3695
3696 // Introduce the local -> global mapping for macros within this module.
3697 F.MacroRemap.insertOrReplace(
3698 std::make_pair(LocalBaseMacroID,
3699 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003700
3701 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003702 }
3703 break;
3704 }
3705
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003706 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003707 LateParsedTemplates.append(Record.begin(), Record.end());
3708 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003709
3710 case OPTIMIZE_PRAGMA_OPTIONS:
3711 if (Record.size() != 1) {
3712 Error("invalid pragma optimize record");
3713 return Failure;
3714 }
3715 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3716 break;
Nico Weber72889432014-09-06 01:25:55 +00003717
Nico Weber779355f2016-03-02 23:22:00 +00003718 case MSSTRUCT_PRAGMA_OPTIONS:
3719 if (Record.size() != 1) {
3720 Error("invalid pragma ms_struct record");
3721 return Failure;
3722 }
3723 PragmaMSStructState = Record[0];
3724 break;
3725
Nico Weber42932312016-03-03 00:17:35 +00003726 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3727 if (Record.size() != 2) {
3728 Error("invalid pragma ms_struct record");
3729 return Failure;
3730 }
3731 PragmaMSPointersToMembersState = Record[0];
3732 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3733 break;
3734
Nico Weber72889432014-09-06 01:25:55 +00003735 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3736 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3737 UnusedLocalTypedefNameCandidates.push_back(
3738 getGlobalDeclID(F, Record[I]));
3739 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003740
3741 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3742 if (Record.size() != 1) {
3743 Error("invalid cuda pragma options record");
3744 return Failure;
3745 }
3746 ForceCUDAHostDeviceDepth = Record[0];
3747 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003748
3749 case PACK_PRAGMA_OPTIONS: {
3750 if (Record.size() < 3) {
3751 Error("invalid pragma pack record");
3752 return Failure;
3753 }
3754 PragmaPackCurrentValue = Record[0];
3755 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3756 unsigned NumStackEntries = Record[2];
3757 unsigned Idx = 3;
3758 // Reset the stack when importing a new module.
3759 PragmaPackStack.clear();
3760 for (unsigned I = 0; I < NumStackEntries; ++I) {
3761 PragmaPackStackEntry Entry;
3762 Entry.Value = Record[Idx++];
3763 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003764 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003765 PragmaPackStrings.push_back(ReadString(Record, Idx));
3766 Entry.SlotLabel = PragmaPackStrings.back();
3767 PragmaPackStack.push_back(Entry);
3768 }
3769 break;
3770 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 }
3772 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003773}
3774
Richard Smith37a93df2017-02-18 00:32:02 +00003775void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3776 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3777
3778 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003779 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003780 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3781 F.ModuleOffsetMap = StringRef();
3782
3783 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3784 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3785 F.SLocRemap.insert(std::make_pair(0U, 0));
3786 F.SLocRemap.insert(std::make_pair(2U, 1));
3787 }
3788
3789 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003790 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003791 RemapBuilder SLocRemap(F.SLocRemap);
3792 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3793 RemapBuilder MacroRemap(F.MacroRemap);
3794 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3795 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3796 RemapBuilder SelectorRemap(F.SelectorRemap);
3797 RemapBuilder DeclRemap(F.DeclRemap);
3798 RemapBuilder TypeRemap(F.TypeRemap);
3799
3800 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003801 // FIXME: Looking up dependency modules by filename is horrible. Let's
3802 // start fixing this with prebuilt and explicit modules and see how it
3803 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003804 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003805 ModuleKind Kind = static_cast<ModuleKind>(
3806 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003807 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3808 StringRef Name = StringRef((const char*)Data, Len);
3809 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003810 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3811 ? ModuleMgr.lookupByModuleName(Name)
3812 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003813 if (!OM) {
3814 std::string Msg =
3815 "SourceLocation remap refers to unknown module, cannot find ";
3816 Msg.append(Name);
3817 Error(Msg);
3818 return;
3819 }
3820
3821 uint32_t SLocOffset =
3822 endian::readNext<uint32_t, little, unaligned>(Data);
3823 uint32_t IdentifierIDOffset =
3824 endian::readNext<uint32_t, little, unaligned>(Data);
3825 uint32_t MacroIDOffset =
3826 endian::readNext<uint32_t, little, unaligned>(Data);
3827 uint32_t PreprocessedEntityIDOffset =
3828 endian::readNext<uint32_t, little, unaligned>(Data);
3829 uint32_t SubmoduleIDOffset =
3830 endian::readNext<uint32_t, little, unaligned>(Data);
3831 uint32_t SelectorIDOffset =
3832 endian::readNext<uint32_t, little, unaligned>(Data);
3833 uint32_t DeclIDOffset =
3834 endian::readNext<uint32_t, little, unaligned>(Data);
3835 uint32_t TypeIndexOffset =
3836 endian::readNext<uint32_t, little, unaligned>(Data);
3837
3838 uint32_t None = std::numeric_limits<uint32_t>::max();
3839
3840 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3841 RemapBuilder &Remap) {
3842 if (Offset != None)
3843 Remap.insert(std::make_pair(Offset,
3844 static_cast<int>(BaseOffset - Offset)));
3845 };
3846 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3847 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3848 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3849 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3850 PreprocessedEntityRemap);
3851 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3852 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3853 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3854 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3855
3856 // Global -> local mappings.
3857 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3858 }
3859}
3860
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003861ASTReader::ASTReadResult
3862ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3863 const ModuleFile *ImportedBy,
3864 unsigned ClientLoadCapabilities) {
3865 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003866 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003867
3868 // Try to resolve ModuleName in the current header search context and
3869 // verify that it is found in the same module map file as we saved. If the
3870 // top-level AST file is a main file, skip this check because there is no
3871 // usable header search context.
3872 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003873 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003874 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003875 // An implicitly-loaded module file should have its module listed in some
3876 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003877 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003878 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3879 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003880 // Don't emit module relocation error if we have -fno-validate-pch
3881 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003882 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003883 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003884 // This module was defined by an imported (explicit) module.
3885 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3886 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003887 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003888 // This module was built with a different module map.
3889 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003890 << F.ModuleName << F.FileName
3891 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3892 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003893 // In case it was imported by a PCH, there's a chance the user is
3894 // just missing to include the search path to the directory containing
3895 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003896 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003897 Diag(diag::note_imported_by_pch_module_not_found)
3898 << llvm::sys::path::parent_path(F.ModuleMapPath);
3899 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003900 }
3901 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003902 }
3903
Richard Smithe842a472014-10-22 02:05:46 +00003904 assert(M->Name == F.ModuleName && "found module with different name");
3905
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003906 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003907 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3908 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003909 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003910 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3911 "top-level import should be verified");
3912 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003913 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3914 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003915 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3916 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003917 return OutOfDate;
3918 }
3919
3920 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3921 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3922 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003923 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003924 auto F = FileMgr.getFile(Filename, false, false);
3925 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003926 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3927 Error("could not find file '" + Filename +"' referenced by AST file");
3928 return OutOfDate;
3929 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003930 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003931 }
3932
3933 // Check any additional module map files (e.g. module.private.modulemap)
3934 // that are not in the pcm.
3935 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003936 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003937 // Remove files that match
3938 // Note: SmallPtrSet::erase is really remove
3939 if (!AdditionalStoredMaps.erase(ModMap)) {
3940 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3941 Diag(diag::err_module_different_modmap)
3942 << F.ModuleName << /*new*/0 << ModMap->getName();
3943 return OutOfDate;
3944 }
3945 }
3946 }
3947
3948 // Check any additional module map files that are in the pcm, but not
3949 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003950 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003951 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3952 Diag(diag::err_module_different_modmap)
3953 << F.ModuleName << /*not new*/1 << ModMap->getName();
3954 return OutOfDate;
3955 }
3956 }
3957
3958 if (Listener)
3959 Listener->ReadModuleMapFile(F.ModuleMapPath);
3960 return Success;
3961}
3962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003963/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003964static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3965 // Find the entry for this selector in the method pool.
3966 Sema::GlobalMethodPool::iterator Known
3967 = S.MethodPool.find(Method->getSelector());
3968 if (Known == S.MethodPool.end())
3969 return;
3970
3971 // Retrieve the appropriate method list.
3972 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3973 : Known->second.second;
3974 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003975 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003976 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003977 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003978 Found = true;
3979 } else {
3980 // Keep searching.
3981 continue;
3982 }
3983 }
3984
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003985 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003986 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003987 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003988 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003989 }
3990}
3991
Richard Smithde711422015-04-23 21:20:19 +00003992void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003993 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003994 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003995 bool wasHidden = D->isHidden();
3996 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003997
Vedant Kumar48b4f762018-04-14 01:40:48 +00003998 if (wasHidden && SemaObj) {
3999 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004000 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004001 }
4002 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 }
4004}
4005
Richard Smith49f906a2014-03-01 00:08:04 +00004006void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004007 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004008 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004010 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004011 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004013 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004014
4015 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004016 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 // there is nothing more to do.
4018 continue;
4019 }
Richard Smith49f906a2014-03-01 00:08:04 +00004020
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 if (!Mod->isAvailable()) {
4022 // Modules that aren't available cannot be made visible.
4023 continue;
4024 }
4025
4026 // Update the module's name visibility.
4027 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004028
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 // If we've already deserialized any names from this module,
4030 // mark them as visible.
4031 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4032 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004033 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004035 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004036 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4037 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004039
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004041 SmallVector<Module *, 16> Exports;
4042 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004043 for (SmallVectorImpl<Module *>::iterator
4044 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4045 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004046 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004047 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 }
4050}
4051
Richard Smith6561f922016-09-12 21:06:40 +00004052/// We've merged the definition \p MergedDef into the existing definition
4053/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4054/// visible.
4055void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4056 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004057 if (Def->isHidden()) {
4058 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004059 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004060 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004061 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004062 getContext().mergeDefinitionIntoModule(
4063 Def, MergedDef->getImportedOwningModule(),
4064 /*NotifyListeners*/ false);
4065 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004066 }
Richard Smith6561f922016-09-12 21:06:40 +00004067 }
4068}
4069
Douglas Gregore060e572013-01-25 01:03:03 +00004070bool ASTReader::loadGlobalIndex() {
4071 if (GlobalIndex)
4072 return false;
4073
4074 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004075 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004076 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004077
Douglas Gregore060e572013-01-25 01:03:03 +00004078 // Try to load the global index.
4079 TriedLoadingGlobalIndex = true;
4080 StringRef ModuleCachePath
4081 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004082 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4083 GlobalModuleIndex::readIndex(ModuleCachePath);
4084 if (llvm::Error Err = std::move(Result.second)) {
4085 assert(!Result.first);
4086 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004087 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004088 }
Douglas Gregore060e572013-01-25 01:03:03 +00004089
4090 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004091 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004092 return false;
4093}
4094
4095bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004096 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004097 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4098}
4099
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004100static void updateModuleTimestamp(ModuleFile &MF) {
4101 // Overwrite the timestamp file contents so that file's mtime changes.
4102 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004103 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004104 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004105 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004106 return;
4107 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004108 OS.close();
4109 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004110}
4111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004112/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004113/// cursor into the start of the given block ID, returning false on success and
4114/// true on failure.
4115static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004116 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004117 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4118 if (!MaybeEntry) {
4119 // FIXME this drops errors on the floor.
4120 consumeError(MaybeEntry.takeError());
4121 return true;
4122 }
4123 llvm::BitstreamEntry Entry = MaybeEntry.get();
4124
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004125 switch (Entry.Kind) {
4126 case llvm::BitstreamEntry::Error:
4127 case llvm::BitstreamEntry::EndBlock:
4128 return true;
4129
4130 case llvm::BitstreamEntry::Record:
4131 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004132 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4133 break;
4134 else {
4135 // FIXME this drops errors on the floor.
4136 consumeError(Skipped.takeError());
4137 return true;
4138 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004139
4140 case llvm::BitstreamEntry::SubBlock:
4141 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004142 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4143 // FIXME this drops the error on the floor.
4144 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004145 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004146 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004147 // Found it!
4148 return false;
4149 }
4150
JF Bastien0e828952019-06-26 19:50:12 +00004151 if (llvm::Error Err = Cursor.SkipBlock()) {
4152 // FIXME this drops the error on the floor.
4153 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004154 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004155 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004156 }
4157 }
4158}
4159
Benjamin Kramer0772c422016-02-13 13:42:54 +00004160ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 ModuleKind Type,
4162 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004163 unsigned ClientLoadCapabilities,
4164 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004165 llvm::SaveAndRestore<SourceLocation>
4166 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4167
Richard Smithd1c46742014-04-30 02:24:17 +00004168 // Defer any pending actions until we get to the end of reading the AST file.
4169 Deserializing AnASTFile(this);
4170
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004172 unsigned PreviousGeneration = 0;
4173 if (ContextObj)
4174 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004175
4176 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004177 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004178 switch (ASTReadResult ReadResult =
4179 ReadASTCore(FileName, Type, ImportLoc,
4180 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4181 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00004183 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 case OutOfDate:
4185 case VersionMismatch:
4186 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00004187 case HadErrors: {
4188 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004189 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00004190 LoadedSet.insert(IM.Mod);
4191
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004192 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004193 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004194 ? &PP.getHeaderSearchInfo().getModuleMap()
4195 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004196
4197 // If we find that any modules are unusable, the global index is going
4198 // to be out-of-date. Just remove it.
4199 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004200 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00004202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 case Success:
4204 break;
4205 }
4206
4207 // Here comes stuff that we only do once the entire chain is loaded.
4208
4209 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004210 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4211 MEnd = Loaded.end();
4212 M != MEnd; ++M) {
4213 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214
4215 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004216 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4217 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004219 // Read the extension blocks.
4220 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4221 if (ASTReadResult Result = ReadExtensionBlock(F))
4222 return Result;
4223 }
4224
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004225 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 // bits of all files we've seen.
4227 F.GlobalBitOffset = TotalModulesSizeInBits;
4228 TotalModulesSizeInBits += F.SizeInBits;
4229 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004230
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004232 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4233 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 // Load it through the SourceManager and don't call ReadSLocEntry()
4235 // directly because the entry may have already been loaded in which case
4236 // calling ReadSLocEntry() directly would trigger an assertion in
4237 // SourceManager.
4238 SourceMgr.getLoadedSLocEntryByID(Index);
4239 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004240
Richard Smithea741482017-05-01 22:10:47 +00004241 // Map the original source file ID into the ID space of the current
4242 // compilation.
4243 if (F.OriginalSourceFileID.isValid()) {
4244 F.OriginalSourceFileID = FileID::get(
4245 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4246 }
4247
Richard Smith33e0f7e2015-07-22 02:08:40 +00004248 // Preload all the pending interesting identifiers by marking them out of
4249 // date.
4250 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004251 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004252 F.IdentifierTableData + Offset);
4253
4254 ASTIdentifierLookupTrait Trait(*this, F);
4255 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4256 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004257 auto &II = PP.getIdentifierTable().getOwn(Key);
4258 II.setOutOfDate(true);
4259
4260 // Mark this identifier as being from an AST file so that we can track
4261 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004262 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004263
4264 // Associate the ID with the identifier so that the writer can reuse it.
4265 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4266 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004267 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 }
4269
Douglas Gregor603cd862013-03-22 18:50:14 +00004270 // Setup the import locations and notify the module manager that we've
4271 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004272 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4273 MEnd = Loaded.end();
4274 M != MEnd; ++M) {
4275 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004276
4277 ModuleMgr.moduleFileAccepted(&F);
4278
4279 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004280 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004281 // FIXME: We assume that locations from PCH / preamble do not need
4282 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004283 if (!M->ImportedBy)
4284 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00004286 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 }
4288
Richard Smithdbafb6c2017-06-29 23:23:46 +00004289 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004290 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4291 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004292 // Mark all of the identifiers in the identifier table as being out of date,
4293 // so that various accessors know to check the loaded modules when the
4294 // identifier is used.
4295 //
4296 // For C++ modules, we don't need information on many identifiers (just
4297 // those that provide macros or are poisoned), so we mark all of
4298 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004299 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4300 IdEnd = PP.getIdentifierTable().end();
4301 Id != IdEnd; ++Id)
4302 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004303 }
Manman Rena0f31a02016-04-29 19:04:05 +00004304 // Mark selectors as out of date.
4305 for (auto Sel : SelectorGeneration)
4306 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004307
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004309 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4310 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4312 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004313
4314 switch (Unresolved.Kind) {
4315 case UnresolvedModuleRef::Conflict:
4316 if (ResolvedMod) {
4317 Module::Conflict Conflict;
4318 Conflict.Other = ResolvedMod;
4319 Conflict.Message = Unresolved.String.str();
4320 Unresolved.Mod->Conflicts.push_back(Conflict);
4321 }
4322 continue;
4323
4324 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004326 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328
Douglas Gregorfb912652013-03-20 21:10:35 +00004329 case UnresolvedModuleRef::Export:
4330 if (ResolvedMod || Unresolved.IsWildcard)
4331 Unresolved.Mod->Exports.push_back(
4332 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4333 continue;
4334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004336 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004337
Graydon Hoaree7196af2016-12-09 21:45:49 +00004338 if (Imported)
4339 Imported->append(ImportedModules.begin(),
4340 ImportedModules.end());
4341
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004342 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4343 // Might be unnecessary as use declarations are only used to build the
4344 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004345
Richard Smithdbafb6c2017-06-29 23:23:46 +00004346 if (ContextObj)
4347 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004348
Richard Smith3d8e97e2013-10-18 06:54:39 +00004349 if (SemaObj)
4350 UpdateSema();
4351
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 if (DeserializationListener)
4353 DeserializationListener->ReaderInitialized(this);
4354
4355 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004356 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 // If this AST file is a precompiled preamble, then set the
4358 // preamble file ID of the source manager to the file source file
4359 // from which the preamble was built.
4360 if (Type == MK_Preamble) {
4361 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4362 } else if (Type == MK_MainFile) {
4363 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4364 }
4365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004366
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 // For any Objective-C class definitions we have already loaded, make sure
4368 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004369 if (ContextObj) {
4370 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4371 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4372 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004373 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004374 }
4375 }
Douglas Gregore060e572013-01-25 01:03:03 +00004376
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004377 if (PP.getHeaderSearchInfo()
4378 .getHeaderSearchOpts()
4379 .ModulesValidateOncePerBuildSession) {
4380 // Now we are certain that the module and all modules it depends on are
4381 // up to date. Create or update timestamp files for modules that are
4382 // located in the module cache (not for PCH files that could be anywhere
4383 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004384 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4385 ImportedModule &M = Loaded[I];
4386 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004387 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004388 }
4389 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004390 }
4391
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 return Success;
4393}
4394
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004395static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004396
JF Bastien0e828952019-06-26 19:50:12 +00004397/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4398static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4399 // FIXME checking magic headers is done in other places such as
4400 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4401 // always done the same. Unify it all with a helper.
4402 if (!Stream.canSkipToPos(4))
4403 return llvm::createStringError(std::errc::illegal_byte_sequence,
4404 "file too small to contain AST file magic");
4405 for (unsigned C : {'C', 'P', 'C', 'H'})
4406 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4407 if (Res.get() != C)
4408 return llvm::createStringError(
4409 std::errc::illegal_byte_sequence,
4410 "file doesn't start with AST file magic");
4411 } else
4412 return Res.takeError();
4413 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004414}
4415
Richard Smith0f99d6a2015-08-09 08:48:41 +00004416static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4417 switch (Kind) {
4418 case MK_PCH:
4419 return 0; // PCH
4420 case MK_ImplicitModule:
4421 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004422 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004423 return 1; // module
4424 case MK_MainFile:
4425 case MK_Preamble:
4426 return 2; // main source file
4427 }
4428 llvm_unreachable("unknown module kind");
4429}
4430
Guy Benyei11169dd2012-12-18 14:30:41 +00004431ASTReader::ASTReadResult
4432ASTReader::ReadASTCore(StringRef FileName,
4433 ModuleKind Type,
4434 SourceLocation ImportLoc,
4435 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004436 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004437 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004438 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 unsigned ClientLoadCapabilities) {
4440 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004442 ModuleManager::AddModuleResult AddResult
4443 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004444 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004445 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004446 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004447
Douglas Gregor7029ce12013-03-19 00:28:20 +00004448 switch (AddResult) {
4449 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004450 Diag(diag::remark_module_import)
4451 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4452 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004453 return Success;
4454
4455 case ModuleManager::NewlyLoaded:
4456 // Load module file below.
4457 break;
4458
4459 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004460 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004461 // it.
4462 if (ClientLoadCapabilities & ARR_Missing)
4463 return Missing;
4464
4465 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004466 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004467 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004468 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004469 return Failure;
4470
4471 case ModuleManager::OutOfDate:
4472 // We couldn't load the module file because it is out-of-date. If the
4473 // client can handle out-of-date, return it.
4474 if (ClientLoadCapabilities & ARR_OutOfDate)
4475 return OutOfDate;
4476
4477 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004478 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004479 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004480 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 return Failure;
4482 }
4483
Douglas Gregor7029ce12013-03-19 00:28:20 +00004484 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004485
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004486 bool ShouldFinalizePCM = false;
4487 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4488 auto &MC = getModuleManager().getModuleCache();
4489 if (ShouldFinalizePCM)
4490 MC.finalizePCM(FileName);
4491 else
4492 MC.tryToDropPCM(FileName);
4493 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004495 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004496 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004497 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004498
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004500 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4501 Diag(diag::err_module_file_invalid)
4502 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 return Failure;
4504 }
4505
4506 // This is used for compatibility with older PCH formats.
4507 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004508 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004509 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4510 if (!MaybeEntry) {
4511 Error(MaybeEntry.takeError());
4512 return Failure;
4513 }
4514 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004515
Chris Lattnerefa77172013-01-20 00:00:22 +00004516 switch (Entry.Kind) {
4517 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004518 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004519 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 Error("invalid record at top-level of AST file");
4521 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004522
Chris Lattnerefa77172013-01-20 00:00:22 +00004523 case llvm::BitstreamEntry::SubBlock:
4524 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 }
4526
Chris Lattnerefa77172013-01-20 00:00:22 +00004527 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 case CONTROL_BLOCK_ID:
4529 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004530 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004532 // Check that we didn't try to load a non-module AST file as a module.
4533 //
4534 // FIXME: Should we also perform the converse check? Loading a module as
4535 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004536 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4537 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004538 F.ModuleName.empty()) {
4539 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4540 if (Result != OutOfDate ||
4541 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4542 Diag(diag::err_module_file_not_module) << FileName;
4543 return Result;
4544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 break;
4546
4547 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004548 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 case OutOfDate: return OutOfDate;
4550 case VersionMismatch: return VersionMismatch;
4551 case ConfigurationMismatch: return ConfigurationMismatch;
4552 case HadErrors: return HadErrors;
4553 }
4554 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004555
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 case AST_BLOCK_ID:
4557 if (!HaveReadControlBlock) {
4558 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004559 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 return VersionMismatch;
4561 }
4562
4563 // Record that we've loaded this module.
4564 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004565 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 return Success;
4567
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004568 case UNHASHED_CONTROL_BLOCK_ID:
4569 // This block is handled using look-ahead during ReadControlBlock. We
4570 // shouldn't get here!
4571 Error("malformed block record in AST file");
4572 return Failure;
4573
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 default:
JF Bastien0e828952019-06-26 19:50:12 +00004575 if (llvm::Error Err = Stream.SkipBlock()) {
4576 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 return Failure;
4578 }
4579 break;
4580 }
4581 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004582
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004583 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004584}
4585
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004586ASTReader::ASTReadResult
4587ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4588 unsigned ClientLoadCapabilities) {
4589 const HeaderSearchOptions &HSOpts =
4590 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4591 bool AllowCompatibleConfigurationMismatch =
4592 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4593
4594 ASTReadResult Result = readUnhashedControlBlockImpl(
4595 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4596 Listener.get(),
4597 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4598
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004599 // If F was directly imported by another module, it's implicitly validated by
4600 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004601 if (DisableValidation || WasImportedBy ||
4602 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4603 return Success;
4604
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004605 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004606 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004607 return Failure;
4608 }
4609
4610 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004611 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004612 // with it; we can only load a single version of each module.
4613 //
4614 // This can happen when a module is imported in two contexts: in one, as a
4615 // user module; in another, as a system module (due to an import from
4616 // another module marked with the [system] flag). It usually indicates a
4617 // bug in the module map: this module should also be marked with [system].
4618 //
4619 // If -Wno-system-headers (the default), and the first import is as a
4620 // system module, then validation will fail during the as-user import,
4621 // since -Werror flags won't have been validated. However, it's reasonable
4622 // to treat this consistently as a system module.
4623 //
4624 // If -Wsystem-headers, the PCM on disk was built with
4625 // -Wno-system-headers, and the first import is as a user module, then
4626 // validation will fail during the as-system import since the PCM on disk
4627 // doesn't guarantee that -Werror was respected. However, the -Werror
4628 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004629 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004630 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4631 return Success;
4632 }
4633 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004634
4635 return Result;
4636}
4637
4638ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4639 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4640 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4641 bool ValidateDiagnosticOptions) {
4642 // Initialize a stream.
4643 BitstreamCursor Stream(StreamData);
4644
4645 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004646 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4647 // FIXME this drops the error on the floor.
4648 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004649 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004650 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004651
4652 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4653 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4654 return Failure;
4655
4656 // Read all of the records in the options block.
4657 RecordData Record;
4658 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004659 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004660 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4661 if (!MaybeEntry) {
4662 // FIXME this drops the error on the floor.
4663 consumeError(MaybeEntry.takeError());
4664 return Failure;
4665 }
4666 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004667
4668 switch (Entry.Kind) {
4669 case llvm::BitstreamEntry::Error:
4670 case llvm::BitstreamEntry::SubBlock:
4671 return Failure;
4672
4673 case llvm::BitstreamEntry::EndBlock:
4674 return Result;
4675
4676 case llvm::BitstreamEntry::Record:
4677 // The interesting case.
4678 break;
4679 }
4680
4681 // Read and process a record.
4682 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004683 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4684 if (!MaybeRecordType) {
4685 // FIXME this drops the error.
4686 return Failure;
4687 }
4688 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004689 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004690 if (F)
4691 std::copy(Record.begin(), Record.end(), F->Signature.data());
4692 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004693 case DIAGNOSTIC_OPTIONS: {
4694 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4695 if (Listener && ValidateDiagnosticOptions &&
4696 !AllowCompatibleConfigurationMismatch &&
4697 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004698 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004699 break;
4700 }
4701 case DIAG_PRAGMA_MAPPINGS:
4702 if (!F)
4703 break;
4704 if (F->PragmaDiagMappings.empty())
4705 F->PragmaDiagMappings.swap(Record);
4706 else
4707 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4708 Record.begin(), Record.end());
4709 break;
4710 }
4711 }
4712}
4713
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004714/// Parse a record and blob containing module file extension metadata.
4715static bool parseModuleFileExtensionMetadata(
4716 const SmallVectorImpl<uint64_t> &Record,
4717 StringRef Blob,
4718 ModuleFileExtensionMetadata &Metadata) {
4719 if (Record.size() < 4) return true;
4720
4721 Metadata.MajorVersion = Record[0];
4722 Metadata.MinorVersion = Record[1];
4723
4724 unsigned BlockNameLen = Record[2];
4725 unsigned UserInfoLen = Record[3];
4726
4727 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4728
4729 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4730 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4731 Blob.data() + BlockNameLen + UserInfoLen);
4732 return false;
4733}
4734
4735ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4736 BitstreamCursor &Stream = F.Stream;
4737
4738 RecordData Record;
4739 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004740 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4741 if (!MaybeEntry) {
4742 Error(MaybeEntry.takeError());
4743 return Failure;
4744 }
4745 llvm::BitstreamEntry Entry = MaybeEntry.get();
4746
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004747 switch (Entry.Kind) {
4748 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004749 if (llvm::Error Err = Stream.SkipBlock()) {
4750 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004751 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004752 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004753 continue;
4754
4755 case llvm::BitstreamEntry::EndBlock:
4756 return Success;
4757
4758 case llvm::BitstreamEntry::Error:
4759 return HadErrors;
4760
4761 case llvm::BitstreamEntry::Record:
4762 break;
4763 }
4764
4765 Record.clear();
4766 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004767 Expected<unsigned> MaybeRecCode =
4768 Stream.readRecord(Entry.ID, Record, &Blob);
4769 if (!MaybeRecCode) {
4770 Error(MaybeRecCode.takeError());
4771 return Failure;
4772 }
4773 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004774 case EXTENSION_METADATA: {
4775 ModuleFileExtensionMetadata Metadata;
4776 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4777 return Failure;
4778
4779 // Find a module file extension with this block name.
4780 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4781 if (Known == ModuleFileExtensions.end()) break;
4782
4783 // Form a reader.
4784 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4785 F, Stream)) {
4786 F.ExtensionReaders.push_back(std::move(Reader));
4787 }
4788
4789 break;
4790 }
4791 }
4792 }
4793
4794 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004795}
4796
Richard Smitha7e2cc62015-05-01 01:53:09 +00004797void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004798 assert(ContextObj && "no context to initialize");
4799 ASTContext &Context = *ContextObj;
4800
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 // If there's a listener, notify them that we "read" the translation unit.
4802 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004803 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 Context.getTranslationUnitDecl());
4805
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 // FIXME: Find a better way to deal with collisions between these
4807 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004808
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 // Load the special types.
4810 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4811 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4812 if (!Context.CFConstantStringTypeDecl)
4813 Context.setCFConstantStringType(GetType(String));
4814 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004815
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4817 QualType FileType = GetType(File);
4818 if (FileType.isNull()) {
4819 Error("FILE type is NULL");
4820 return;
4821 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004822
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004824 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 Context.setFILEDecl(Typedef->getDecl());
4826 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004827 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 if (!Tag) {
4829 Error("Invalid FILE type in AST file");
4830 return;
4831 }
4832 Context.setFILEDecl(Tag->getDecl());
4833 }
4834 }
4835 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004836
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4838 QualType Jmp_bufType = GetType(Jmp_buf);
4839 if (Jmp_bufType.isNull()) {
4840 Error("jmp_buf type is NULL");
4841 return;
4842 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004843
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004845 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 Context.setjmp_bufDecl(Typedef->getDecl());
4847 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004848 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 if (!Tag) {
4850 Error("Invalid jmp_buf type in AST file");
4851 return;
4852 }
4853 Context.setjmp_bufDecl(Tag->getDecl());
4854 }
4855 }
4856 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004857
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4859 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4860 if (Sigjmp_bufType.isNull()) {
4861 Error("sigjmp_buf type is NULL");
4862 return;
4863 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004864
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004866 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 Context.setsigjmp_bufDecl(Typedef->getDecl());
4868 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004869 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 assert(Tag && "Invalid sigjmp_buf type in AST file");
4871 Context.setsigjmp_bufDecl(Tag->getDecl());
4872 }
4873 }
4874 }
4875
4876 if (unsigned ObjCIdRedef
4877 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4878 if (Context.ObjCIdRedefinitionType.isNull())
4879 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4880 }
4881
4882 if (unsigned ObjCClassRedef
4883 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4884 if (Context.ObjCClassRedefinitionType.isNull())
4885 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4886 }
4887
4888 if (unsigned ObjCSelRedef
4889 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4890 if (Context.ObjCSelRedefinitionType.isNull())
4891 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4892 }
4893
4894 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4895 QualType Ucontext_tType = GetType(Ucontext_t);
4896 if (Ucontext_tType.isNull()) {
4897 Error("ucontext_t type is NULL");
4898 return;
4899 }
4900
4901 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004902 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 Context.setucontext_tDecl(Typedef->getDecl());
4904 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004905 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 assert(Tag && "Invalid ucontext_t type in AST file");
4907 Context.setucontext_tDecl(Tag->getDecl());
4908 }
4909 }
4910 }
4911 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004912
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4914
4915 // If there were any CUDA special declarations, deserialize them.
4916 if (!CUDASpecialDeclRefs.empty()) {
4917 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4918 Context.setcudaConfigureCallDecl(
4919 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4920 }
Richard Smith56be7542014-03-21 00:33:59 +00004921
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004923 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004924 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004925 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004926 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004927 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004928 if (Import.ImportLoc.isValid())
4929 PP.makeModuleVisible(Imported, Import.ImportLoc);
4930 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 }
4933 ImportedModules.clear();
4934}
4935
4936void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004937 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004938}
4939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004940/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004941/// else returns 0.
4942static ASTFileSignature readASTFileSignature(StringRef PCH) {
4943 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004944 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4945 // FIXME this drops the error on the floor.
4946 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004947 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004948 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004949
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004950 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4951 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004952 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004953
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004954 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004955 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004956 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004957 Expected<llvm::BitstreamEntry> MaybeEntry =
4958 Stream.advanceSkippingSubblocks();
4959 if (!MaybeEntry) {
4960 // FIXME this drops the error on the floor.
4961 consumeError(MaybeEntry.takeError());
4962 return ASTFileSignature();
4963 }
4964 llvm::BitstreamEntry Entry = MaybeEntry.get();
4965
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004966 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004967 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004968
4969 Record.clear();
4970 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004971 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4972 if (!MaybeRecord) {
4973 // FIXME this drops the error on the floor.
4974 consumeError(MaybeRecord.takeError());
4975 return ASTFileSignature();
4976 }
4977 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004978 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4979 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004980 }
4981}
4982
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004983/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004984/// directly from the AST file, without actually loading the AST
4985/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004986std::string ASTReader::getOriginalSourceFile(
4987 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004988 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004990 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004992 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4993 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004994 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 }
4996
4997 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004998 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004999
5000 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005001 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5002 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005003 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005005
Chris Lattnere7b154b2013-01-19 21:39:22 +00005006 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005007 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005008 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005009 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005010 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005011
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005012 // Scan for ORIGINAL_FILE inside the control block.
5013 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005014 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005015 Expected<llvm::BitstreamEntry> MaybeEntry =
5016 Stream.advanceSkippingSubblocks();
5017 if (!MaybeEntry) {
5018 // FIXME this drops errors on the floor.
5019 consumeError(MaybeEntry.takeError());
5020 return std::string();
5021 }
5022 llvm::BitstreamEntry Entry = MaybeEntry.get();
5023
Chris Lattnere7b154b2013-01-19 21:39:22 +00005024 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005025 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005026
Chris Lattnere7b154b2013-01-19 21:39:22 +00005027 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5028 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005029 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005031
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005033 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005034 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5035 if (!MaybeRecord) {
5036 // FIXME this drops the errors on the floor.
5037 consumeError(MaybeRecord.takeError());
5038 return std::string();
5039 }
5040 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005041 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005043}
5044
5045namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005046
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 class SimplePCHValidator : public ASTReaderListener {
5048 const LangOptions &ExistingLangOpts;
5049 const TargetOptions &ExistingTargetOpts;
5050 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005051 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005053
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 public:
5055 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5056 const TargetOptions &ExistingTargetOpts,
5057 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005058 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 FileManager &FileMgr)
5060 : ExistingLangOpts(ExistingLangOpts),
5061 ExistingTargetOpts(ExistingTargetOpts),
5062 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005063 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005064 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005065
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005066 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5067 bool AllowCompatibleDifferences) override {
5068 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5069 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005071
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005072 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5073 bool AllowCompatibleDifferences) override {
5074 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5075 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005077
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005078 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5079 StringRef SpecificModuleCachePath,
5080 bool Complain) override {
5081 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5082 ExistingModuleCachePath,
5083 nullptr, ExistingLangOpts);
5084 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005085
Craig Topper3e89dfe2014-03-13 02:13:41 +00005086 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5087 bool Complain,
5088 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005089 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005090 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 }
5092 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005093
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005094} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005095
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005096bool ASTReader::readASTFileControlBlock(
5097 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005098 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005099 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005100 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005102 // FIXME: This allows use of the VFS; we do not allow use of the
5103 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005104 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 if (!Buffer) {
5106 return true;
5107 }
5108
5109 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005110 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5111 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005112
5113 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005114 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5115 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005118
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005119 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005120 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005121 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005122
5123 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005124 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005125 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005126 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005127
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005129 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005130 bool DoneWithControlBlock = false;
5131 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005132 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5133 if (!MaybeEntry) {
5134 // FIXME this drops the error on the floor.
5135 consumeError(MaybeEntry.takeError());
5136 return true;
5137 }
5138 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005139
5140 switch (Entry.Kind) {
5141 case llvm::BitstreamEntry::SubBlock: {
5142 switch (Entry.ID) {
5143 case OPTIONS_BLOCK_ID: {
5144 std::string IgnoredSuggestedPredefines;
5145 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5146 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005147 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005148 return true;
5149 break;
5150 }
5151
5152 case INPUT_FILES_BLOCK_ID:
5153 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005154 if (llvm::Error Err = Stream.SkipBlock()) {
5155 // FIXME this drops the error on the floor.
5156 consumeError(std::move(Err));
5157 return true;
5158 }
5159 if (NeedsInputFiles &&
5160 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005161 return true;
5162 break;
5163
5164 default:
JF Bastien0e828952019-06-26 19:50:12 +00005165 if (llvm::Error Err = Stream.SkipBlock()) {
5166 // FIXME this drops the error on the floor.
5167 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005168 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005169 }
Richard Smith0516b182015-09-08 19:40:14 +00005170 break;
5171 }
5172
5173 continue;
5174 }
5175
5176 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005177 DoneWithControlBlock = true;
5178 break;
Richard Smith0516b182015-09-08 19:40:14 +00005179
5180 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005181 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005182
5183 case llvm::BitstreamEntry::Record:
5184 break;
5185 }
5186
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005187 if (DoneWithControlBlock) break;
5188
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005190 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005191 Expected<unsigned> MaybeRecCode =
5192 Stream.readRecord(Entry.ID, Record, &Blob);
5193 if (!MaybeRecCode) {
5194 // FIXME this drops the error.
5195 return Failure;
5196 }
5197 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005198 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005199 if (Record[0] != VERSION_MAJOR)
5200 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005201 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005202 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005203 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005204 case MODULE_NAME:
5205 Listener.ReadModuleName(Blob);
5206 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005207 case MODULE_DIRECTORY:
5208 ModuleDir = Blob;
5209 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005210 case MODULE_MAP_FILE: {
5211 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005212 auto Path = ReadString(Record, Idx);
5213 ResolveImportedPath(Path, ModuleDir);
5214 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005215 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005216 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005217 case INPUT_FILE_OFFSETS: {
5218 if (!NeedsInputFiles)
5219 break;
5220
5221 unsigned NumInputFiles = Record[0];
5222 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005223 const llvm::support::unaligned_uint64_t *InputFileOffs =
5224 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005225 for (unsigned I = 0; I != NumInputFiles; ++I) {
5226 // Go find this input file.
5227 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005228
5229 if (isSystemFile && !NeedsSystemInputFiles)
5230 break; // the rest are system input files
5231
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005232 BitstreamCursor &Cursor = InputFilesCursor;
5233 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005234 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5235 // FIXME this drops errors on the floor.
5236 consumeError(std::move(Err));
5237 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005238
JF Bastien0e828952019-06-26 19:50:12 +00005239 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5240 if (!MaybeCode) {
5241 // FIXME this drops errors on the floor.
5242 consumeError(MaybeCode.takeError());
5243 }
5244 unsigned Code = MaybeCode.get();
5245
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005246 RecordData Record;
5247 StringRef Blob;
5248 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005249 Expected<unsigned> MaybeRecordType =
5250 Cursor.readRecord(Code, Record, &Blob);
5251 if (!MaybeRecordType) {
5252 // FIXME this drops errors on the floor.
5253 consumeError(MaybeRecordType.takeError());
5254 }
5255 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005256 case INPUT_FILE_HASH:
5257 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005258 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005259 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005260 std::string Filename = Blob;
5261 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005262 shouldContinue = Listener.visitInputFile(
5263 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005264 break;
5265 }
5266 if (!shouldContinue)
5267 break;
5268 }
5269 break;
5270 }
5271
Richard Smithd4b230b2014-10-27 23:01:16 +00005272 case IMPORTS: {
5273 if (!NeedsImports)
5274 break;
5275
5276 unsigned Idx = 0, N = Record.size();
5277 while (Idx < N) {
5278 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005279 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5280 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005281 std::string Filename = ReadString(Record, Idx);
5282 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005283 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005284 }
5285 break;
5286 }
5287
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005288 default:
5289 // No other validation to perform.
5290 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 }
5292 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005293
5294 // Look for module file extension blocks, if requested.
5295 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005296 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005297 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5298 bool DoneWithExtensionBlock = false;
5299 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005300 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5301 if (!MaybeEntry) {
5302 // FIXME this drops the error.
5303 return true;
5304 }
5305 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005306
JF Bastien0e828952019-06-26 19:50:12 +00005307 switch (Entry.Kind) {
5308 case llvm::BitstreamEntry::SubBlock:
5309 if (llvm::Error Err = Stream.SkipBlock()) {
5310 // FIXME this drops the error on the floor.
5311 consumeError(std::move(Err));
5312 return true;
5313 }
5314 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005315
JF Bastien0e828952019-06-26 19:50:12 +00005316 case llvm::BitstreamEntry::EndBlock:
5317 DoneWithExtensionBlock = true;
5318 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005319
JF Bastien0e828952019-06-26 19:50:12 +00005320 case llvm::BitstreamEntry::Error:
5321 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005322
JF Bastien0e828952019-06-26 19:50:12 +00005323 case llvm::BitstreamEntry::Record:
5324 break;
5325 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005326
5327 Record.clear();
5328 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005329 Expected<unsigned> MaybeRecCode =
5330 Stream.readRecord(Entry.ID, Record, &Blob);
5331 if (!MaybeRecCode) {
5332 // FIXME this drops the error.
5333 return true;
5334 }
5335 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005336 case EXTENSION_METADATA: {
5337 ModuleFileExtensionMetadata Metadata;
5338 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5339 return true;
5340
5341 Listener.readModuleFileExtension(Metadata);
5342 break;
5343 }
5344 }
5345 }
5346 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005347 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005348 }
5349
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005350 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5351 if (readUnhashedControlBlockImpl(
5352 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5353 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5354 ValidateDiagnosticOptions) != Success)
5355 return true;
5356
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005357 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005358}
5359
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005360bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5361 const PCHContainerReader &PCHContainerRdr,
5362 const LangOptions &LangOpts,
5363 const TargetOptions &TargetOpts,
5364 const PreprocessorOptions &PPOpts,
5365 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005366 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5367 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005368 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005369 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005370 validator,
5371 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005372}
5373
Ben Langmuir2c9af442014-04-10 17:57:43 +00005374ASTReader::ASTReadResult
5375ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005377 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5378 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005379 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005380 }
5381
5382 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5383 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005384 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 RecordData Record;
5386 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005387 Expected<llvm::BitstreamEntry> MaybeEntry =
5388 F.Stream.advanceSkippingSubblocks();
5389 if (!MaybeEntry) {
5390 Error(MaybeEntry.takeError());
5391 return Failure;
5392 }
5393 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005394
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005395 switch (Entry.Kind) {
5396 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5397 case llvm::BitstreamEntry::Error:
5398 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005399 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005400 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005401 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005402 case llvm::BitstreamEntry::Record:
5403 // The interesting case.
5404 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005406
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005408 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005410 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5411 if (!MaybeKind) {
5412 Error(MaybeKind.takeError());
5413 return Failure;
5414 }
5415 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005416
5417 if ((Kind == SUBMODULE_METADATA) != First) {
5418 Error("submodule metadata record should be at beginning of block");
5419 return Failure;
5420 }
5421 First = false;
5422
5423 // Submodule information is only valid if we have a current module.
5424 // FIXME: Should we error on these cases?
5425 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5426 Kind != SUBMODULE_DEFINITION)
5427 continue;
5428
5429 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 default: // Default behavior: ignore.
5431 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005432
Richard Smith03478d92014-10-23 22:12:14 +00005433 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005434 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005436 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 }
Richard Smith03478d92014-10-23 22:12:14 +00005438
Chris Lattner0e6c9402013-01-20 02:38:54 +00005439 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005440 unsigned Idx = 0;
5441 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5442 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005443 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005444 bool IsFramework = Record[Idx++];
5445 bool IsExplicit = Record[Idx++];
5446 bool IsSystem = Record[Idx++];
5447 bool IsExternC = Record[Idx++];
5448 bool InferSubmodules = Record[Idx++];
5449 bool InferExplicitSubmodules = Record[Idx++];
5450 bool InferExportWildcard = Record[Idx++];
5451 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005452 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005453
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005454 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005455 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005457
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 // Retrieve this (sub)module from the module map, creating it if
5459 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005460 CurrentModule =
5461 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5462 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005463
5464 // FIXME: set the definition loc for CurrentModule, or call
5465 // ModMap.setInferredModuleAllowedBy()
5466
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5468 if (GlobalIndex >= SubmodulesLoaded.size() ||
5469 SubmodulesLoaded[GlobalIndex]) {
5470 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005473
Douglas Gregor7029ce12013-03-19 00:28:20 +00005474 if (!ParentModule) {
5475 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005476 // Don't emit module relocation error if we have -fno-validate-pch
5477 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5478 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005479 if (!Diags.isDiagnosticInFlight()) {
5480 Diag(diag::err_module_file_conflict)
5481 << CurrentModule->getTopLevelModuleName()
5482 << CurFile->getName()
5483 << F.File->getName();
5484 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005485 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005486 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005487 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005488
5489 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005490 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005491 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005492
Richard Smithdd8b5332017-09-04 05:37:53 +00005493 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005494 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005495 CurrentModule->IsFromModuleFile = true;
5496 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005497 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 CurrentModule->InferSubmodules = InferSubmodules;
5499 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5500 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005501 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005502 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 if (DeserializationListener)
5504 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005505
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005507
Richard Smith8a3e39a2016-03-28 21:31:09 +00005508 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005509 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005510 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005511 CurrentModule->UnresolvedConflicts.clear();
5512 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005513
5514 // The module is available unless it's missing a requirement; relevant
5515 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5516 // Missing headers that were present when the module was built do not
5517 // make it unavailable -- if we got this far, this must be an explicitly
5518 // imported module file.
5519 CurrentModule->Requirements.clear();
5520 CurrentModule->MissingHeaders.clear();
5521 CurrentModule->IsMissingRequirement =
5522 ParentModule && ParentModule->IsMissingRequirement;
5523 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 break;
5525 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005526
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005528 std::string Filename = Blob;
5529 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005530 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005531 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005532 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5533 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005534 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5535 Error("mismatched umbrella headers in submodule");
5536 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005537 }
5538 }
5539 break;
5540 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005541
Richard Smith202210b2014-10-24 20:23:01 +00005542 case SUBMODULE_HEADER:
5543 case SUBMODULE_EXCLUDED_HEADER:
5544 case SUBMODULE_PRIVATE_HEADER:
5545 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005546 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5547 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005548 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005549
Richard Smith202210b2014-10-24 20:23:01 +00005550 case SUBMODULE_TEXTUAL_HEADER:
5551 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5552 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5553 // them here.
5554 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005555
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005556 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005557 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005559
5560 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005561 std::string Dirname = Blob;
5562 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005563 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005565 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5566 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005567 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5568 Error("mismatched umbrella directories in submodule");
5569 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005570 }
5571 }
5572 break;
5573 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005574
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 F.BaseSubmoduleID = getTotalNumSubmodules();
5577 F.LocalNumSubmodules = Record[0];
5578 unsigned LocalBaseSubmoduleID = Record[1];
5579 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005580 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 // module.
5582 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005583
5584 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005585 // module.
5586 F.SubmoduleRemap.insertOrReplace(
5587 std::make_pair(LocalBaseSubmoduleID,
5588 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005589
Ben Langmuir52ca6782014-10-20 16:27:32 +00005590 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5591 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005592 break;
5593 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005594
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005595 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005596 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005597 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005598 Unresolved.File = &F;
5599 Unresolved.Mod = CurrentModule;
5600 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005601 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005603 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 }
5605 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005606
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005607 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005609 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 Unresolved.File = &F;
5611 Unresolved.Mod = CurrentModule;
5612 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005613 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005615 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005617
5618 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 // the parsed, unresolved exports around.
5620 CurrentModule->UnresolvedExports.clear();
5621 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005622
5623 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005624 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5625 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005627
5628 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005629 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005630 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005631 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005632 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005633
5634 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005635 CurrentModule->ConfigMacros.push_back(Blob.str());
5636 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005637
5638 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005639 UnresolvedModuleRef Unresolved;
5640 Unresolved.File = &F;
5641 Unresolved.Mod = CurrentModule;
5642 Unresolved.ID = Record[0];
5643 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5644 Unresolved.IsWildcard = false;
5645 Unresolved.String = Blob;
5646 UnresolvedModuleRefs.push_back(Unresolved);
5647 break;
5648 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005649
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005650 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005651 if (!ContextObj)
5652 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005653 SmallVector<uint32_t, 16> Inits;
5654 for (auto &ID : Record)
5655 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005656 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005657 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005659
5660 case SUBMODULE_EXPORT_AS:
5661 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005662 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005663 break;
5664 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 }
5666}
5667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005669/// structure.
5670///
5671/// This routine parses the language options from the AST file and then gives
5672/// them to the AST listener if one is set.
5673///
5674/// \returns true if the listener deems the file unacceptable, false otherwise.
5675bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5676 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005677 ASTReaderListener &Listener,
5678 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 LangOptions LangOpts;
5680 unsigned Idx = 0;
5681#define LANGOPT(Name, Bits, Default, Description) \
5682 LangOpts.Name = Record[Idx++];
5683#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5684 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5685#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005686#define SANITIZER(NAME, ID) \
5687 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005688#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005689
Ben Langmuircd98cb72015-06-23 18:20:18 +00005690 for (unsigned N = Record[Idx++]; N; --N)
5691 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5692
Vedant Kumar48b4f762018-04-14 01:40:48 +00005693 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5695 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005696
Ben Langmuird4a667a2015-06-23 18:20:23 +00005697 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005698
5699 // Comment options.
5700 for (unsigned N = Record[Idx++]; N; --N) {
5701 LangOpts.CommentOpts.BlockCommandNames.push_back(
5702 ReadString(Record, Idx));
5703 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005704 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005705
Samuel Antaoee8fb302016-01-06 13:42:12 +00005706 // OpenMP offloading options.
5707 for (unsigned N = Record[Idx++]; N; --N) {
5708 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5709 }
5710
5711 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5712
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005713 return Listener.ReadLanguageOptions(LangOpts, Complain,
5714 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005715}
5716
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005717bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5718 ASTReaderListener &Listener,
5719 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005720 unsigned Idx = 0;
5721 TargetOptions TargetOpts;
5722 TargetOpts.Triple = ReadString(Record, Idx);
5723 TargetOpts.CPU = ReadString(Record, Idx);
5724 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 for (unsigned N = Record[Idx++]; N; --N) {
5726 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5727 }
5728 for (unsigned N = Record[Idx++]; N; --N) {
5729 TargetOpts.Features.push_back(ReadString(Record, Idx));
5730 }
5731
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005732 return Listener.ReadTargetOptions(TargetOpts, Complain,
5733 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734}
5735
5736bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5737 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005738 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005740#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005741#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005742 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005743#include "clang/Basic/DiagnosticOptions.def"
5744
Richard Smith3be1cb22014-08-07 00:24:21 +00005745 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005746 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005747 for (unsigned N = Record[Idx++]; N; --N)
5748 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005749
5750 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5751}
5752
5753bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5754 ASTReaderListener &Listener) {
5755 FileSystemOptions FSOpts;
5756 unsigned Idx = 0;
5757 FSOpts.WorkingDir = ReadString(Record, Idx);
5758 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5759}
5760
5761bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5762 bool Complain,
5763 ASTReaderListener &Listener) {
5764 HeaderSearchOptions HSOpts;
5765 unsigned Idx = 0;
5766 HSOpts.Sysroot = ReadString(Record, Idx);
5767
5768 // Include entries.
5769 for (unsigned N = Record[Idx++]; N; --N) {
5770 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005771 frontend::IncludeDirGroup Group
5772 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 bool IsFramework = Record[Idx++];
5774 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005775 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5776 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005777 }
5778
5779 // System header prefixes.
5780 for (unsigned N = Record[Idx++]; N; --N) {
5781 std::string Prefix = ReadString(Record, Idx);
5782 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005783 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 }
5785
5786 HSOpts.ResourceDir = ReadString(Record, Idx);
5787 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005788 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005790 HSOpts.ImplicitModuleMaps = Record[Idx++];
5791 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 HSOpts.UseBuiltinIncludes = Record[Idx++];
5793 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5794 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5795 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005796 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005797
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005798 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5799 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005800}
5801
5802bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5803 bool Complain,
5804 ASTReaderListener &Listener,
5805 std::string &SuggestedPredefines) {
5806 PreprocessorOptions PPOpts;
5807 unsigned Idx = 0;
5808
5809 // Macro definitions/undefs
5810 for (unsigned N = Record[Idx++]; N; --N) {
5811 std::string Macro = ReadString(Record, Idx);
5812 bool IsUndef = Record[Idx++];
5813 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5814 }
5815
5816 // Includes
5817 for (unsigned N = Record[Idx++]; N; --N) {
5818 PPOpts.Includes.push_back(ReadString(Record, Idx));
5819 }
5820
5821 // Macro Includes
5822 for (unsigned N = Record[Idx++]; N; --N) {
5823 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5824 }
5825
5826 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005827 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005829 PPOpts.ObjCXXARCStandardLibrary =
5830 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5831 SuggestedPredefines.clear();
5832 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5833 SuggestedPredefines);
5834}
5835
5836std::pair<ModuleFile *, unsigned>
5837ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5838 GlobalPreprocessedEntityMapType::iterator
5839 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005840 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 "Corrupted global preprocessed entity map");
5842 ModuleFile *M = I->second;
5843 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5844 return std::make_pair(M, LocalIndex);
5845}
5846
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005847llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005848ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5849 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5850 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5851 Mod.NumPreprocessedEntities);
5852
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005853 return llvm::make_range(PreprocessingRecord::iterator(),
5854 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005855}
5856
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005857llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005858ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005859 return llvm::make_range(
5860 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5861 ModuleDeclIterator(this, &Mod,
5862 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005863}
5864
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005865SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5866 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5867 assert(I != GlobalSkippedRangeMap.end() &&
5868 "Corrupted global skipped range map");
5869 ModuleFile *M = I->second;
5870 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5871 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5872 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5873 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5874 TranslateSourceLocation(*M, RawRange.getEnd()));
5875 assert(Range.isValid());
5876 return Range;
5877}
5878
Guy Benyei11169dd2012-12-18 14:30:41 +00005879PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5880 PreprocessedEntityID PPID = Index+1;
5881 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5882 ModuleFile &M = *PPInfo.first;
5883 unsigned LocalIndex = PPInfo.second;
5884 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5885
Guy Benyei11169dd2012-12-18 14:30:41 +00005886 if (!PP.getPreprocessingRecord()) {
5887 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005888 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005889 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005890
5891 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005892 if (llvm::Error Err =
5893 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5894 Error(std::move(Err));
5895 return nullptr;
5896 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005897
JF Bastien0e828952019-06-26 19:50:12 +00005898 Expected<llvm::BitstreamEntry> MaybeEntry =
5899 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5900 if (!MaybeEntry) {
5901 Error(MaybeEntry.takeError());
5902 return nullptr;
5903 }
5904 llvm::BitstreamEntry Entry = MaybeEntry.get();
5905
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005906 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005907 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005908
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005910 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5911 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005912 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005913 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005915 Expected<unsigned> MaybeRecType =
5916 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5917 if (!MaybeRecType) {
5918 Error(MaybeRecType.takeError());
5919 return nullptr;
5920 }
5921 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005922 case PPD_MACRO_EXPANSION: {
5923 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005924 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005925 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 if (isBuiltin)
5927 Name = getLocalIdentifier(M, Record[1]);
5928 else {
Richard Smith66a81862015-05-04 02:25:31 +00005929 PreprocessedEntityID GlobalID =
5930 getGlobalPreprocessedEntityID(M, Record[1]);
5931 Def = cast<MacroDefinitionRecord>(
5932 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 }
5934
5935 MacroExpansion *ME;
5936 if (isBuiltin)
5937 ME = new (PPRec) MacroExpansion(Name, Range);
5938 else
5939 ME = new (PPRec) MacroExpansion(Def, Range);
5940
5941 return ME;
5942 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005943
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 case PPD_MACRO_DEFINITION: {
5945 // Decode the identifier info and then check again; if the macro is
5946 // still defined and associated with the identifier,
5947 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005948 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005949
5950 if (DeserializationListener)
5951 DeserializationListener->MacroDefinitionRead(PPID, MD);
5952
5953 return MD;
5954 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005955
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005957 const char *FullFileNameStart = Blob.data() + Record[0];
5958 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005959 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005961 if (auto FE = PP.getFileManager().getFile(FullFileName))
5962 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005963
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005965 InclusionDirective::InclusionKind Kind
5966 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5967 InclusionDirective *ID
5968 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005969 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 Record[1], Record[3],
5971 File,
5972 Range);
5973 return ID;
5974 }
5975 }
5976
5977 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5978}
5979
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005980/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005981/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005982///
5983/// \param SLocMapI points at a chunk of a module that contains no
5984/// preprocessed entities or the entities it contains are not the ones we are
5985/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005986PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5987 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5988 ++SLocMapI;
5989 for (GlobalSLocOffsetMapType::const_iterator
5990 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5991 ModuleFile &M = *SLocMapI->second;
5992 if (M.NumPreprocessedEntities)
5993 return M.BasePreprocessedEntityID;
5994 }
5995
5996 return getTotalNumPreprocessedEntities();
5997}
5998
5999namespace {
6000
Guy Benyei11169dd2012-12-18 14:30:41 +00006001struct PPEntityComp {
6002 const ASTReader &Reader;
6003 ModuleFile &M;
6004
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006005 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006006
6007 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6008 SourceLocation LHS = getLoc(L);
6009 SourceLocation RHS = getLoc(R);
6010 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6011 }
6012
6013 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6014 SourceLocation LHS = getLoc(L);
6015 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6016 }
6017
6018 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6019 SourceLocation RHS = getLoc(R);
6020 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6021 }
6022
6023 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006024 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 }
6026};
6027
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006028} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006029
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006030PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6031 bool EndsAfter) const {
6032 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 return getTotalNumPreprocessedEntities();
6034
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006035 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6036 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6038 "Corrupted global sloc offset map");
6039
6040 if (SLocMapI->second->NumPreprocessedEntities == 0)
6041 return findNextPreprocessedEntity(SLocMapI);
6042
6043 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006044
6045 using pp_iterator = const PPEntityOffset *;
6046
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6048 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6049
6050 size_t Count = M.NumPreprocessedEntities;
6051 size_t Half;
6052 pp_iterator First = pp_begin;
6053 pp_iterator PPI;
6054
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006055 if (EndsAfter) {
6056 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006057 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006058 } else {
6059 // Do a binary search manually instead of using std::lower_bound because
6060 // The end locations of entities may be unordered (when a macro expansion
6061 // is inside another macro argument), but for this case it is not important
6062 // whether we get the first macro expansion or its containing macro.
6063 while (Count > 0) {
6064 Half = Count / 2;
6065 PPI = First;
6066 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006067 if (SourceMgr.isBeforeInTranslationUnit(
6068 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006069 First = PPI;
6070 ++First;
6071 Count = Count - Half - 1;
6072 } else
6073 Count = Half;
6074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 }
6076
6077 if (PPI == pp_end)
6078 return findNextPreprocessedEntity(SLocMapI);
6079
6080 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6081}
6082
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006083/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006084/// preprocessed entities that \arg Range encompasses.
6085std::pair<unsigned, unsigned>
6086 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6087 if (Range.isInvalid())
6088 return std::make_pair(0,0);
6089 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6090
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006091 PreprocessedEntityID BeginID =
6092 findPreprocessedEntity(Range.getBegin(), false);
6093 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 return std::make_pair(BeginID, EndID);
6095}
6096
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006097/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006098/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006099Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 FileID FID) {
6101 if (FID.isInvalid())
6102 return false;
6103
6104 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6105 ModuleFile &M = *PPInfo.first;
6106 unsigned LocalIndex = PPInfo.second;
6107 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006108
Richard Smithcb34bd32016-03-27 07:28:06 +00006109 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 if (Loc.isInvalid())
6111 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006112
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6114 return true;
6115 else
6116 return false;
6117}
6118
6119namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006121 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006124 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006125
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006127 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006128
6129 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006130 HeaderFileInfoLookupTable *Table
6131 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 if (!Table)
6133 return false;
6134
6135 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006136 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 if (Pos == Table->end())
6138 return false;
6139
Richard Smithbdf2d932015-07-30 03:37:16 +00006140 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 return true;
6142 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006143
David Blaikie05785d12013-02-20 22:23:23 +00006144 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006146
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006147} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006148
6149HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006150 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006151 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006152 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006154
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 return HeaderFileInfo();
6156}
6157
6158void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006159 using DiagState = DiagnosticsEngine::DiagState;
6160 SmallVector<DiagState *, 32> DiagStates;
6161
Vedant Kumar48b4f762018-04-14 01:40:48 +00006162 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006164 auto &Record = F.PragmaDiagMappings;
6165 if (Record.empty())
6166 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006167
Richard Smithd230de22017-01-26 01:01:01 +00006168 DiagStates.clear();
6169
6170 auto ReadDiagState =
6171 [&](const DiagState &BasedOn, SourceLocation Loc,
6172 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6173 unsigned BackrefID = Record[Idx++];
6174 if (BackrefID != 0)
6175 return DiagStates[BackrefID - 1];
6176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006178 Diag.DiagStates.push_back(BasedOn);
6179 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006181 unsigned Size = Record[Idx++];
6182 assert(Idx + Size * 2 <= Record.size() &&
6183 "Invalid data, not enough diag/map pairs");
6184 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006185 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006186 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006187 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006188 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6189 continue;
6190
6191 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6192
6193 // If this mapping was specified as a warning but the severity was
6194 // upgraded due to diagnostic settings, simulate the current diagnostic
6195 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006196 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6197 NewMapping.setSeverity(diag::Severity::Warning);
6198 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006199 }
6200
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006201 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006202 }
Richard Smithd230de22017-01-26 01:01:01 +00006203 return NewState;
6204 };
6205
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006206 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006207 DiagState *FirstState;
6208 if (F.Kind == MK_ImplicitModule) {
6209 // Implicitly-built modules are reused with different diagnostic
6210 // settings. Use the initial diagnostic state from Diag to simulate this
6211 // compilation's diagnostic settings.
6212 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6213 DiagStates.push_back(FirstState);
6214
6215 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006216 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006217 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006218 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006219 assert(Idx < Record.size() &&
6220 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006221 } else if (F.isModule()) {
6222 // For an explicit module, preserve the flags from the module build
6223 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6224 // -Wblah flags.
6225 unsigned Flags = Record[Idx++];
6226 DiagState Initial;
6227 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6228 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6229 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6230 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6231 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6232 Initial.ExtBehavior = (diag::Severity)Flags;
6233 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006234
Richard Smith6c2b5a82018-02-09 01:15:13 +00006235 assert(F.OriginalSourceFileID.isValid());
6236
Richard Smithe37391c2017-05-03 00:28:49 +00006237 // Set up the root buffer of the module to start with the initial
6238 // diagnostic state of the module itself, to cover files that contain no
6239 // explicit transitions (for which we did not serialize anything).
6240 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6241 .StateTransitions.push_back({FirstState, 0});
6242 } else {
6243 // For prefix ASTs, start with whatever the user configured on the
6244 // command line.
6245 Idx++; // Skip flags.
6246 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6247 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006248 }
Richard Smithd230de22017-01-26 01:01:01 +00006249
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006250 // Read the state transitions.
6251 unsigned NumLocations = Record[Idx++];
6252 while (NumLocations--) {
6253 assert(Idx < Record.size() &&
6254 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006255 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6256 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006257 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006258 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6259 unsigned Transitions = Record[Idx++];
6260
6261 // Note that we don't need to set up Parent/ParentOffset here, because
6262 // we won't be changing the diagnostic state within imported FileIDs
6263 // (other than perhaps appending to the main source file, which has no
6264 // parent).
6265 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6266 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6267 for (unsigned I = 0; I != Transitions; ++I) {
6268 unsigned Offset = Record[Idx++];
6269 auto *State =
6270 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6271 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 }
6273 }
Richard Smithd230de22017-01-26 01:01:01 +00006274
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006275 // Read the final state.
6276 assert(Idx < Record.size() &&
6277 "Invalid data, missing final pragma diagnostic state");
6278 SourceLocation CurStateLoc =
6279 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6280 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6281
6282 if (!F.isModule()) {
6283 Diag.DiagStatesByLoc.CurDiagState = CurState;
6284 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6285
6286 // Preserve the property that the imaginary root file describes the
6287 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006288 FileID NullFile;
6289 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006290 if (T.empty())
6291 T.push_back({CurState, 0});
6292 else
6293 T[0].State = CurState;
6294 }
6295
Richard Smithd230de22017-01-26 01:01:01 +00006296 // Don't try to read these mappings again.
6297 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 }
6299}
6300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006301/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006302ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6303 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6304 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6305 ModuleFile *M = I->second;
6306 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6307}
6308
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006309/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006310///
6311/// The index is the type ID, shifted and minus the number of predefs. This
6312/// routine actually reads the record corresponding to the type at the given
6313/// location. It is a helper routine for GetType, which deals with reading type
6314/// IDs.
6315QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006316 assert(ContextObj && "reading type with no AST context");
6317 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006319 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006320
6321 // Keep track of where we are in the stream, then jump back there
6322 // after reading this type.
6323 SavedStreamPosition SavedPosition(DeclsCursor);
6324
6325 ReadingKindTracker ReadingKind(Read_Type, *this);
6326
6327 // Note that we are loading a type record.
6328 Deserializing AType(this);
6329
6330 unsigned Idx = 0;
JF Bastien0e828952019-06-26 19:50:12 +00006331 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6332 Error(std::move(Err));
6333 return QualType();
6334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00006336 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
6337 if (!MaybeCode) {
6338 Error(MaybeCode.takeError());
6339 return QualType();
6340 }
6341 unsigned Code = MaybeCode.get();
6342
6343 Expected<unsigned> MaybeTypeCode = DeclsCursor.readRecord(Code, Record);
6344 if (!MaybeTypeCode) {
6345 Error(MaybeTypeCode.takeError());
6346 return QualType();
6347 }
6348 switch ((TypeCode)MaybeTypeCode.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 case TYPE_EXT_QUAL: {
6350 if (Record.size() != 2) {
6351 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006352 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 }
6354 QualType Base = readType(*Loc.F, Record, Idx);
6355 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
6356 return Context.getQualifiedType(Base, Quals);
6357 }
6358
6359 case TYPE_COMPLEX: {
6360 if (Record.size() != 1) {
6361 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006362 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 }
6364 QualType ElemType = readType(*Loc.F, Record, Idx);
6365 return Context.getComplexType(ElemType);
6366 }
6367
6368 case TYPE_POINTER: {
6369 if (Record.size() != 1) {
6370 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006371 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 }
6373 QualType PointeeType = readType(*Loc.F, Record, Idx);
6374 return Context.getPointerType(PointeeType);
6375 }
6376
Reid Kleckner8a365022013-06-24 17:51:48 +00006377 case TYPE_DECAYED: {
6378 if (Record.size() != 1) {
6379 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006380 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00006381 }
6382 QualType OriginalType = readType(*Loc.F, Record, Idx);
6383 QualType DT = Context.getAdjustedParameterType(OriginalType);
6384 if (!isa<DecayedType>(DT))
6385 Error("Decayed type does not decay");
6386 return DT;
6387 }
6388
Reid Kleckner0503a872013-12-05 01:23:43 +00006389 case TYPE_ADJUSTED: {
6390 if (Record.size() != 2) {
6391 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006392 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00006393 }
6394 QualType OriginalTy = readType(*Loc.F, Record, Idx);
6395 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
6396 return Context.getAdjustedType(OriginalTy, AdjustedTy);
6397 }
6398
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 case TYPE_BLOCK_POINTER: {
6400 if (Record.size() != 1) {
6401 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006402 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 }
6404 QualType PointeeType = readType(*Loc.F, Record, Idx);
6405 return Context.getBlockPointerType(PointeeType);
6406 }
6407
6408 case TYPE_LVALUE_REFERENCE: {
6409 if (Record.size() != 2) {
6410 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006411 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 }
6413 QualType PointeeType = readType(*Loc.F, Record, Idx);
6414 return Context.getLValueReferenceType(PointeeType, Record[1]);
6415 }
6416
6417 case TYPE_RVALUE_REFERENCE: {
6418 if (Record.size() != 1) {
6419 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006420 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 }
6422 QualType PointeeType = readType(*Loc.F, Record, Idx);
6423 return Context.getRValueReferenceType(PointeeType);
6424 }
6425
6426 case TYPE_MEMBER_POINTER: {
6427 if (Record.size() != 2) {
6428 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006429 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 }
6431 QualType PointeeType = readType(*Loc.F, Record, Idx);
6432 QualType ClassType = readType(*Loc.F, Record, Idx);
6433 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006434 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006435
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
6437 }
6438
6439 case TYPE_CONSTANT_ARRAY: {
6440 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006441 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 unsigned IndexTypeQuals = Record[2];
6443 unsigned Idx = 3;
6444 llvm::APInt Size = ReadAPInt(Record, Idx);
Richard Smith772e2662019-10-04 01:25:59 +00006445 Expr *SizeExpr = ReadExpr(*Loc.F);
6446 return Context.getConstantArrayType(ElementType, Size, SizeExpr,
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 ASM, IndexTypeQuals);
6448 }
6449
6450 case TYPE_INCOMPLETE_ARRAY: {
6451 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006452 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 unsigned IndexTypeQuals = Record[2];
6454 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6455 }
6456
6457 case TYPE_VARIABLE_ARRAY: {
6458 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006459 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 unsigned IndexTypeQuals = Record[2];
6461 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6462 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6463 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6464 ASM, IndexTypeQuals,
6465 SourceRange(LBLoc, RBLoc));
6466 }
6467
6468 case TYPE_VECTOR: {
6469 if (Record.size() != 3) {
6470 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006471 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 }
6473
6474 QualType ElementType = readType(*Loc.F, Record, Idx);
6475 unsigned NumElements = Record[1];
6476 unsigned VecKind = Record[2];
6477 return Context.getVectorType(ElementType, NumElements,
6478 (VectorType::VectorKind)VecKind);
6479 }
6480
6481 case TYPE_EXT_VECTOR: {
6482 if (Record.size() != 3) {
6483 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006484 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 }
6486
6487 QualType ElementType = readType(*Loc.F, Record, Idx);
6488 unsigned NumElements = Record[1];
6489 return Context.getExtVectorType(ElementType, NumElements);
6490 }
6491
6492 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006493 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006495 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 }
6497 QualType ResultType = readType(*Loc.F, Record, Idx);
6498 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006499 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006500 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 return Context.getFunctionNoProtoType(ResultType, Info);
6502 }
6503
6504 case TYPE_FUNCTION_PROTO: {
6505 QualType ResultType = readType(*Loc.F, Record, Idx);
6506
6507 FunctionProtoType::ExtProtoInfo EPI;
6508 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6509 /*hasregparm*/ Record[2],
6510 /*regparm*/ Record[3],
6511 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006512 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006513 /*nocallersavedregs*/ Record[6],
6514 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006515
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006516 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006517
6518 EPI.Variadic = Record[Idx++];
6519 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006520 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006522 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006523 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006524
6525 unsigned NumParams = Record[Idx++];
6526 SmallVector<QualType, 16> ParamTypes;
6527 for (unsigned I = 0; I != NumParams; ++I)
6528 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6529
John McCall18afab72016-03-01 00:49:02 +00006530 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6531 if (Idx != Record.size()) {
6532 for (unsigned I = 0; I != NumParams; ++I)
6533 ExtParameterInfos.push_back(
6534 FunctionProtoType::ExtParameterInfo
6535 ::getFromOpaqueValue(Record[Idx++]));
6536 EPI.ExtParameterInfos = ExtParameterInfos.data();
6537 }
6538
6539 assert(Idx == Record.size());
6540
Jordan Rose5c382722013-03-08 21:51:21 +00006541 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 }
6543
6544 case TYPE_UNRESOLVED_USING: {
6545 unsigned Idx = 0;
6546 return Context.getTypeDeclType(
6547 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6548 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006549
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 case TYPE_TYPEDEF: {
6551 if (Record.size() != 2) {
6552 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006553 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006554 }
6555 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006556 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 QualType Canonical = readType(*Loc.F, Record, Idx);
6558 if (!Canonical.isNull())
6559 Canonical = Context.getCanonicalType(Canonical);
6560 return Context.getTypedefType(Decl, Canonical);
6561 }
6562
6563 case TYPE_TYPEOF_EXPR:
6564 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6565
6566 case TYPE_TYPEOF: {
6567 if (Record.size() != 1) {
6568 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006569 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 }
6571 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6572 return Context.getTypeOfType(UnderlyingType);
6573 }
6574
6575 case TYPE_DECLTYPE: {
6576 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6577 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6578 }
6579
6580 case TYPE_UNARY_TRANSFORM: {
6581 QualType BaseType = readType(*Loc.F, Record, Idx);
6582 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006583 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6585 }
6586
Richard Smith74aeef52013-04-26 16:15:35 +00006587 case TYPE_AUTO: {
6588 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006589 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006590 bool IsDependent = false, IsPack = false;
6591 if (Deduced.isNull()) {
6592 IsDependent = Record[Idx] > 0;
6593 IsPack = Record[Idx] > 1;
6594 ++Idx;
6595 }
6596 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006597 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006598
Richard Smith600b5262017-01-26 20:40:47 +00006599 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6600 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6601 QualType Deduced = readType(*Loc.F, Record, Idx);
6602 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6603 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6604 IsDependent);
6605 }
6606
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 case TYPE_RECORD: {
6608 if (Record.size() != 2) {
6609 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006610 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 }
6612 unsigned Idx = 0;
6613 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006614 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6616 QualType T = Context.getRecordType(RD);
6617 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6618 return T;
6619 }
6620
6621 case TYPE_ENUM: {
6622 if (Record.size() != 2) {
6623 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006624 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 }
6626 unsigned Idx = 0;
6627 bool IsDependent = Record[Idx++];
6628 QualType T
6629 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6630 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6631 return T;
6632 }
6633
6634 case TYPE_ATTRIBUTED: {
6635 if (Record.size() != 3) {
6636 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006637 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 }
6639 QualType modifiedType = readType(*Loc.F, Record, Idx);
6640 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006641 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 return Context.getAttributedType(kind, modifiedType, equivalentType);
6643 }
6644
6645 case TYPE_PAREN: {
6646 if (Record.size() != 1) {
6647 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006648 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 }
6650 QualType InnerType = readType(*Loc.F, Record, Idx);
6651 return Context.getParenType(InnerType);
6652 }
6653
Leonard Chanc72aaf62019-05-07 03:20:17 +00006654 case TYPE_MACRO_QUALIFIED: {
6655 if (Record.size() != 2) {
6656 Error("incorrect encoding of macro defined type");
6657 return QualType();
6658 }
6659 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6660 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6661 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6662 }
6663
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 case TYPE_PACK_EXPANSION: {
6665 if (Record.size() != 2) {
6666 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006667 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 }
6669 QualType Pattern = readType(*Loc.F, Record, Idx);
6670 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006671 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006672 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 if (Record[1])
6674 NumExpansions = Record[1] - 1;
6675 return Context.getPackExpansionType(Pattern, NumExpansions);
6676 }
6677
6678 case TYPE_ELABORATED: {
6679 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006680 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6682 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006683 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6684 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 }
6686
6687 case TYPE_OBJC_INTERFACE: {
6688 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006689 ObjCInterfaceDecl *ItfD
6690 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6692 }
6693
Manman Rene6be26c2016-09-13 17:25:08 +00006694 case TYPE_OBJC_TYPE_PARAM: {
6695 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006696 ObjCTypeParamDecl *Decl
6697 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006698 unsigned NumProtos = Record[Idx++];
6699 SmallVector<ObjCProtocolDecl*, 4> Protos;
6700 for (unsigned I = 0; I != NumProtos; ++I)
6701 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6702 return Context.getObjCTypeParamType(Decl, Protos);
6703 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006704
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 case TYPE_OBJC_OBJECT: {
6706 unsigned Idx = 0;
6707 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006708 unsigned NumTypeArgs = Record[Idx++];
6709 SmallVector<QualType, 4> TypeArgs;
6710 for (unsigned I = 0; I != NumTypeArgs; ++I)
6711 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 unsigned NumProtos = Record[Idx++];
6713 SmallVector<ObjCProtocolDecl*, 4> Protos;
6714 for (unsigned I = 0; I != NumProtos; ++I)
6715 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006716 bool IsKindOf = Record[Idx++];
6717 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 }
6719
6720 case TYPE_OBJC_OBJECT_POINTER: {
6721 unsigned Idx = 0;
6722 QualType Pointee = readType(*Loc.F, Record, Idx);
6723 return Context.getObjCObjectPointerType(Pointee);
6724 }
6725
6726 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6727 unsigned Idx = 0;
6728 QualType Parm = readType(*Loc.F, Record, Idx);
6729 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006730 return Context.getSubstTemplateTypeParmType(
6731 cast<TemplateTypeParmType>(Parm),
6732 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 }
6734
6735 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6736 unsigned Idx = 0;
6737 QualType Parm = readType(*Loc.F, Record, Idx);
6738 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6739 return Context.getSubstTemplateTypeParmPackType(
6740 cast<TemplateTypeParmType>(Parm),
6741 ArgPack);
6742 }
6743
6744 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006745 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6747 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6748 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006749 const Type *T = nullptr;
6750 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6751 if (const Type *Existing = DI->getTypeForDecl()) {
6752 T = Existing;
6753 break;
6754 }
6755 }
6756 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006757 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006758 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6759 DI->setTypeForDecl(T);
6760 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006761 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 }
6763
6764 case TYPE_TEMPLATE_TYPE_PARM: {
6765 unsigned Idx = 0;
6766 unsigned Depth = Record[Idx++];
6767 unsigned Index = Record[Idx++];
6768 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006769 TemplateTypeParmDecl *D
6770 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6772 }
6773
6774 case TYPE_DEPENDENT_NAME: {
6775 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006776 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006778 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 QualType Canon = readType(*Loc.F, Record, Idx);
6780 if (!Canon.isNull())
6781 Canon = Context.getCanonicalType(Canon);
6782 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6783 }
6784
6785 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6786 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006787 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006789 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 unsigned NumArgs = Record[Idx++];
6791 SmallVector<TemplateArgument, 8> Args;
6792 Args.reserve(NumArgs);
6793 while (NumArgs--)
6794 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6795 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006796 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 }
6798
6799 case TYPE_DEPENDENT_SIZED_ARRAY: {
6800 unsigned Idx = 0;
6801
6802 // ArrayType
6803 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006804 ArrayType::ArraySizeModifier ASM
6805 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006806 unsigned IndexTypeQuals = Record[Idx++];
6807
6808 // DependentSizedArrayType
6809 Expr *NumElts = ReadExpr(*Loc.F);
6810 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6811
6812 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6813 IndexTypeQuals, Brackets);
6814 }
6815
6816 case TYPE_TEMPLATE_SPECIALIZATION: {
6817 unsigned Idx = 0;
6818 bool IsDependent = Record[Idx++];
6819 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6820 SmallVector<TemplateArgument, 8> Args;
6821 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6822 QualType Underlying = readType(*Loc.F, Record, Idx);
6823 QualType T;
6824 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006825 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006827 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006828 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6829 return T;
6830 }
6831
6832 case TYPE_ATOMIC: {
6833 if (Record.size() != 1) {
6834 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006835 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 }
6837 QualType ValueType = readType(*Loc.F, Record, Idx);
6838 return Context.getAtomicType(ValueType);
6839 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006840
Joey Goulye3c85de2016-12-01 11:30:49 +00006841 case TYPE_PIPE: {
6842 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006843 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006844 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006845 }
6846
6847 // Reading the pipe element type.
6848 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006849 unsigned ReadOnly = Record[1];
6850 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006851 }
6852
Erich Keanef702b022018-07-13 19:46:04 +00006853 case TYPE_DEPENDENT_SIZED_VECTOR: {
6854 unsigned Idx = 0;
6855 QualType ElementType = readType(*Loc.F, Record, Idx);
6856 Expr *SizeExpr = ReadExpr(*Loc.F);
6857 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6858 unsigned VecKind = Record[Idx];
6859
6860 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6861 (VectorType::VectorKind)VecKind);
6862 }
6863
Alex Lorenz00aee432017-03-22 10:04:48 +00006864 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6865 unsigned Idx = 0;
6866
6867 // DependentSizedExtVectorType
6868 QualType ElementType = readType(*Loc.F, Record, Idx);
6869 Expr *SizeExpr = ReadExpr(*Loc.F);
6870 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6871
6872 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6873 AttrLoc);
6874 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006875
6876 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6877 unsigned Idx = 0;
6878
6879 // DependentAddressSpaceType
6880 QualType PointeeType = readType(*Loc.F, Record, Idx);
6881 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6882 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6883
6884 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6885 AttrLoc);
6886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006887 }
6888 llvm_unreachable("Invalid TypeCode!");
6889}
6890
Richard Smith564417a2014-03-20 21:47:22 +00006891void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6892 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006893 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006894 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006895 ExceptionSpecificationType EST =
6896 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006897 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006898 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006899 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006900 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006901 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006902 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006903 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006904 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006905 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6906 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006907 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006908 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006909 }
6910}
6911
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006912namespace clang {
6913
6914class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006915 ModuleFile *F;
6916 ASTReader *Reader;
6917 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 unsigned &Idx;
6919
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006920 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006921 return Reader->ReadSourceLocation(*F, Record, Idx);
6922 }
6923
6924 TypeSourceInfo *GetTypeSourceInfo() {
6925 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6926 }
6927
6928 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6929 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 }
6931
Richard Smithe43e2b32018-08-20 21:47:29 +00006932 Attr *ReadAttr() {
6933 return Reader->ReadAttr(*F, Record, Idx);
6934 }
6935
Guy Benyei11169dd2012-12-18 14:30:41 +00006936public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006937 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006939 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006940
6941 // We want compile-time assurance that we've enumerated all of
6942 // these, so unfortunately we have to declare them first, then
6943 // define them out-of-line.
6944#define ABSTRACT_TYPELOC(CLASS, PARENT)
6945#define TYPELOC(CLASS, PARENT) \
6946 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6947#include "clang/AST/TypeLocNodes.def"
6948
6949 void VisitFunctionTypeLoc(FunctionTypeLoc);
6950 void VisitArrayTypeLoc(ArrayTypeLoc);
6951};
6952
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006953} // namespace clang
6954
Guy Benyei11169dd2012-12-18 14:30:41 +00006955void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6956 // nothing to do
6957}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006958
Guy Benyei11169dd2012-12-18 14:30:41 +00006959void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006960 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006962 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6963 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6964 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6965 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 }
6967}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006968
Guy Benyei11169dd2012-12-18 14:30:41 +00006969void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006970 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006971}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006972
Guy Benyei11169dd2012-12-18 14:30:41 +00006973void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006974 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006975}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006976
Reid Kleckner8a365022013-06-24 17:51:48 +00006977void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6978 // nothing to do
6979}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006980
Reid Kleckner0503a872013-12-05 01:23:43 +00006981void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6982 // nothing to do
6983}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006984
Leonard Chanc72aaf62019-05-07 03:20:17 +00006985void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6986 TL.setExpansionLoc(ReadSourceLocation());
6987}
6988
Guy Benyei11169dd2012-12-18 14:30:41 +00006989void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006990 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006991}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006992
Guy Benyei11169dd2012-12-18 14:30:41 +00006993void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006994 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006995}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006996
Guy Benyei11169dd2012-12-18 14:30:41 +00006997void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006998 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006999}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007000
Guy Benyei11169dd2012-12-18 14:30:41 +00007001void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007002 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007003 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007004}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007005
Guy Benyei11169dd2012-12-18 14:30:41 +00007006void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007007 TL.setLBracketLoc(ReadSourceLocation());
7008 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007009 if (Record[Idx++])
7010 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 else
Craig Toppera13603a2014-05-22 05:54:18 +00007012 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007013}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007014
Guy Benyei11169dd2012-12-18 14:30:41 +00007015void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7016 VisitArrayTypeLoc(TL);
7017}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007018
Guy Benyei11169dd2012-12-18 14:30:41 +00007019void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7020 VisitArrayTypeLoc(TL);
7021}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007022
Guy Benyei11169dd2012-12-18 14:30:41 +00007023void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7024 VisitArrayTypeLoc(TL);
7025}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007026
Guy Benyei11169dd2012-12-18 14:30:41 +00007027void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7028 DependentSizedArrayTypeLoc TL) {
7029 VisitArrayTypeLoc(TL);
7030}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007031
Andrew Gozillon572bbb02017-10-02 06:25:51 +00007032void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7033 DependentAddressSpaceTypeLoc TL) {
7034
7035 TL.setAttrNameLoc(ReadSourceLocation());
7036 SourceRange range;
7037 range.setBegin(ReadSourceLocation());
7038 range.setEnd(ReadSourceLocation());
7039 TL.setAttrOperandParensRange(range);
7040 TL.setAttrExprOperand(Reader->ReadExpr(*F));
7041}
7042
Guy Benyei11169dd2012-12-18 14:30:41 +00007043void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7044 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007045 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007046}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007047
Guy Benyei11169dd2012-12-18 14:30:41 +00007048void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007049 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007050}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007051
Erich Keanef702b022018-07-13 19:46:04 +00007052void TypeLocReader::VisitDependentVectorTypeLoc(
7053 DependentVectorTypeLoc TL) {
7054 TL.setNameLoc(ReadSourceLocation());
7055}
7056
Guy Benyei11169dd2012-12-18 14:30:41 +00007057void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007058 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007059}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007060
Guy Benyei11169dd2012-12-18 14:30:41 +00007061void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007062 TL.setLocalRangeBegin(ReadSourceLocation());
7063 TL.setLParenLoc(ReadSourceLocation());
7064 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00007065 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
7066 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007067 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007068 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007069 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 }
7071}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007072
Guy Benyei11169dd2012-12-18 14:30:41 +00007073void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7074 VisitFunctionTypeLoc(TL);
7075}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007076
Guy Benyei11169dd2012-12-18 14:30:41 +00007077void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7078 VisitFunctionTypeLoc(TL);
7079}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007080
Guy Benyei11169dd2012-12-18 14:30:41 +00007081void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007082 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007083}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007084
Guy Benyei11169dd2012-12-18 14:30:41 +00007085void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007086 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007087}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007088
Guy Benyei11169dd2012-12-18 14:30:41 +00007089void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007090 TL.setTypeofLoc(ReadSourceLocation());
7091 TL.setLParenLoc(ReadSourceLocation());
7092 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007093}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007094
Guy Benyei11169dd2012-12-18 14:30:41 +00007095void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007096 TL.setTypeofLoc(ReadSourceLocation());
7097 TL.setLParenLoc(ReadSourceLocation());
7098 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007099 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007100}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007101
Guy Benyei11169dd2012-12-18 14:30:41 +00007102void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007103 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007104}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007105
Guy Benyei11169dd2012-12-18 14:30:41 +00007106void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007107 TL.setKWLoc(ReadSourceLocation());
7108 TL.setLParenLoc(ReadSourceLocation());
7109 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007110 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007111}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007112
Guy Benyei11169dd2012-12-18 14:30:41 +00007113void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007114 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007115}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007116
Richard Smith600b5262017-01-26 20:40:47 +00007117void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7118 DeducedTemplateSpecializationTypeLoc TL) {
7119 TL.setTemplateNameLoc(ReadSourceLocation());
7120}
7121
Guy Benyei11169dd2012-12-18 14:30:41 +00007122void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007123 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007124}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007125
Guy Benyei11169dd2012-12-18 14:30:41 +00007126void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007127 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007128}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007129
Guy Benyei11169dd2012-12-18 14:30:41 +00007130void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00007131 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00007132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007133
Guy Benyei11169dd2012-12-18 14:30:41 +00007134void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007135 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007136}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007137
Guy Benyei11169dd2012-12-18 14:30:41 +00007138void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7139 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007140 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007141}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7144 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007145 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007146}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007147
Guy Benyei11169dd2012-12-18 14:30:41 +00007148void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7149 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007150 TL.setTemplateKeywordLoc(ReadSourceLocation());
7151 TL.setTemplateNameLoc(ReadSourceLocation());
7152 TL.setLAngleLoc(ReadSourceLocation());
7153 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007155 TL.setArgLocInfo(
7156 i,
7157 Reader->GetTemplateArgumentLocInfo(
7158 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007159}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007162 TL.setLParenLoc(ReadSourceLocation());
7163 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007165
Guy Benyei11169dd2012-12-18 14:30:41 +00007166void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007167 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007168 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007169}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007170
Guy Benyei11169dd2012-12-18 14:30:41 +00007171void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007172 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007173}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007174
Guy Benyei11169dd2012-12-18 14:30:41 +00007175void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007176 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007177 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007178 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007179}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007180
Guy Benyei11169dd2012-12-18 14:30:41 +00007181void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7182 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007183 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007184 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007185 TL.setTemplateKeywordLoc(ReadSourceLocation());
7186 TL.setTemplateNameLoc(ReadSourceLocation());
7187 TL.setLAngleLoc(ReadSourceLocation());
7188 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007189 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007190 TL.setArgLocInfo(
7191 I,
7192 Reader->GetTemplateArgumentLocInfo(
7193 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007194}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007195
Guy Benyei11169dd2012-12-18 14:30:41 +00007196void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007197 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007198}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007199
Guy Benyei11169dd2012-12-18 14:30:41 +00007200void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007201 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007202}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007203
Manman Rene6be26c2016-09-13 17:25:08 +00007204void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7205 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007206 TL.setProtocolLAngleLoc(ReadSourceLocation());
7207 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007208 }
7209 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007210 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007211}
7212
Guy Benyei11169dd2012-12-18 14:30:41 +00007213void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007214 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007215 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
7216 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00007217 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007218 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007219 TL.setProtocolLAngleLoc(ReadSourceLocation());
7220 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007221 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007222 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007223}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007224
Guy Benyei11169dd2012-12-18 14:30:41 +00007225void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007226 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007227}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007228
Guy Benyei11169dd2012-12-18 14:30:41 +00007229void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007230 TL.setKWLoc(ReadSourceLocation());
7231 TL.setLParenLoc(ReadSourceLocation());
7232 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007233}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007234
Xiuli Pan9c14e282016-01-09 12:53:17 +00007235void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007236 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00007237}
Guy Benyei11169dd2012-12-18 14:30:41 +00007238
Richard Smithc23d7342018-06-29 20:46:25 +00007239void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
7240 unsigned &Idx, TypeLoc TL) {
7241 TypeLocReader TLR(F, *this, Record, Idx);
7242 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7243 TLR.Visit(TL);
7244}
7245
David L. Jonesbe1557a2016-12-21 00:17:49 +00007246TypeSourceInfo *
7247ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
7248 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 QualType InfoTy = readType(F, Record, Idx);
7250 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00007251 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007252
7253 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00007254 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 return TInfo;
7256}
7257
7258QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007259 assert(ContextObj && "reading type with no AST context");
7260 ASTContext &Context = *ContextObj;
7261
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 unsigned FastQuals = ID & Qualifiers::FastMask;
7263 unsigned Index = ID >> Qualifiers::FastWidth;
7264
7265 if (Index < NUM_PREDEF_TYPE_IDS) {
7266 QualType T;
7267 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00007268 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00007269 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00007270 case PREDEF_TYPE_VOID_ID:
7271 T = Context.VoidTy;
7272 break;
7273 case PREDEF_TYPE_BOOL_ID:
7274 T = Context.BoolTy;
7275 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 case PREDEF_TYPE_CHAR_U_ID:
7277 case PREDEF_TYPE_CHAR_S_ID:
7278 // FIXME: Check that the signedness of CharTy is correct!
7279 T = Context.CharTy;
7280 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007281 case PREDEF_TYPE_UCHAR_ID:
7282 T = Context.UnsignedCharTy;
7283 break;
7284 case PREDEF_TYPE_USHORT_ID:
7285 T = Context.UnsignedShortTy;
7286 break;
7287 case PREDEF_TYPE_UINT_ID:
7288 T = Context.UnsignedIntTy;
7289 break;
7290 case PREDEF_TYPE_ULONG_ID:
7291 T = Context.UnsignedLongTy;
7292 break;
7293 case PREDEF_TYPE_ULONGLONG_ID:
7294 T = Context.UnsignedLongLongTy;
7295 break;
7296 case PREDEF_TYPE_UINT128_ID:
7297 T = Context.UnsignedInt128Ty;
7298 break;
7299 case PREDEF_TYPE_SCHAR_ID:
7300 T = Context.SignedCharTy;
7301 break;
7302 case PREDEF_TYPE_WCHAR_ID:
7303 T = Context.WCharTy;
7304 break;
7305 case PREDEF_TYPE_SHORT_ID:
7306 T = Context.ShortTy;
7307 break;
7308 case PREDEF_TYPE_INT_ID:
7309 T = Context.IntTy;
7310 break;
7311 case PREDEF_TYPE_LONG_ID:
7312 T = Context.LongTy;
7313 break;
7314 case PREDEF_TYPE_LONGLONG_ID:
7315 T = Context.LongLongTy;
7316 break;
7317 case PREDEF_TYPE_INT128_ID:
7318 T = Context.Int128Ty;
7319 break;
7320 case PREDEF_TYPE_HALF_ID:
7321 T = Context.HalfTy;
7322 break;
7323 case PREDEF_TYPE_FLOAT_ID:
7324 T = Context.FloatTy;
7325 break;
7326 case PREDEF_TYPE_DOUBLE_ID:
7327 T = Context.DoubleTy;
7328 break;
7329 case PREDEF_TYPE_LONGDOUBLE_ID:
7330 T = Context.LongDoubleTy;
7331 break;
Leonard Chanf921d852018-06-04 16:07:52 +00007332 case PREDEF_TYPE_SHORT_ACCUM_ID:
7333 T = Context.ShortAccumTy;
7334 break;
7335 case PREDEF_TYPE_ACCUM_ID:
7336 T = Context.AccumTy;
7337 break;
7338 case PREDEF_TYPE_LONG_ACCUM_ID:
7339 T = Context.LongAccumTy;
7340 break;
7341 case PREDEF_TYPE_USHORT_ACCUM_ID:
7342 T = Context.UnsignedShortAccumTy;
7343 break;
7344 case PREDEF_TYPE_UACCUM_ID:
7345 T = Context.UnsignedAccumTy;
7346 break;
7347 case PREDEF_TYPE_ULONG_ACCUM_ID:
7348 T = Context.UnsignedLongAccumTy;
7349 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00007350 case PREDEF_TYPE_SHORT_FRACT_ID:
7351 T = Context.ShortFractTy;
7352 break;
7353 case PREDEF_TYPE_FRACT_ID:
7354 T = Context.FractTy;
7355 break;
7356 case PREDEF_TYPE_LONG_FRACT_ID:
7357 T = Context.LongFractTy;
7358 break;
7359 case PREDEF_TYPE_USHORT_FRACT_ID:
7360 T = Context.UnsignedShortFractTy;
7361 break;
7362 case PREDEF_TYPE_UFRACT_ID:
7363 T = Context.UnsignedFractTy;
7364 break;
7365 case PREDEF_TYPE_ULONG_FRACT_ID:
7366 T = Context.UnsignedLongFractTy;
7367 break;
7368 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7369 T = Context.SatShortAccumTy;
7370 break;
7371 case PREDEF_TYPE_SAT_ACCUM_ID:
7372 T = Context.SatAccumTy;
7373 break;
7374 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7375 T = Context.SatLongAccumTy;
7376 break;
7377 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7378 T = Context.SatUnsignedShortAccumTy;
7379 break;
7380 case PREDEF_TYPE_SAT_UACCUM_ID:
7381 T = Context.SatUnsignedAccumTy;
7382 break;
7383 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7384 T = Context.SatUnsignedLongAccumTy;
7385 break;
7386 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7387 T = Context.SatShortFractTy;
7388 break;
7389 case PREDEF_TYPE_SAT_FRACT_ID:
7390 T = Context.SatFractTy;
7391 break;
7392 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7393 T = Context.SatLongFractTy;
7394 break;
7395 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7396 T = Context.SatUnsignedShortFractTy;
7397 break;
7398 case PREDEF_TYPE_SAT_UFRACT_ID:
7399 T = Context.SatUnsignedFractTy;
7400 break;
7401 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7402 T = Context.SatUnsignedLongFractTy;
7403 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00007404 case PREDEF_TYPE_FLOAT16_ID:
7405 T = Context.Float16Ty;
7406 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007407 case PREDEF_TYPE_FLOAT128_ID:
7408 T = Context.Float128Ty;
7409 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007410 case PREDEF_TYPE_OVERLOAD_ID:
7411 T = Context.OverloadTy;
7412 break;
7413 case PREDEF_TYPE_BOUND_MEMBER:
7414 T = Context.BoundMemberTy;
7415 break;
7416 case PREDEF_TYPE_PSEUDO_OBJECT:
7417 T = Context.PseudoObjectTy;
7418 break;
7419 case PREDEF_TYPE_DEPENDENT_ID:
7420 T = Context.DependentTy;
7421 break;
7422 case PREDEF_TYPE_UNKNOWN_ANY:
7423 T = Context.UnknownAnyTy;
7424 break;
7425 case PREDEF_TYPE_NULLPTR_ID:
7426 T = Context.NullPtrTy;
7427 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007428 case PREDEF_TYPE_CHAR8_ID:
7429 T = Context.Char8Ty;
7430 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007431 case PREDEF_TYPE_CHAR16_ID:
7432 T = Context.Char16Ty;
7433 break;
7434 case PREDEF_TYPE_CHAR32_ID:
7435 T = Context.Char32Ty;
7436 break;
7437 case PREDEF_TYPE_OBJC_ID:
7438 T = Context.ObjCBuiltinIdTy;
7439 break;
7440 case PREDEF_TYPE_OBJC_CLASS:
7441 T = Context.ObjCBuiltinClassTy;
7442 break;
7443 case PREDEF_TYPE_OBJC_SEL:
7444 T = Context.ObjCBuiltinSelTy;
7445 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007446#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7447 case PREDEF_TYPE_##Id##_ID: \
7448 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007449 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007450#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007451#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7452 case PREDEF_TYPE_##Id##_ID: \
7453 T = Context.Id##Ty; \
7454 break;
7455#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007456 case PREDEF_TYPE_SAMPLER_ID:
7457 T = Context.OCLSamplerTy;
7458 break;
7459 case PREDEF_TYPE_EVENT_ID:
7460 T = Context.OCLEventTy;
7461 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007462 case PREDEF_TYPE_CLK_EVENT_ID:
7463 T = Context.OCLClkEventTy;
7464 break;
7465 case PREDEF_TYPE_QUEUE_ID:
7466 T = Context.OCLQueueTy;
7467 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007468 case PREDEF_TYPE_RESERVE_ID_ID:
7469 T = Context.OCLReserveIDTy;
7470 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007471 case PREDEF_TYPE_AUTO_DEDUCT:
7472 T = Context.getAutoDeductType();
7473 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007474 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7475 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7478 T = Context.ARCUnbridgedCastTy;
7479 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 case PREDEF_TYPE_BUILTIN_FN:
7481 T = Context.BuiltinFnTy;
7482 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007483 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7484 T = Context.OMPArraySectionTy;
7485 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00007486#define SVE_TYPE(Name, Id, SingletonId) \
7487 case PREDEF_TYPE_##Id##_ID: \
7488 T = Context.SingletonId; \
7489 break;
7490#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00007491 }
7492
7493 assert(!T.isNull() && "Unknown predefined type");
7494 return T.withFastQualifiers(FastQuals);
7495 }
7496
7497 Index -= NUM_PREDEF_TYPE_IDS;
7498 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7499 if (TypesLoaded[Index].isNull()) {
7500 TypesLoaded[Index] = readTypeRecord(Index);
7501 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007502 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007503
7504 TypesLoaded[Index]->setFromAST();
7505 if (DeserializationListener)
7506 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7507 TypesLoaded[Index]);
7508 }
7509
7510 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7511}
7512
7513QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7514 return GetType(getGlobalTypeID(F, LocalID));
7515}
7516
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007517serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007518ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7519 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7520 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007521
Guy Benyei11169dd2012-12-18 14:30:41 +00007522 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7523 return LocalID;
7524
Richard Smith37a93df2017-02-18 00:32:02 +00007525 if (!F.ModuleOffsetMap.empty())
7526 ReadModuleOffsetMap(F);
7527
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7529 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7530 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007531
Guy Benyei11169dd2012-12-18 14:30:41 +00007532 unsigned GlobalIndex = LocalIndex + I->second;
7533 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7534}
7535
7536TemplateArgumentLocInfo
7537ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7538 TemplateArgument::ArgKind Kind,
7539 const RecordData &Record,
7540 unsigned &Index) {
7541 switch (Kind) {
7542 case TemplateArgument::Expression:
7543 return ReadExpr(F);
7544 case TemplateArgument::Type:
7545 return GetTypeSourceInfo(F, Record, Index);
7546 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007547 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 Index);
7549 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7550 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7551 SourceLocation());
7552 }
7553 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007554 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 Index);
7556 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7557 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007558 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007559 EllipsisLoc);
7560 }
7561 case TemplateArgument::Null:
7562 case TemplateArgument::Integral:
7563 case TemplateArgument::Declaration:
7564 case TemplateArgument::NullPtr:
7565 case TemplateArgument::Pack:
7566 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007567 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007568 }
7569 llvm_unreachable("unexpected template argument loc");
7570}
7571
7572TemplateArgumentLoc
7573ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7574 const RecordData &Record, unsigned &Index) {
7575 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7576
7577 if (Arg.getKind() == TemplateArgument::Expression) {
7578 if (Record[Index++]) // bool InfoHasSameExpr.
7579 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7580 }
7581 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7582 Record, Index));
7583}
7584
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007585const ASTTemplateArgumentListInfo*
7586ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7587 const RecordData &Record,
7588 unsigned &Index) {
7589 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7590 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7591 unsigned NumArgsAsWritten = Record[Index++];
7592 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7593 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7594 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7595 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7596}
7597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7599 return GetDecl(ID);
7600}
7601
Richard Smith053f6c62014-05-16 23:01:30 +00007602void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007603 if (NumCurrentElementsDeserializing) {
7604 // We arrange to not care about the complete redeclaration chain while we're
7605 // deserializing. Just remember that the AST has marked this one as complete
7606 // but that it's not actually complete yet, so we know we still need to
7607 // complete it later.
7608 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7609 return;
7610 }
7611
Richard Smith053f6c62014-05-16 23:01:30 +00007612 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7613
Richard Smith053f6c62014-05-16 23:01:30 +00007614 // If this is a named declaration, complete it by looking it up
7615 // within its context.
7616 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007617 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007618 // all mergeable entities within it.
7619 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7620 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7621 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007622 if (!getContext().getLangOpts().CPlusPlus &&
7623 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007624 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007625 // the identifier instead. (For C++ modules, we don't store decls
7626 // in the serialized identifier table, so we do the lookup in the TU.)
7627 auto *II = Name.getAsIdentifierInfo();
7628 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007629 if (II->isOutOfDate())
7630 updateOutOfDateIdentifier(*II);
7631 } else
7632 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007633 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007634 // Find all declarations of this kind from the relevant context.
7635 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7636 auto *DC = cast<DeclContext>(DCDecl);
7637 SmallVector<Decl*, 8> Decls;
7638 FindExternalLexicalDecls(
7639 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7640 }
Richard Smith053f6c62014-05-16 23:01:30 +00007641 }
7642 }
Richard Smith50895422015-01-31 03:04:55 +00007643
7644 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7645 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7646 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7647 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7648 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7649 if (auto *Template = FD->getPrimaryTemplate())
7650 Template->LoadLazySpecializations();
7651 }
Richard Smith053f6c62014-05-16 23:01:30 +00007652}
7653
Richard Smithc2bb8182015-03-24 06:36:48 +00007654CXXCtorInitializer **
7655ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7656 RecordLocation Loc = getLocalBitOffset(Offset);
7657 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7658 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007659 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7660 Error(std::move(Err));
7661 return nullptr;
7662 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007663 ReadingKindTracker ReadingKind(Read_Decl, *this);
7664
7665 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007666 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7667 if (!MaybeCode) {
7668 Error(MaybeCode.takeError());
7669 return nullptr;
7670 }
7671 unsigned Code = MaybeCode.get();
7672
7673 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7674 if (!MaybeRecCode) {
7675 Error(MaybeRecCode.takeError());
7676 return nullptr;
7677 }
7678 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007679 Error("malformed AST file: missing C++ ctor initializers");
7680 return nullptr;
7681 }
7682
7683 unsigned Idx = 0;
7684 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7685}
7686
Guy Benyei11169dd2012-12-18 14:30:41 +00007687CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007688 assert(ContextObj && "reading base specifiers with no AST context");
7689 ASTContext &Context = *ContextObj;
7690
Guy Benyei11169dd2012-12-18 14:30:41 +00007691 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007692 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007694 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7695 Error(std::move(Err));
7696 return nullptr;
7697 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007698 ReadingKindTracker ReadingKind(Read_Decl, *this);
7699 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007700
7701 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7702 if (!MaybeCode) {
7703 Error(MaybeCode.takeError());
7704 return nullptr;
7705 }
7706 unsigned Code = MaybeCode.get();
7707
7708 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7709 if (!MaybeRecCode) {
7710 Error(MaybeCode.takeError());
7711 return nullptr;
7712 }
7713 unsigned RecCode = MaybeRecCode.get();
7714
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007716 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007717 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 }
7719
7720 unsigned Idx = 0;
7721 unsigned NumBases = Record[Idx++];
7722 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007723 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 for (unsigned I = 0; I != NumBases; ++I)
7725 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7726 return Bases;
7727}
7728
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007729serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007730ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7731 if (LocalID < NUM_PREDEF_DECL_IDS)
7732 return LocalID;
7733
Richard Smith37a93df2017-02-18 00:32:02 +00007734 if (!F.ModuleOffsetMap.empty())
7735 ReadModuleOffsetMap(F);
7736
Guy Benyei11169dd2012-12-18 14:30:41 +00007737 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7738 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7739 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007740
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 return LocalID + I->second;
7742}
7743
7744bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7745 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007746 // Predefined decls aren't from any module.
7747 if (ID < NUM_PREDEF_DECL_IDS)
7748 return false;
7749
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007750 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007751 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752}
7753
Douglas Gregor9f782892013-01-21 15:25:38 +00007754ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007756 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7758 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7759 return I->second;
7760}
7761
7762SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7763 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007764 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007765
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7767
7768 if (Index > DeclsLoaded.size()) {
7769 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007770 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007772
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 if (Decl *D = DeclsLoaded[Index])
7774 return D->getLocation();
7775
Richard Smithcb34bd32016-03-27 07:28:06 +00007776 SourceLocation Loc;
7777 DeclCursorForID(ID, Loc);
7778 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007779}
7780
Richard Smithfe620d22015-03-05 23:24:12 +00007781static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7782 switch (ID) {
7783 case PREDEF_DECL_NULL_ID:
7784 return nullptr;
7785
7786 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7787 return Context.getTranslationUnitDecl();
7788
7789 case PREDEF_DECL_OBJC_ID_ID:
7790 return Context.getObjCIdDecl();
7791
7792 case PREDEF_DECL_OBJC_SEL_ID:
7793 return Context.getObjCSelDecl();
7794
7795 case PREDEF_DECL_OBJC_CLASS_ID:
7796 return Context.getObjCClassDecl();
7797
7798 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7799 return Context.getObjCProtocolDecl();
7800
7801 case PREDEF_DECL_INT_128_ID:
7802 return Context.getInt128Decl();
7803
7804 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7805 return Context.getUInt128Decl();
7806
7807 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7808 return Context.getObjCInstanceTypeDecl();
7809
7810 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7811 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007812
Richard Smith9b88a4c2015-07-27 05:40:23 +00007813 case PREDEF_DECL_VA_LIST_TAG:
7814 return Context.getVaListTagDecl();
7815
Charles Davisc7d5c942015-09-17 20:55:33 +00007816 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7817 return Context.getBuiltinMSVaListDecl();
7818
Richard Smithf19e1272015-03-07 00:04:49 +00007819 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7820 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007821
7822 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7823 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007824
7825 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7826 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007827
7828 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7829 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007830
7831 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7832 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007833 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007834 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007835}
7836
Richard Smithcd45dbc2014-04-19 03:48:30 +00007837Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007838 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007839 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007840 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007841 if (D) {
7842 // Track that we have merged the declaration with ID \p ID into the
7843 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007844 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007845 if (Merged.empty())
7846 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 }
Richard Smithfe620d22015-03-05 23:24:12 +00007848 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007850
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7852
7853 if (Index >= DeclsLoaded.size()) {
7854 assert(0 && "declaration ID out-of-range for AST file");
7855 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007856 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007858
7859 return DeclsLoaded[Index];
7860}
7861
7862Decl *ASTReader::GetDecl(DeclID ID) {
7863 if (ID < NUM_PREDEF_DECL_IDS)
7864 return GetExistingDecl(ID);
7865
7866 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7867
7868 if (Index >= DeclsLoaded.size()) {
7869 assert(0 && "declaration ID out-of-range for AST file");
7870 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007871 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007872 }
7873
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 if (!DeclsLoaded[Index]) {
7875 ReadDeclRecord(ID);
7876 if (DeserializationListener)
7877 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7878 }
7879
7880 return DeclsLoaded[Index];
7881}
7882
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007883DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 DeclID GlobalID) {
7885 if (GlobalID < NUM_PREDEF_DECL_IDS)
7886 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007887
Guy Benyei11169dd2012-12-18 14:30:41 +00007888 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7889 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7890 ModuleFile *Owner = I->second;
7891
7892 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7893 = M.GlobalToLocalDeclIDs.find(Owner);
7894 if (Pos == M.GlobalToLocalDeclIDs.end())
7895 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007896
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 return GlobalID - Owner->BaseDeclID + Pos->second;
7898}
7899
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007900serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007901 const RecordData &Record,
7902 unsigned &Idx) {
7903 if (Idx >= Record.size()) {
7904 Error("Corrupted AST file");
7905 return 0;
7906 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007907
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 return getGlobalDeclID(F, Record[Idx++]);
7909}
7910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007911/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007912///
7913/// This operation will read a new statement from the external
7914/// source each time it is called, and is meant to be used via a
7915/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7916Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7917 // Switch case IDs are per Decl.
7918 ClearSwitchCaseIDs();
7919
7920 // Offset here is a global offset across the entire chain.
7921 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007922 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7923 Error(std::move(Err));
7924 return nullptr;
7925 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007926 assert(NumCurrentElementsDeserializing == 0 &&
7927 "should not be called while already deserializing");
7928 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 return ReadStmtFromStream(*Loc.F);
7930}
7931
Richard Smith3cb15722015-08-05 22:41:45 +00007932void ASTReader::FindExternalLexicalDecls(
7933 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7934 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007935 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7936
Richard Smith9ccdd932015-08-06 22:14:12 +00007937 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007938 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7939 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7940 auto K = (Decl::Kind)+LexicalDecls[I];
7941 if (!IsKindWeWant(K))
7942 continue;
7943
7944 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7945
7946 // Don't add predefined declarations to the lexical context more
7947 // than once.
7948 if (ID < NUM_PREDEF_DECL_IDS) {
7949 if (PredefsVisited[ID])
7950 continue;
7951
7952 PredefsVisited[ID] = true;
7953 }
7954
7955 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007956 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007957 if (!DC->isDeclInLexicalTraversal(D))
7958 Decls.push_back(D);
7959 }
7960 }
7961 };
7962
7963 if (isa<TranslationUnitDecl>(DC)) {
7964 for (auto Lexical : TULexicalDecls)
7965 Visit(Lexical.first, Lexical.second);
7966 } else {
7967 auto I = LexicalDecls.find(DC);
7968 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007969 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007970 }
7971
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007973}
7974
7975namespace {
7976
7977class DeclIDComp {
7978 ASTReader &Reader;
7979 ModuleFile &Mod;
7980
7981public:
7982 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7983
7984 bool operator()(LocalDeclID L, LocalDeclID R) const {
7985 SourceLocation LHS = getLocation(L);
7986 SourceLocation RHS = getLocation(R);
7987 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7988 }
7989
7990 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7991 SourceLocation RHS = getLocation(R);
7992 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7993 }
7994
7995 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7996 SourceLocation LHS = getLocation(L);
7997 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7998 }
7999
8000 SourceLocation getLocation(LocalDeclID ID) const {
8001 return Reader.getSourceManager().getFileLoc(
8002 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
8003 }
8004};
8005
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008006} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00008007
8008void ASTReader::FindFileRegionDecls(FileID File,
8009 unsigned Offset, unsigned Length,
8010 SmallVectorImpl<Decl *> &Decls) {
8011 SourceManager &SM = getSourceManager();
8012
8013 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8014 if (I == FileDeclIDs.end())
8015 return;
8016
8017 FileDeclsInfo &DInfo = I->second;
8018 if (DInfo.Decls.empty())
8019 return;
8020
8021 SourceLocation
8022 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8023 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8024
8025 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00008026 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
8027 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 if (BeginIt != DInfo.Decls.begin())
8029 --BeginIt;
8030
8031 // If we are pointing at a top-level decl inside an objc container, we need
8032 // to backtrack until we find it otherwise we will fail to report that the
8033 // region overlaps with an objc container.
8034 while (BeginIt != DInfo.Decls.begin() &&
8035 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
8036 ->isTopLevelDeclInObjCContainer())
8037 --BeginIt;
8038
Fangrui Song7264a472019-07-03 08:13:17 +00008039 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
8040 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 if (EndIt != DInfo.Decls.end())
8042 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008043
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 for (ArrayRef<serialization::LocalDeclID>::iterator
8045 DIt = BeginIt; DIt != EndIt; ++DIt)
8046 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
8047}
8048
Richard Smith9ce12e32013-02-07 03:30:24 +00008049bool
Guy Benyei11169dd2012-12-18 14:30:41 +00008050ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
8051 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00008052 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 "DeclContext has no visible decls in storage");
8054 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00008055 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00008056
Richard Smithd88a7f12015-09-01 20:35:42 +00008057 auto It = Lookups.find(DC);
8058 if (It == Lookups.end())
8059 return false;
8060
Richard Smith8c913ec2014-08-14 02:21:01 +00008061 Deserializing LookupResults(this);
8062
Richard Smithd88a7f12015-09-01 20:35:42 +00008063 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008065 for (DeclID ID : It->second.Table.find(Name)) {
8066 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008067 if (ND->getDeclName() == Name)
8068 Decls.push_back(ND);
8069 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008070
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 ++NumVisibleDeclContextsRead;
8072 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00008073 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008074}
8075
Guy Benyei11169dd2012-12-18 14:30:41 +00008076void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8077 if (!DC->hasExternalVisibleStorage())
8078 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00008079
8080 auto It = Lookups.find(DC);
8081 assert(It != Lookups.end() &&
8082 "have external visible storage but no lookup tables");
8083
Craig Topper79be4cd2013-07-05 04:33:53 +00008084 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00008085
Vedant Kumar48b4f762018-04-14 01:40:48 +00008086 for (DeclID ID : It->second.Table.findAll()) {
8087 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008088 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 }
8090
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 ++NumVisibleDeclContextsRead;
8092
Vedant Kumar48b4f762018-04-14 01:40:48 +00008093 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8094 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8095 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008096 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8097}
8098
Richard Smithd88a7f12015-09-01 20:35:42 +00008099const serialization::reader::DeclContextLookupTable *
8100ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8101 auto I = Lookups.find(Primary);
8102 return I == Lookups.end() ? nullptr : &I->second;
8103}
8104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008105/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00008106/// before receiving the implementation, and codegen depends on this.
8107/// We simulate this by deserializing and passing to consumer the methods of the
8108/// implementation before passing the deserialized implementation decl.
8109static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8110 ASTConsumer *Consumer) {
8111 assert(ImplD && Consumer);
8112
Aaron Ballmanaff18c02014-03-13 19:03:34 +00008113 for (auto *I : ImplD->methods())
8114 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00008115
8116 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8117}
8118
Guy Benyei11169dd2012-12-18 14:30:41 +00008119void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008120 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 PassObjCImplDeclToConsumer(ImplD, Consumer);
8122 else
8123 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8124}
8125
8126void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8127 this->Consumer = Consumer;
8128
Richard Smith9e2341d2015-03-23 03:25:59 +00008129 if (Consumer)
8130 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00008131
8132 if (DeserializationListener)
8133 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00008134}
8135
8136void ASTReader::PrintStats() {
8137 std::fprintf(stderr, "*** AST File Statistics:\n");
8138
8139 unsigned NumTypesLoaded
8140 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
8141 QualType());
8142 unsigned NumDeclsLoaded
8143 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008144 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 unsigned NumIdentifiersLoaded
8146 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
8147 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008148 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 unsigned NumMacrosLoaded
8150 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
8151 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008152 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 unsigned NumSelectorsLoaded
8154 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
8155 SelectorsLoaded.end(),
8156 Selector());
8157
8158 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8159 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8160 NumSLocEntriesRead, TotalNumSLocEntries,
8161 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8162 if (!TypesLoaded.empty())
8163 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8164 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8165 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8166 if (!DeclsLoaded.empty())
8167 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8168 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8169 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8170 if (!IdentifiersLoaded.empty())
8171 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8172 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8173 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8174 if (!MacrosLoaded.empty())
8175 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8176 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8177 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8178 if (!SelectorsLoaded.empty())
8179 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8180 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8181 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8182 if (TotalNumStatements)
8183 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8184 NumStatementsRead, TotalNumStatements,
8185 ((float)NumStatementsRead/TotalNumStatements * 100));
8186 if (TotalNumMacros)
8187 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8188 NumMacrosRead, TotalNumMacros,
8189 ((float)NumMacrosRead/TotalNumMacros * 100));
8190 if (TotalLexicalDeclContexts)
8191 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8192 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8193 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8194 * 100));
8195 if (TotalVisibleDeclContexts)
8196 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8197 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8198 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8199 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008200 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8202 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8203 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8204 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008205 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008206 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8207 NumMethodPoolHits, NumMethodPoolLookups,
8208 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008209 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008210 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8211 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8212 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8213 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008214 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00008215 std::fprintf(stderr,
8216 " %u / %u identifier table lookups succeeded (%f%%)\n",
8217 NumIdentifierLookupHits, NumIdentifierLookups,
8218 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00008219
Douglas Gregore060e572013-01-25 01:03:03 +00008220 if (GlobalIndex) {
8221 std::fprintf(stderr, "\n");
8222 GlobalIndex->printStats();
8223 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008224
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 std::fprintf(stderr, "\n");
8226 dump();
8227 std::fprintf(stderr, "\n");
8228}
8229
8230template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00008231LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00008232dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008233 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 InitialCapacity> &Map) {
8235 if (Map.begin() == Map.end())
8236 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008237
Vedant Kumar48b4f762018-04-14 01:40:48 +00008238 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8239
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008241 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8242 I != IEnd; ++I) {
8243 llvm::errs() << " " << I->first << " -> " << I->second->FileName
8244 << "\n";
8245 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008246}
8247
Yaron Kerencdae9412016-01-29 19:38:18 +00008248LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8250 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8251 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8252 dumpModuleIDMap("Global type map", GlobalTypeMap);
8253 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8254 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8255 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8256 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8257 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008258 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008260
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008262 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00008263 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00008264}
8265
8266/// Return the amount of memory used by memory buffers, breaking down
8267/// by heap-backed versus mmap'ed memory.
8268void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008269 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00008270 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 size_t bytes = buf->getBufferSize();
8272 switch (buf->getBufferKind()) {
8273 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8274 sizes.malloc_bytes += bytes;
8275 break;
8276 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8277 sizes.mmap_bytes += bytes;
8278 break;
8279 }
8280 }
8281 }
8282}
8283
8284void ASTReader::InitializeSema(Sema &S) {
8285 SemaObj = &S;
8286 S.addExternalSource(this);
8287
8288 // Makes sure any declarations that were deserialized "too early"
8289 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008290 for (uint64_t ID : PreloadedDeclIDs) {
8291 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00008292 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008294 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008295
Richard Smith3d8e97e2013-10-18 06:54:39 +00008296 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 if (!FPPragmaOptions.empty()) {
8298 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00008299 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 }
8301
Yaxun Liu5b746652016-12-18 05:18:55 +00008302 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
8303 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
8304 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00008305
8306 UpdateSema();
8307}
8308
8309void ASTReader::UpdateSema() {
8310 assert(SemaObj && "no Sema to update");
8311
8312 // Load the offsets of the declarations that Sema references.
8313 // They will be lazily deserialized when needed.
8314 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00008315 assert(SemaDeclRefs.size() % 3 == 0);
8316 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00008317 if (!SemaObj->StdNamespace)
8318 SemaObj->StdNamespace = SemaDeclRefs[I];
8319 if (!SemaObj->StdBadAlloc)
8320 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00008321 if (!SemaObj->StdAlignValT)
8322 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00008323 }
8324 SemaDeclRefs.clear();
8325 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00008326
Nico Weber779355f2016-03-02 23:22:00 +00008327 // Update the state of pragmas. Use the same API as if we had encountered the
8328 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00008329 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00008330 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00008331 if (PragmaMSStructState != -1)
8332 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00008333 if (PointersToMembersPragmaLocation.isValid()) {
8334 SemaObj->ActOnPragmaMSPointersToMembers(
8335 (LangOptions::PragmaMSPointersToMembersKind)
8336 PragmaMSPointersToMembersState,
8337 PointersToMembersPragmaLocation);
8338 }
Justin Lebar67a78a62016-10-08 22:15:58 +00008339 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008340
8341 if (PragmaPackCurrentValue) {
8342 // The bottom of the stack might have a default value. It must be adjusted
8343 // to the current value to ensure that the packing state is preserved after
8344 // popping entries that were included/imported from a PCH/module.
8345 bool DropFirst = false;
8346 if (!PragmaPackStack.empty() &&
8347 PragmaPackStack.front().Location.isInvalid()) {
8348 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
8349 "Expected a default alignment value");
8350 SemaObj->PackStack.Stack.emplace_back(
8351 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00008352 SemaObj->PackStack.CurrentPragmaLocation,
8353 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008354 DropFirst = true;
8355 }
8356 for (const auto &Entry :
8357 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
8358 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00008359 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008360 if (PragmaPackCurrentLocation.isInvalid()) {
8361 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
8362 "Expected a default alignment value");
8363 // Keep the current values.
8364 } else {
8365 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
8366 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
8367 }
8368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008369}
8370
Richard Smitha8d5b6a2015-07-17 19:51:03 +00008371IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 // Note that we are loading an identifier.
8373 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00008374
Douglas Gregor7211ac12013-01-25 23:32:03 +00008375 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00008376 NumIdentifierLookups,
8377 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008378
8379 // We don't need to do identifier table lookups in C++ modules (we preload
8380 // all interesting declarations, and don't need to use the scope for name
8381 // lookups). Perform the lookup in PCH files, though, since we don't build
8382 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00008383 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00008384 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008385 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00008386 break;
8387 } else {
8388 // If there is a global index, look there first to determine which modules
8389 // provably do not have any results for this identifier.
8390 GlobalModuleIndex::HitSet Hits;
8391 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8392 if (!loadGlobalIndex()) {
8393 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8394 HitsPtr = &Hits;
8395 }
8396 }
8397
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008398 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008399 }
8400
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 IdentifierInfo *II = Visitor.getIdentifierInfo();
8402 markIdentifierUpToDate(II);
8403 return II;
8404}
8405
8406namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008408 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00008409 /// identifiers stored within a set of AST files.
8410 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008411 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 const ASTReader &Reader;
8413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008414 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00008415 /// the AST reader.
8416 unsigned Index;
8417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008418 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00008419 /// of the current AST file.
8420 ASTIdentifierLookupTable::key_iterator Current;
8421
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008422 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00008423 /// the current AST file.
8424 ASTIdentifierLookupTable::key_iterator End;
8425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008426 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00008427 bool SkipModules;
8428
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00008430 explicit ASTIdentifierIterator(const ASTReader &Reader,
8431 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00008432
Craig Topper3e89dfe2014-03-13 02:13:41 +00008433 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00008434 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008435
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008436} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008437
Ben Langmuir537c5b52016-05-04 00:53:13 +00008438ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8439 bool SkipModules)
8440 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008441}
8442
8443StringRef ASTIdentifierIterator::Next() {
8444 while (Current == End) {
8445 // If we have exhausted all of our AST files, we're done.
8446 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008447 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008448
8449 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008450 ModuleFile &F = Reader.ModuleMgr[Index];
8451 if (SkipModules && F.isModule())
8452 continue;
8453
Vedant Kumar48b4f762018-04-14 01:40:48 +00008454 ASTIdentifierLookupTable *IdTable =
8455 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 Current = IdTable->key_begin();
8457 End = IdTable->key_end();
8458 }
8459
8460 // We have any identifiers remaining in the current AST file; return
8461 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008462 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008464 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008465}
8466
Ben Langmuir537c5b52016-05-04 00:53:13 +00008467namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008468
Ben Langmuir537c5b52016-05-04 00:53:13 +00008469/// A utility for appending two IdentifierIterators.
8470class ChainedIdentifierIterator : public IdentifierIterator {
8471 std::unique_ptr<IdentifierIterator> Current;
8472 std::unique_ptr<IdentifierIterator> Queued;
8473
8474public:
8475 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8476 std::unique_ptr<IdentifierIterator> Second)
8477 : Current(std::move(First)), Queued(std::move(Second)) {}
8478
8479 StringRef Next() override {
8480 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008481 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008482
8483 StringRef result = Current->Next();
8484 if (!result.empty())
8485 return result;
8486
8487 // Try the queued iterator, which may itself be empty.
8488 Current.reset();
8489 std::swap(Current, Queued);
8490 return Next();
8491 }
8492};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008493
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008494} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008495
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008496IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008497 if (!loadGlobalIndex()) {
8498 std::unique_ptr<IdentifierIterator> ReaderIter(
8499 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8500 std::unique_ptr<IdentifierIterator> ModulesIter(
8501 GlobalIndex->createIdentifierIterator());
8502 return new ChainedIdentifierIterator(std::move(ReaderIter),
8503 std::move(ModulesIter));
8504 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008505
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 return new ASTIdentifierIterator(*this);
8507}
8508
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008509namespace clang {
8510namespace serialization {
8511
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 class ReadMethodPoolVisitor {
8513 ASTReader &Reader;
8514 Selector Sel;
8515 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008516 unsigned InstanceBits = 0;
8517 unsigned FactoryBits = 0;
8518 bool InstanceHasMoreThanOneDecl = false;
8519 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008520 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8521 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008522
8523 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008524 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008526 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008527
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008528 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 if (!M.SelectorLookupTable)
8530 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008531
Guy Benyei11169dd2012-12-18 14:30:41 +00008532 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008533 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008534 return true;
8535
Richard Smithbdf2d932015-07-30 03:37:16 +00008536 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008537 ASTSelectorLookupTable *PoolTable
8538 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008539 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008540 if (Pos == PoolTable->end())
8541 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008542
Richard Smithbdf2d932015-07-30 03:37:16 +00008543 ++Reader.NumMethodPoolTableHits;
8544 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008545 // FIXME: Not quite happy with the statistics here. We probably should
8546 // disable this tracking when called via LoadSelector.
8547 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008548 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008549 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008550 if (Reader.DeserializationListener)
8551 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008552
Richard Smithbdf2d932015-07-30 03:37:16 +00008553 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8554 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8555 InstanceBits = Data.InstanceBits;
8556 FactoryBits = Data.FactoryBits;
8557 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8558 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008559 return true;
8560 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008561
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008562 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008563 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8564 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008565 }
8566
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008567 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008568 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008569 return FactoryMethods;
8570 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008571
8572 unsigned getInstanceBits() const { return InstanceBits; }
8573 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008574
Nico Weberff4b35e2014-12-27 22:14:15 +00008575 bool instanceHasMoreThanOneDecl() const {
8576 return InstanceHasMoreThanOneDecl;
8577 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008578
Nico Weberff4b35e2014-12-27 22:14:15 +00008579 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008580 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008581
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008582} // namespace serialization
8583} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008585/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008586static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8587 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008588 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8589 S.addMethodToGlobalList(&List, Methods[I]);
8590 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008591}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008592
Guy Benyei11169dd2012-12-18 14:30:41 +00008593void ASTReader::ReadMethodPool(Selector Sel) {
8594 // Get the selector generation and update it to the current generation.
8595 unsigned &Generation = SelectorGeneration[Sel];
8596 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008597 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008598 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008599
Guy Benyei11169dd2012-12-18 14:30:41 +00008600 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008601 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008602 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008603 ModuleMgr.visit(Visitor);
8604
Guy Benyei11169dd2012-12-18 14:30:41 +00008605 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008606 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008608
8609 ++NumMethodPoolHits;
8610
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 if (!getSema())
8612 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008613
Guy Benyei11169dd2012-12-18 14:30:41 +00008614 Sema &S = *getSema();
8615 Sema::GlobalMethodPool::iterator Pos
8616 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008617
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008618 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008619 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008620 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008621 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008622
8623 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8624 // when building a module we keep every method individually and may need to
8625 // update hasMoreThanOneDecl as we add the methods.
8626 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8627 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008628}
8629
Manman Rena0f31a02016-04-29 19:04:05 +00008630void ASTReader::updateOutOfDateSelector(Selector Sel) {
8631 if (SelectorOutOfDate[Sel])
8632 ReadMethodPool(Sel);
8633}
8634
Guy Benyei11169dd2012-12-18 14:30:41 +00008635void ASTReader::ReadKnownNamespaces(
8636 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8637 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008638
Vedant Kumar48b4f762018-04-14 01:40:48 +00008639 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8640 if (NamespaceDecl *Namespace
8641 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008643 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008644}
8645
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008646void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008647 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008648 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008649 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008650 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008651 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008652 Undefined.insert(std::make_pair(D, Loc));
8653 }
8654}
Nick Lewycky8334af82013-01-26 00:35:08 +00008655
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008656void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8657 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8658 Exprs) {
8659 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008660 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008661 uint64_t Count = DelayedDeleteExprs[Idx++];
8662 for (uint64_t C = 0; C < Count; ++C) {
8663 SourceLocation DeleteLoc =
8664 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8665 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8666 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8667 }
8668 }
8669}
8670
Guy Benyei11169dd2012-12-18 14:30:41 +00008671void ASTReader::ReadTentativeDefinitions(
8672 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008673 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8674 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008675 if (Var)
8676 TentativeDefs.push_back(Var);
8677 }
8678 TentativeDefinitions.clear();
8679}
8680
8681void ASTReader::ReadUnusedFileScopedDecls(
8682 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008683 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8684 DeclaratorDecl *D
8685 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008686 if (D)
8687 Decls.push_back(D);
8688 }
8689 UnusedFileScopedDecls.clear();
8690}
8691
8692void ASTReader::ReadDelegatingConstructors(
8693 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008694 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8695 CXXConstructorDecl *D
8696 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008697 if (D)
8698 Decls.push_back(D);
8699 }
8700 DelegatingCtorDecls.clear();
8701}
8702
8703void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008704 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8705 TypedefNameDecl *D
8706 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008707 if (D)
8708 Decls.push_back(D);
8709 }
8710 ExtVectorDecls.clear();
8711}
8712
Nico Weber72889432014-09-06 01:25:55 +00008713void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8714 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008715 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8716 ++I) {
8717 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8718 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008719 if (D)
8720 Decls.insert(D);
8721 }
8722 UnusedLocalTypedefNameCandidates.clear();
8723}
8724
Guy Benyei11169dd2012-12-18 14:30:41 +00008725void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008726 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 if (ReferencedSelectorsData.empty())
8728 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008729
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 // If there are @selector references added them to its pool. This is for
8731 // implementation of -Wselector.
8732 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8733 unsigned I = 0;
8734 while (I < DataSize) {
8735 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8736 SourceLocation SelLoc
8737 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8738 Sels.push_back(std::make_pair(Sel, SelLoc));
8739 }
8740 ReferencedSelectorsData.clear();
8741}
8742
8743void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008744 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008745 if (WeakUndeclaredIdentifiers.empty())
8746 return;
8747
8748 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008749 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008750 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008751 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008752 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8753 SourceLocation Loc
8754 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8755 bool Used = WeakUndeclaredIdentifiers[I++];
8756 WeakInfo WI(AliasId, Loc);
8757 WI.setUsed(Used);
8758 WeakIDs.push_back(std::make_pair(WeakId, WI));
8759 }
8760 WeakUndeclaredIdentifiers.clear();
8761}
8762
8763void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8764 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8765 ExternalVTableUse VT;
8766 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8767 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8768 VT.DefinitionRequired = VTableUses[Idx++];
8769 VTables.push_back(VT);
8770 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008771
Guy Benyei11169dd2012-12-18 14:30:41 +00008772 VTableUses.clear();
8773}
8774
8775void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008776 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008777 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008778 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008779 SourceLocation Loc
8780 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8781
8782 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008783 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008784 PendingInstantiations.clear();
8785}
8786
Richard Smithe40f2ba2013-08-07 21:41:30 +00008787void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008788 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8789 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008790 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8791 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008792 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008793
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008794 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008795 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8796
8797 ModuleFile *F = getOwningModuleFile(LT->D);
8798 assert(F && "No module");
8799
8800 unsigned TokN = LateParsedTemplates[Idx++];
8801 LT->Toks.reserve(TokN);
8802 for (unsigned T = 0; T < TokN; ++T)
8803 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8804
Justin Lebar28f09c52016-10-10 16:26:08 +00008805 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008806 }
8807
8808 LateParsedTemplates.clear();
8809}
8810
Guy Benyei11169dd2012-12-18 14:30:41 +00008811void ASTReader::LoadSelector(Selector Sel) {
8812 // It would be complicated to avoid reading the methods anyway. So don't.
8813 ReadMethodPool(Sel);
8814}
8815
8816void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8817 assert(ID && "Non-zero identifier ID required");
8818 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8819 IdentifiersLoaded[ID - 1] = II;
8820 if (DeserializationListener)
8821 DeserializationListener->IdentifierRead(ID, II);
8822}
8823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008824/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008825/// identifier.
8826///
8827/// If the AST reader is currently in a state where the given declaration IDs
8828/// cannot safely be resolved, they are queued until it is safe to resolve
8829/// them.
8830///
8831/// \param II an IdentifierInfo that refers to one or more globally-visible
8832/// declarations.
8833///
8834/// \param DeclIDs the set of declaration IDs with the name @p II that are
8835/// visible at global scope.
8836///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008837/// \param Decls if non-null, this vector will be populated with the set of
8838/// deserialized declarations. These declarations will not be pushed into
8839/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008840void
8841ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8842 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008843 SmallVectorImpl<Decl *> *Decls) {
8844 if (NumCurrentElementsDeserializing && !Decls) {
8845 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008846 return;
8847 }
8848
Vedant Kumar48b4f762018-04-14 01:40:48 +00008849 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008850 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008851 // Queue this declaration so that it will be added to the
8852 // translation unit scope and identifier's declaration chain
8853 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008854 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008855 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008856 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008857
Vedant Kumar48b4f762018-04-14 01:40:48 +00008858 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008859
8860 // If we're simply supposed to record the declarations, do so now.
8861 if (Decls) {
8862 Decls->push_back(D);
8863 continue;
8864 }
8865
8866 // Introduce this declaration into the translation-unit scope
8867 // and add it to the declaration chain for this identifier, so
8868 // that (unqualified) name lookup will find it.
8869 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008870 }
8871}
8872
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008873IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008874 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008875 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008876
8877 if (IdentifiersLoaded.empty()) {
8878 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008879 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008880 }
8881
8882 ID -= 1;
8883 if (!IdentifiersLoaded[ID]) {
8884 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8885 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8886 ModuleFile *M = I->second;
8887 unsigned Index = ID - M->BaseIdentifierID;
8888 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8889
8890 // All of the strings in the AST file are preceded by a 16-bit length.
8891 // Extract that 16-bit length to avoid having to execute strlen().
8892 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8893 // unsigned integers. This is important to avoid integer overflow when
8894 // we cast them to 'unsigned'.
8895 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8896 unsigned StrLen = (((unsigned) StrLenPtr[0])
8897 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008898 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8899 IdentifiersLoaded[ID] = &II;
8900 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008901 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008902 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 }
8904
8905 return IdentifiersLoaded[ID];
8906}
8907
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008908IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8909 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008910}
8911
8912IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8913 if (LocalID < NUM_PREDEF_IDENT_IDS)
8914 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008915
Richard Smith37a93df2017-02-18 00:32:02 +00008916 if (!M.ModuleOffsetMap.empty())
8917 ReadModuleOffsetMap(M);
8918
Guy Benyei11169dd2012-12-18 14:30:41 +00008919 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8920 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008921 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008922 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008923
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 return LocalID + I->second;
8925}
8926
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008927MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008928 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008929 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008930
8931 if (MacrosLoaded.empty()) {
8932 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008933 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008934 }
8935
8936 ID -= NUM_PREDEF_MACRO_IDS;
8937 if (!MacrosLoaded[ID]) {
8938 GlobalMacroMapType::iterator I
8939 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8940 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8941 ModuleFile *M = I->second;
8942 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008943 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008944
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008945 if (DeserializationListener)
8946 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8947 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008948 }
8949
8950 return MacrosLoaded[ID];
8951}
8952
8953MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8954 if (LocalID < NUM_PREDEF_MACRO_IDS)
8955 return LocalID;
8956
Richard Smith37a93df2017-02-18 00:32:02 +00008957 if (!M.ModuleOffsetMap.empty())
8958 ReadModuleOffsetMap(M);
8959
Guy Benyei11169dd2012-12-18 14:30:41 +00008960 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8961 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8962 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8963
8964 return LocalID + I->second;
8965}
8966
8967serialization::SubmoduleID
8968ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8969 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8970 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008971
Richard Smith37a93df2017-02-18 00:32:02 +00008972 if (!M.ModuleOffsetMap.empty())
8973 ReadModuleOffsetMap(M);
8974
Guy Benyei11169dd2012-12-18 14:30:41 +00008975 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8976 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008977 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008978 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008979
Guy Benyei11169dd2012-12-18 14:30:41 +00008980 return LocalID + I->second;
8981}
8982
8983Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8984 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8985 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008986 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008987 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008988
Guy Benyei11169dd2012-12-18 14:30:41 +00008989 if (GlobalID > SubmodulesLoaded.size()) {
8990 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008991 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008992 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008993
Guy Benyei11169dd2012-12-18 14:30:41 +00008994 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8995}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008996
8997Module *ASTReader::getModule(unsigned ID) {
8998 return getSubmodule(ID);
8999}
9000
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009001bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
9002 ModuleFile *MF = getOwningModuleFile(D);
9003 return MF && MF->PCHHasObjectFile;
9004}
9005
Richard Smithd88a7f12015-09-01 20:35:42 +00009006ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
9007 if (ID & 1) {
9008 // It's a module, look it up by submodule ID.
9009 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
9010 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9011 } else {
9012 // It's a prefix (preamble, PCH, ...). Look it up by index.
9013 unsigned IndexFromEnd = ID >> 1;
9014 assert(IndexFromEnd && "got reference to unknown module file");
9015 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9016 }
9017}
9018
9019unsigned ASTReader::getModuleFileID(ModuleFile *F) {
9020 if (!F)
9021 return 1;
9022
9023 // For a file representing a module, use the submodule ID of the top-level
9024 // module as the file ID. For any other kind of file, the number of such
9025 // files loaded beforehand will be the same on reload.
9026 // FIXME: Is this true even if we have an explicit module file and a PCH?
9027 if (F->isModule())
9028 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9029
9030 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00009031 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00009032 assert(I != PCHModules.end() && "emitting reference to unknown file");
9033 return (I - PCHModules.end()) << 1;
9034}
9035
Adrian Prantl15bcf702015-06-30 17:39:43 +00009036llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
9037ASTReader::getSourceDescriptor(unsigned ID) {
9038 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00009039 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00009040
9041 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00009042 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00009043 const auto &PCHChain = ModuleMgr.pch_modules();
9044 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00009045 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00009046 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00009047 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9048 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
9049 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00009050 }
9051 return None;
9052}
9053
David Blaikie1ac9c982017-04-11 21:13:37 +00009054ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00009055 auto I = DefinitionSource.find(FD);
9056 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00009057 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00009058 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00009059}
9060
Guy Benyei11169dd2012-12-18 14:30:41 +00009061Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
9062 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9063}
9064
9065Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9066 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009067 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009068
9069 if (ID > SelectorsLoaded.size()) {
9070 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009071 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009072 }
9073
Craig Toppera13603a2014-05-22 05:54:18 +00009074 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009075 // Load this selector from the selector table.
9076 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9077 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9078 ModuleFile &M = *I->second;
9079 ASTSelectorLookupTrait Trait(*this, M);
9080 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9081 SelectorsLoaded[ID - 1] =
9082 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9083 if (DeserializationListener)
9084 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9085 }
9086
9087 return SelectorsLoaded[ID - 1];
9088}
9089
9090Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9091 return DecodeSelector(ID);
9092}
9093
9094uint32_t ASTReader::GetNumExternalSelectors() {
9095 // ID 0 (the null selector) is considered an external selector.
9096 return getTotalNumSelectors() + 1;
9097}
9098
9099serialization::SelectorID
9100ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9101 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9102 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009103
Richard Smith37a93df2017-02-18 00:32:02 +00009104 if (!M.ModuleOffsetMap.empty())
9105 ReadModuleOffsetMap(M);
9106
Guy Benyei11169dd2012-12-18 14:30:41 +00009107 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9108 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009109 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00009110 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009111
Guy Benyei11169dd2012-12-18 14:30:41 +00009112 return LocalID + I->second;
9113}
9114
9115DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009116ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009117 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009118 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009119 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009120 switch (Kind) {
9121 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00009122 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009123
9124 case DeclarationName::ObjCZeroArgSelector:
9125 case DeclarationName::ObjCOneArgSelector:
9126 case DeclarationName::ObjCMultiArgSelector:
9127 return DeclarationName(ReadSelector(F, Record, Idx));
9128
9129 case DeclarationName::CXXConstructorName:
9130 return Context.DeclarationNames.getCXXConstructorName(
9131 Context.getCanonicalType(readType(F, Record, Idx)));
9132
9133 case DeclarationName::CXXDestructorName:
9134 return Context.DeclarationNames.getCXXDestructorName(
9135 Context.getCanonicalType(readType(F, Record, Idx)));
9136
Richard Smith35845152017-02-07 01:37:30 +00009137 case DeclarationName::CXXDeductionGuideName:
9138 return Context.DeclarationNames.getCXXDeductionGuideName(
9139 ReadDeclAs<TemplateDecl>(F, Record, Idx));
9140
Guy Benyei11169dd2012-12-18 14:30:41 +00009141 case DeclarationName::CXXConversionFunctionName:
9142 return Context.DeclarationNames.getCXXConversionFunctionName(
9143 Context.getCanonicalType(readType(F, Record, Idx)));
9144
9145 case DeclarationName::CXXOperatorName:
9146 return Context.DeclarationNames.getCXXOperatorName(
9147 (OverloadedOperatorKind)Record[Idx++]);
9148
9149 case DeclarationName::CXXLiteralOperatorName:
9150 return Context.DeclarationNames.getCXXLiteralOperatorName(
9151 GetIdentifierInfo(F, Record, Idx));
9152
9153 case DeclarationName::CXXUsingDirective:
9154 return DeclarationName::getUsingDirectiveName();
9155 }
9156
9157 llvm_unreachable("Invalid NameKind!");
9158}
9159
9160void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
9161 DeclarationNameLoc &DNLoc,
9162 DeclarationName Name,
9163 const RecordData &Record, unsigned &Idx) {
9164 switch (Name.getNameKind()) {
9165 case DeclarationName::CXXConstructorName:
9166 case DeclarationName::CXXDestructorName:
9167 case DeclarationName::CXXConversionFunctionName:
9168 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
9169 break;
9170
9171 case DeclarationName::CXXOperatorName:
9172 DNLoc.CXXOperatorName.BeginOpNameLoc
9173 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9174 DNLoc.CXXOperatorName.EndOpNameLoc
9175 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9176 break;
9177
9178 case DeclarationName::CXXLiteralOperatorName:
9179 DNLoc.CXXLiteralOperatorName.OpNameLoc
9180 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9181 break;
9182
9183 case DeclarationName::Identifier:
9184 case DeclarationName::ObjCZeroArgSelector:
9185 case DeclarationName::ObjCOneArgSelector:
9186 case DeclarationName::ObjCMultiArgSelector:
9187 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00009188 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00009189 break;
9190 }
9191}
9192
9193void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
9194 DeclarationNameInfo &NameInfo,
9195 const RecordData &Record, unsigned &Idx) {
9196 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
9197 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
9198 DeclarationNameLoc DNLoc;
9199 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
9200 NameInfo.setInfo(DNLoc);
9201}
9202
9203void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
9204 const RecordData &Record, unsigned &Idx) {
9205 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
9206 unsigned NumTPLists = Record[Idx++];
9207 Info.NumTemplParamLists = NumTPLists;
9208 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009209 Info.TemplParamLists =
9210 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00009211 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00009212 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
9213 }
9214}
9215
9216TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009217ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009218 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009219 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009220 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009221 switch (Kind) {
9222 case TemplateName::Template:
9223 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
9224
9225 case TemplateName::OverloadedTemplate: {
9226 unsigned size = Record[Idx++];
9227 UnresolvedSet<8> Decls;
9228 while (size--)
9229 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
9230
9231 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
9232 }
9233
Richard Smithb23c5e82019-05-09 03:31:27 +00009234 case TemplateName::AssumedTemplate: {
9235 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
9236 return Context.getAssumedTemplateName(Name);
9237 }
9238
Guy Benyei11169dd2012-12-18 14:30:41 +00009239 case TemplateName::QualifiedTemplate: {
9240 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9241 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009242 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009243 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
9244 }
9245
9246 case TemplateName::DependentTemplate: {
9247 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9248 if (Record[Idx++]) // isIdentifier
9249 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009250 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009251 Idx));
9252 return Context.getDependentTemplateName(NNS,
9253 (OverloadedOperatorKind)Record[Idx++]);
9254 }
9255
9256 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009257 TemplateTemplateParmDecl *param
9258 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
9259 if (!param) return TemplateName();
9260 TemplateName replacement = ReadTemplateName(F, Record, Idx);
9261 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00009262 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009263
Guy Benyei11169dd2012-12-18 14:30:41 +00009264 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009265 TemplateTemplateParmDecl *Param
9266 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009267 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009268 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009269
Guy Benyei11169dd2012-12-18 14:30:41 +00009270 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
9271 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009272 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009273
Guy Benyei11169dd2012-12-18 14:30:41 +00009274 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
9275 }
9276 }
9277
9278 llvm_unreachable("Unhandled template name kind!");
9279}
9280
Richard Smith2bb3c342015-08-09 01:05:31 +00009281TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
9282 const RecordData &Record,
9283 unsigned &Idx,
9284 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009285 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00009286 if (Canonicalize) {
9287 // The caller wants a canonical template argument. Sometimes the AST only
9288 // wants template arguments in canonical form (particularly as the template
9289 // argument lists of template specializations) so ensure we preserve that
9290 // canonical form across serialization.
9291 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
9292 return Context.getCanonicalTemplateArgument(Arg);
9293 }
9294
Vedant Kumar48b4f762018-04-14 01:40:48 +00009295 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009296 switch (Kind) {
9297 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00009298 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00009299 case TemplateArgument::Type:
9300 return TemplateArgument(readType(F, Record, Idx));
9301 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009302 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00009303 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009304 }
9305 case TemplateArgument::NullPtr:
9306 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
9307 case TemplateArgument::Integral: {
9308 llvm::APSInt Value = ReadAPSInt(Record, Idx);
9309 QualType T = readType(F, Record, Idx);
9310 return TemplateArgument(Context, Value, T);
9311 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009312 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00009313 return TemplateArgument(ReadTemplateName(F, Record, Idx));
9314 case TemplateArgument::TemplateExpansion: {
9315 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00009316 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00009317 if (unsigned NumExpansions = Record[Idx++])
9318 NumTemplateExpansions = NumExpansions - 1;
9319 return TemplateArgument(Name, NumTemplateExpansions);
9320 }
9321 case TemplateArgument::Expression:
9322 return TemplateArgument(ReadExpr(F));
9323 case TemplateArgument::Pack: {
9324 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009325 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00009326 for (unsigned I = 0; I != NumArgs; ++I)
9327 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00009328 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00009329 }
9330 }
9331
9332 llvm_unreachable("Unhandled template argument kind!");
9333}
9334
9335TemplateParameterList *
9336ASTReader::ReadTemplateParameterList(ModuleFile &F,
9337 const RecordData &Record, unsigned &Idx) {
9338 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
9339 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
9340 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
9341
9342 unsigned NumParams = Record[Idx++];
9343 SmallVector<NamedDecl *, 16> Params;
9344 Params.reserve(NumParams);
9345 while (NumParams--)
9346 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
9347
Saar Raz0330fba2019-10-15 18:44:06 +00009348 bool HasRequiresClause = Record[Idx++];
9349 Expr *RequiresClause = HasRequiresClause ? ReadExpr(F) : nullptr;
9350
Richard Smithdbafb6c2017-06-29 23:23:46 +00009351 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00009352 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00009353 return TemplateParams;
9354}
9355
9356void
9357ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00009358ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00009359 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00009360 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009361 unsigned NumTemplateArgs = Record[Idx++];
9362 TemplArgs.reserve(NumTemplateArgs);
9363 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00009364 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00009365}
9366
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009367/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00009368void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00009369 const RecordData &Record, unsigned &Idx) {
9370 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009371 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00009372 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00009373 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009374 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009375 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00009376 }
9377}
9378
9379CXXBaseSpecifier
9380ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
9381 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009382 bool isVirtual = static_cast<bool>(Record[Idx++]);
9383 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
9384 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
9385 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009386 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
9387 SourceRange Range = ReadSourceRange(F, Record, Idx);
9388 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009389 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00009390 EllipsisLoc);
9391 Result.setInheritConstructors(inheritConstructors);
9392 return Result;
9393}
9394
Richard Smithc2bb8182015-03-24 06:36:48 +00009395CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00009396ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
9397 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009398 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009399 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009400 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009401 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00009402 for (unsigned i = 0; i != NumInitializers; ++i) {
9403 TypeSourceInfo *TInfo = nullptr;
9404 bool IsBaseVirtual = false;
9405 FieldDecl *Member = nullptr;
9406 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009407
Vedant Kumar48b4f762018-04-14 01:40:48 +00009408 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009409 switch (Type) {
9410 case CTOR_INITIALIZER_BASE:
9411 TInfo = GetTypeSourceInfo(F, Record, Idx);
9412 IsBaseVirtual = Record[Idx++];
9413 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009414
Richard Smithc2bb8182015-03-24 06:36:48 +00009415 case CTOR_INITIALIZER_DELEGATING:
9416 TInfo = GetTypeSourceInfo(F, Record, Idx);
9417 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009418
Richard Smithc2bb8182015-03-24 06:36:48 +00009419 case CTOR_INITIALIZER_MEMBER:
9420 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
9421 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009422
Richard Smithc2bb8182015-03-24 06:36:48 +00009423 case CTOR_INITIALIZER_INDIRECT_MEMBER:
9424 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
9425 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009426 }
Richard Smithc2bb8182015-03-24 06:36:48 +00009427
9428 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
9429 Expr *Init = ReadExpr(F);
9430 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
9431 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00009432
9433 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00009434 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00009435 BOMInit = new (Context)
9436 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9437 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009438 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00009439 BOMInit = new (Context)
9440 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009441 else if (Member)
9442 BOMInit = new (Context)
9443 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9444 Init, RParenLoc);
9445 else
9446 BOMInit = new (Context)
9447 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9448 LParenLoc, Init, RParenLoc);
9449
Richard Smith418ed822016-12-14 19:45:03 +00009450 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00009451 unsigned SourceOrder = Record[Idx++];
9452 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00009453 }
9454
Richard Smithc2bb8182015-03-24 06:36:48 +00009455 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00009456 }
9457
Richard Smithc2bb8182015-03-24 06:36:48 +00009458 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00009459}
9460
9461NestedNameSpecifier *
9462ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
9463 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009464 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009465 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00009466 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009467 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009468 NestedNameSpecifier::SpecifierKind Kind
9469 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009470 switch (Kind) {
9471 case NestedNameSpecifier::Identifier: {
9472 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
9473 NNS = NestedNameSpecifier::Create(Context, Prev, II);
9474 break;
9475 }
9476
9477 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009478 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009479 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
9480 break;
9481 }
9482
9483 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009484 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009485 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9486 break;
9487 }
9488
9489 case NestedNameSpecifier::TypeSpec:
9490 case NestedNameSpecifier::TypeSpecWithTemplate: {
9491 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9492 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009493 return nullptr;
9494
Guy Benyei11169dd2012-12-18 14:30:41 +00009495 bool Template = Record[Idx++];
9496 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9497 break;
9498 }
9499
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009500 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009501 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9502 // No associated value, and there can't be a prefix.
9503 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009504
9505 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009506 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009507 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9508 break;
9509 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009510 }
9511 Prev = NNS;
9512 }
9513 return NNS;
9514}
9515
9516NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009517ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009518 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009519 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009520 unsigned N = Record[Idx++];
9521 NestedNameSpecifierLocBuilder Builder;
9522 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009523 NestedNameSpecifier::SpecifierKind Kind
9524 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009525 switch (Kind) {
9526 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009527 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009528 SourceRange Range = ReadSourceRange(F, Record, Idx);
9529 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9530 break;
9531 }
9532
9533 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009534 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009535 SourceRange Range = ReadSourceRange(F, Record, Idx);
9536 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9537 break;
9538 }
9539
9540 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009541 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009542 SourceRange Range = ReadSourceRange(F, Record, Idx);
9543 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9544 break;
9545 }
9546
9547 case NestedNameSpecifier::TypeSpec:
9548 case NestedNameSpecifier::TypeSpecWithTemplate: {
9549 bool Template = Record[Idx++];
9550 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9551 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009552 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009553 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9554
9555 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009556 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009557 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9558 T->getTypeLoc(), ColonColonLoc);
9559 break;
9560 }
9561
9562 case NestedNameSpecifier::Global: {
9563 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9564 Builder.MakeGlobal(Context, ColonColonLoc);
9565 break;
9566 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009567
9568 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009569 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009570 SourceRange Range = ReadSourceRange(F, Record, Idx);
9571 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9572 break;
9573 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009574 }
9575 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009576
Guy Benyei11169dd2012-12-18 14:30:41 +00009577 return Builder.getWithLocInContext(Context);
9578}
9579
9580SourceRange
9581ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9582 unsigned &Idx) {
9583 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9584 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9585 return SourceRange(beg, end);
9586}
9587
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009588static FixedPointSemantics
9589ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9590 unsigned &Idx) {
9591 unsigned Width = Record[Idx++];
9592 unsigned Scale = Record[Idx++];
9593 uint64_t Tmp = Record[Idx++];
9594 bool IsSigned = Tmp & 0x1;
9595 bool IsSaturated = Tmp & 0x2;
9596 bool HasUnsignedPadding = Tmp & 0x4;
9597 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9598 HasUnsignedPadding);
9599}
9600
9601APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9602 unsigned Kind = Record[Idx++];
9603 switch (Kind) {
9604 case APValue::None:
9605 return APValue();
9606 case APValue::Indeterminate:
9607 return APValue::IndeterminateValue();
9608 case APValue::Int:
9609 return APValue(ReadAPSInt(Record, Idx));
9610 case APValue::Float: {
9611 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9612 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9613 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9614 }
9615 case APValue::FixedPoint: {
9616 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9617 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9618 }
9619 case APValue::ComplexInt: {
9620 llvm::APSInt First = ReadAPSInt(Record, Idx);
9621 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9622 }
9623 case APValue::ComplexFloat: {
9624 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9625 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9626 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9627 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9628 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9629 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9630 }
9631 case APValue::LValue:
9632 case APValue::Vector:
9633 case APValue::Array:
9634 case APValue::Struct:
9635 case APValue::Union:
9636 case APValue::MemberPointer:
9637 case APValue::AddrLabelDiff:
9638 // TODO : Handle all these APValue::ValueKind.
9639 return APValue();
9640 }
9641 llvm_unreachable("Invalid APValue::ValueKind");
9642}
9643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009644/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009645llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9646 unsigned BitWidth = Record[Idx++];
9647 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9648 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9649 Idx += NumWords;
9650 return Result;
9651}
9652
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009653/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009654llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9655 bool isUnsigned = Record[Idx++];
9656 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9657}
9658
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009659/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009660llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9661 const llvm::fltSemantics &Sem,
9662 unsigned &Idx) {
9663 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009664}
9665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009666// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009667std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9668 unsigned Len = Record[Idx++];
9669 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9670 Idx += Len;
9671 return Result;
9672}
9673
Richard Smith7ed1bc92014-12-05 22:42:13 +00009674std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9675 unsigned &Idx) {
9676 std::string Filename = ReadString(Record, Idx);
9677 ResolveImportedPath(F, Filename);
9678 return Filename;
9679}
9680
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009681std::string ASTReader::ReadPath(StringRef BaseDirectory,
9682 const RecordData &Record, unsigned &Idx) {
9683 std::string Filename = ReadString(Record, Idx);
9684 if (!BaseDirectory.empty())
9685 ResolveImportedPath(Filename, BaseDirectory);
9686 return Filename;
9687}
9688
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009689VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009690 unsigned &Idx) {
9691 unsigned Major = Record[Idx++];
9692 unsigned Minor = Record[Idx++];
9693 unsigned Subminor = Record[Idx++];
9694 if (Minor == 0)
9695 return VersionTuple(Major);
9696 if (Subminor == 0)
9697 return VersionTuple(Major, Minor - 1);
9698 return VersionTuple(Major, Minor - 1, Subminor - 1);
9699}
9700
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009701CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009702 const RecordData &Record,
9703 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009704 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009705 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009706}
9707
Richard Smith37a93df2017-02-18 00:32:02 +00009708DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009709 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009710}
9711
Richard Smith37a93df2017-02-18 00:32:02 +00009712DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009713 return Diags.Report(Loc, DiagID);
9714}
9715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009716/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009717/// preprocessor.
9718IdentifierTable &ASTReader::getIdentifierTable() {
9719 return PP.getIdentifierTable();
9720}
9721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009722/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009723/// statement.
9724void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009725 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009726 "Already have a SwitchCase with this ID");
9727 (*CurrSwitchCaseStmts)[ID] = SC;
9728}
9729
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009730/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009731SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009732 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009733 return (*CurrSwitchCaseStmts)[ID];
9734}
9735
9736void ASTReader::ClearSwitchCaseIDs() {
9737 CurrSwitchCaseStmts->clear();
9738}
9739
9740void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009741 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009742 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009743 for (SmallVectorImpl<std::pair<BitstreamCursor,
9744 serialization::ModuleFile *>>::iterator
9745 I = CommentsCursors.begin(),
9746 E = CommentsCursors.end();
9747 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009748 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009749 BitstreamCursor &Cursor = I->first;
9750 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009751 SavedStreamPosition SavedPosition(Cursor);
9752
9753 RecordData Record;
9754 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009755 Expected<llvm::BitstreamEntry> MaybeEntry =
9756 Cursor.advanceSkippingSubblocks(
9757 BitstreamCursor::AF_DontPopBlockAtEnd);
9758 if (!MaybeEntry) {
9759 Error(MaybeEntry.takeError());
9760 return;
9761 }
9762 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009763
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009764 switch (Entry.Kind) {
9765 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9766 case llvm::BitstreamEntry::Error:
9767 Error("malformed block record in AST file");
9768 return;
9769 case llvm::BitstreamEntry::EndBlock:
9770 goto NextCursor;
9771 case llvm::BitstreamEntry::Record:
9772 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009773 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009774 }
9775
9776 // Read a record.
9777 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009778 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9779 if (!MaybeComment) {
9780 Error(MaybeComment.takeError());
9781 return;
9782 }
9783 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009784 case COMMENTS_RAW_COMMENT: {
9785 unsigned Idx = 0;
9786 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009787 RawComment::CommentKind Kind =
9788 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009789 bool IsTrailingComment = Record[Idx++];
9790 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009791 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009792 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009793 break;
9794 }
9795 }
9796 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009797 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009798 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9799 FileToOffsetToComment;
9800 for (RawComment *C : Comments) {
9801 SourceLocation CommentLoc = C->getBeginLoc();
9802 if (CommentLoc.isValid()) {
9803 std::pair<FileID, unsigned> Loc =
9804 SourceMgr.getDecomposedLoc(CommentLoc);
9805 if (Loc.first.isValid())
9806 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9807 }
9808 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009809 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009810}
9811
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009812void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9813 bool IncludeSystem, bool Complain,
9814 llvm::function_ref<void(const serialization::InputFile &IF,
9815 bool isSystem)> Visitor) {
9816 unsigned NumUserInputs = MF.NumUserInputFiles;
9817 unsigned NumInputs = MF.InputFilesLoaded.size();
9818 assert(NumUserInputs <= NumInputs);
9819 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9820 for (unsigned I = 0; I < N; ++I) {
9821 bool IsSystem = I >= NumUserInputs;
9822 InputFile IF = getInputFile(MF, I+1, Complain);
9823 Visitor(IF, IsSystem);
9824 }
9825}
9826
Richard Smithf3f84612017-06-29 02:19:42 +00009827void ASTReader::visitTopLevelModuleMaps(
9828 serialization::ModuleFile &MF,
9829 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9830 unsigned NumInputs = MF.InputFilesLoaded.size();
9831 for (unsigned I = 0; I < NumInputs; ++I) {
9832 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9833 if (IFI.TopLevelModuleMap)
9834 // FIXME: This unnecessarily re-reads the InputFileInfo.
9835 if (auto *FE = getInputFile(MF, I + 1).getFile())
9836 Visitor(FE);
9837 }
9838}
9839
Richard Smithcd45dbc2014-04-19 03:48:30 +00009840std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9841 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009842 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009843 return M->getFullModuleName();
9844
9845 // Otherwise, use the name of the top-level module the decl is within.
9846 if (ModuleFile *M = getOwningModuleFile(D))
9847 return M->ModuleName;
9848
9849 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009850 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009851}
9852
Guy Benyei11169dd2012-12-18 14:30:41 +00009853void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009854 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009855 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009856 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009857 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009858 // If any identifiers with corresponding top-level declarations have
9859 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009860 using TopLevelDeclsMap =
9861 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009862 TopLevelDeclsMap TopLevelDecls;
9863
Guy Benyei11169dd2012-12-18 14:30:41 +00009864 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009865 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009866 SmallVector<uint32_t, 4> DeclIDs =
9867 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009868 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009869
9870 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009871 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009872
Richard Smitha62d1982018-08-03 01:00:01 +00009873 // Load each function type that we deferred loading because it was a
9874 // deduced type that might refer to a local type declared within itself.
9875 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9876 auto *FD = PendingFunctionTypes[I].first;
9877 FD->setType(GetType(PendingFunctionTypes[I].second));
9878
9879 // If we gave a function a deduced return type, remember that we need to
9880 // propagate that along the redeclaration chain.
9881 auto *DT = FD->getReturnType()->getContainedDeducedType();
9882 if (DT && DT->isDeduced())
9883 PendingDeducedTypeUpdates.insert(
9884 {FD->getCanonicalDecl(), FD->getReturnType()});
9885 }
9886 PendingFunctionTypes.clear();
9887
Richard Smith851072e2014-05-19 20:59:20 +00009888 // For each decl chain that we wanted to complete while deserializing, mark
9889 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009890 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9891 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9892 }
Richard Smith851072e2014-05-19 20:59:20 +00009893 PendingIncompleteDeclChains.clear();
9894
Guy Benyei11169dd2012-12-18 14:30:41 +00009895 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009896 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009897 loadPendingDeclChain(PendingDeclChains[I].first,
9898 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009899 PendingDeclChains.clear();
9900
Douglas Gregor6168bd22013-02-18 15:53:43 +00009901 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009902 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9903 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9904 IdentifierInfo *II = TLD->first;
9905 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9906 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009907 }
9908 }
9909
Guy Benyei11169dd2012-12-18 14:30:41 +00009910 // Load any pending macro definitions.
9911 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009912 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9913 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9914 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9915 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009916 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009917 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009918 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009919 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009920 resolvePendingMacro(II, Info);
9921 }
9922 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009923 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009924 ++IDIdx) {
9925 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009926 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009927 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009928 }
9929 }
9930 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009931
9932 // Wire up the DeclContexts for Decls that we delayed setting until
9933 // recursive loading is completed.
9934 while (!PendingDeclContextInfos.empty()) {
9935 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9936 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009937 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9938 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009939 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9940 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009941
Richard Smithd1c46742014-04-30 02:24:17 +00009942 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009943 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009944 auto Update = PendingUpdateRecords.pop_back_val();
9945 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009946 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009948 }
Richard Smith8a639892015-01-24 01:07:20 +00009949
9950 // At this point, all update records for loaded decls are in place, so any
9951 // fake class definitions should have become real.
9952 assert(PendingFakeDefinitionData.empty() &&
9953 "faked up a class definition but never saw the real one");
9954
Guy Benyei11169dd2012-12-18 14:30:41 +00009955 // If we deserialized any C++ or Objective-C class definitions, any
9956 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009957 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009958 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009959 for (Decl *D : PendingDefinitions) {
9960 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9961 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009962 // Make sure that the TagType points at the definition.
9963 const_cast<TagType*>(TagT)->decl = TD;
9964 }
Richard Smith8ce51082015-03-11 01:44:51 +00009965
Vedant Kumar48b4f762018-04-14 01:40:48 +00009966 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009967 for (auto *R = getMostRecentExistingDecl(RD); R;
9968 R = R->getPreviousDecl()) {
9969 assert((R == D) ==
9970 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009971 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009972 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009973 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009974 }
9975
9976 continue;
9977 }
Richard Smith8ce51082015-03-11 01:44:51 +00009978
Vedant Kumar48b4f762018-04-14 01:40:48 +00009979 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009980 // Make sure that the ObjCInterfaceType points at the definition.
9981 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9982 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009983
9984 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9985 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9986
Guy Benyei11169dd2012-12-18 14:30:41 +00009987 continue;
9988 }
Richard Smith8ce51082015-03-11 01:44:51 +00009989
Vedant Kumar48b4f762018-04-14 01:40:48 +00009990 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009991 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9992 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9993
Guy Benyei11169dd2012-12-18 14:30:41 +00009994 continue;
9995 }
Richard Smith8ce51082015-03-11 01:44:51 +00009996
Vedant Kumar48b4f762018-04-14 01:40:48 +00009997 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009998 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9999 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +000010000 }
10001 PendingDefinitions.clear();
10002
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010003 // Load the bodies of any functions or methods we've encountered. We do
10004 // this now (delayed) so that we can be sure that the declaration chains
10005 // have been fully wired up (hasBody relies on this).
10006 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +000010007 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10008 PBEnd = PendingBodies.end();
10009 PB != PBEnd; ++PB) {
10010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +000010011 // For a function defined inline within a class template, force the
10012 // canonical definition to be the one inside the canonical definition of
10013 // the template. This ensures that we instantiate from a correct view
10014 // of the template.
10015 //
10016 // Sadly we can't do this more generally: we can't be sure that all
10017 // copies of an arbitrary class definition will have the same members
10018 // defined (eg, some member functions may not be instantiated, and some
10019 // special members may or may not have been implicitly defined).
10020 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
10021 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
10022 continue;
10023
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010024 // FIXME: Check for =delete/=default?
10025 // FIXME: Complain about ODR violations here?
10026 const FunctionDecl *Defn = nullptr;
10027 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010028 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +000010029 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010030 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +000010031 mergeDefinitionVisibility(NonConstDefn, FD);
10032
10033 if (!FD->isLateTemplateParsed() &&
10034 !NonConstDefn->isLateTemplateParsed() &&
10035 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010036 if (!isa<CXXMethodDecl>(FD)) {
10037 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10038 } else if (FD->getLexicalParent()->isFileContext() &&
10039 NonConstDefn->getLexicalParent()->isFileContext()) {
10040 // Only diagnose out-of-line method definitions. If they are
10041 // in class definitions, then an error will be generated when
10042 // processing the class bodies.
10043 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10044 }
Richard Trieue6caa262017-12-23 00:41:01 +000010045 }
10046 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010047 continue;
10048 }
10049
Vedant Kumar48b4f762018-04-14 01:40:48 +000010050 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010051 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +000010052 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +000010053 }
10054 PendingBodies.clear();
10055
Richard Smith42413142015-05-15 20:05:43 +000010056 // Do some cleanup.
10057 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10058 getContext().deduplicateMergedDefinitonsFor(ND);
10059 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010060}
10061
10062void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +000010063 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +000010064 PendingFunctionOdrMergeFailures.empty() &&
10065 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +000010066 return;
10067
Richard Smitha0ce9c42014-07-29 23:23:27 +000010068 // Trigger the import of the full definition of each class that had any
10069 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +000010070 // These updates may in turn find and diagnose some ODR failures, so take
10071 // ownership of the set first.
10072 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10073 PendingOdrMergeFailures.clear();
10074 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010075 Merge.first->buildLookup();
10076 Merge.first->decls_begin();
10077 Merge.first->bases_begin();
10078 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +000010079 for (auto &RecordPair : Merge.second) {
10080 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010081 RD->decls_begin();
10082 RD->bases_begin();
10083 RD->vbases_begin();
10084 }
10085 }
10086
Richard Trieue6caa262017-12-23 00:41:01 +000010087 // Trigger the import of functions.
10088 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10089 PendingFunctionOdrMergeFailures.clear();
10090 for (auto &Merge : FunctionOdrMergeFailures) {
10091 Merge.first->buildLookup();
10092 Merge.first->decls_begin();
10093 Merge.first->getBody();
10094 for (auto &FD : Merge.second) {
10095 FD->buildLookup();
10096 FD->decls_begin();
10097 FD->getBody();
10098 }
10099 }
10100
Richard Trieuab4d7302018-07-25 22:52:05 +000010101 // Trigger the import of enums.
10102 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10103 PendingEnumOdrMergeFailures.clear();
10104 for (auto &Merge : EnumOdrMergeFailures) {
10105 Merge.first->decls_begin();
10106 for (auto &Enum : Merge.second) {
10107 Enum->decls_begin();
10108 }
10109 }
10110
Richard Smitha0ce9c42014-07-29 23:23:27 +000010111 // For each declaration from a merged context, check that the canonical
10112 // definition of that context also contains a declaration of the same
10113 // entity.
10114 //
10115 // Caution: this loop does things that might invalidate iterators into
10116 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10117 while (!PendingOdrMergeChecks.empty()) {
10118 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10119
10120 // FIXME: Skip over implicit declarations for now. This matters for things
10121 // like implicitly-declared special member functions. This isn't entirely
10122 // correct; we can end up with multiple unmerged declarations of the same
10123 // implicit entity.
10124 if (D->isImplicit())
10125 continue;
10126
10127 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010128
10129 bool Found = false;
10130 const Decl *DCanon = D->getCanonicalDecl();
10131
Richard Smith01bdb7a2014-08-28 05:44:07 +000010132 for (auto RI : D->redecls()) {
10133 if (RI->getLexicalDeclContext() == CanonDef) {
10134 Found = true;
10135 break;
10136 }
10137 }
10138 if (Found)
10139 continue;
10140
Richard Smith0f4e2c42015-08-06 04:23:48 +000010141 // Quick check failed, time to do the slow thing. Note, we can't just
10142 // look up the name of D in CanonDef here, because the member that is
10143 // in CanonDef might not be found by name lookup (it might have been
10144 // replaced by a more recent declaration in the lookup table), and we
10145 // can't necessarily find it in the redeclaration chain because it might
10146 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010147 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +000010148 for (auto *CanonMember : CanonDef->decls()) {
10149 if (CanonMember->getCanonicalDecl() == DCanon) {
10150 // This can happen if the declaration is merely mergeable and not
10151 // actually redeclarable (we looked for redeclarations earlier).
10152 //
10153 // FIXME: We should be able to detect this more efficiently, without
10154 // pulling in all of the members of CanonDef.
10155 Found = true;
10156 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010157 }
Richard Smith0f4e2c42015-08-06 04:23:48 +000010158 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10159 if (ND->getDeclName() == D->getDeclName())
10160 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010161 }
10162
10163 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +000010164 // The AST doesn't like TagDecls becoming invalid after they've been
10165 // completed. We only really need to mark FieldDecls as invalid here.
10166 if (!isa<TagDecl>(D))
10167 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010168
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010169 // Ensure we don't accidentally recursively enter deserialization while
10170 // we're producing our diagnostic.
10171 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010172
10173 std::string CanonDefModule =
10174 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
10175 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10176 << D << getOwningModuleNameForDiagnostic(D)
10177 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10178
10179 if (Candidates.empty())
10180 Diag(cast<Decl>(CanonDef)->getLocation(),
10181 diag::note_module_odr_violation_no_possible_decls) << D;
10182 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010183 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10184 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +000010185 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +000010186 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +000010187 }
10188
10189 DiagnosedOdrMergeFailures.insert(CanonDef);
10190 }
10191 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010192
Richard Trieuab4d7302018-07-25 22:52:05 +000010193 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
10194 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010195 return;
10196
10197 // Ensure we don't accidentally recursively enter deserialization while
10198 // we're producing our diagnostics.
10199 Deserializing RecursionGuard(this);
10200
Richard Trieue6caa262017-12-23 00:41:01 +000010201 // Common code for hashing helpers.
10202 ODRHash Hash;
10203 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
10204 Hash.clear();
10205 Hash.AddQualType(Ty);
10206 return Hash.CalculateHash();
10207 };
10208
10209 auto ComputeODRHash = [&Hash](const Stmt *S) {
10210 assert(S);
10211 Hash.clear();
10212 Hash.AddStmt(S);
10213 return Hash.CalculateHash();
10214 };
10215
10216 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
10217 assert(D);
10218 Hash.clear();
10219 Hash.AddSubDecl(D);
10220 return Hash.CalculateHash();
10221 };
10222
Richard Trieu7282d322018-04-25 00:31:15 +000010223 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
10224 Hash.clear();
10225 Hash.AddTemplateArgument(TA);
10226 return Hash.CalculateHash();
10227 };
10228
Richard Trieu9359e8f2018-05-30 01:12:26 +000010229 auto ComputeTemplateParameterListODRHash =
10230 [&Hash](const TemplateParameterList *TPL) {
10231 assert(TPL);
10232 Hash.clear();
10233 Hash.AddTemplateParameterList(TPL);
10234 return Hash.CalculateHash();
10235 };
10236
Richard Smithcd45dbc2014-04-19 03:48:30 +000010237 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010238 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010239 // If we've already pointed out a specific problem with this class, don't
10240 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010241 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010242 continue;
10243
10244 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010245 CXXRecordDecl *FirstRecord = Merge.first;
10246 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010247 for (auto &RecordPair : Merge.second) {
10248 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010249 // Multiple different declarations got merged together; tell the user
10250 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010251 if (FirstRecord == SecondRecord)
10252 continue;
10253
10254 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010255
10256 auto *FirstDD = FirstRecord->DefinitionData;
10257 auto *SecondDD = RecordPair.second;
10258
10259 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10260
10261 // Diagnostics from DefinitionData are emitted here.
10262 if (FirstDD != SecondDD) {
10263 enum ODRDefinitionDataDifference {
10264 NumBases,
10265 NumVBases,
10266 BaseType,
10267 BaseVirtual,
10268 BaseAccess,
10269 };
10270 auto ODRDiagError = [FirstRecord, &FirstModule,
10271 this](SourceLocation Loc, SourceRange Range,
10272 ODRDefinitionDataDifference DiffType) {
10273 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10274 << FirstRecord << FirstModule.empty() << FirstModule << Range
10275 << DiffType;
10276 };
10277 auto ODRDiagNote = [&SecondModule,
10278 this](SourceLocation Loc, SourceRange Range,
10279 ODRDefinitionDataDifference DiffType) {
10280 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10281 << SecondModule << Range << DiffType;
10282 };
10283
Richard Trieue13eabe2017-09-30 02:19:17 +000010284 unsigned FirstNumBases = FirstDD->NumBases;
10285 unsigned FirstNumVBases = FirstDD->NumVBases;
10286 unsigned SecondNumBases = SecondDD->NumBases;
10287 unsigned SecondNumVBases = SecondDD->NumVBases;
10288
10289 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10290 unsigned NumBases = DD->NumBases;
10291 if (NumBases == 0) return SourceRange();
10292 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010293 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010294 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010295 };
10296
10297 if (FirstNumBases != SecondNumBases) {
10298 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10299 NumBases)
10300 << FirstNumBases;
10301 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10302 NumBases)
10303 << SecondNumBases;
10304 Diagnosed = true;
10305 break;
10306 }
10307
10308 if (FirstNumVBases != SecondNumVBases) {
10309 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10310 NumVBases)
10311 << FirstNumVBases;
10312 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10313 NumVBases)
10314 << SecondNumVBases;
10315 Diagnosed = true;
10316 break;
10317 }
10318
10319 auto FirstBases = FirstDD->bases();
10320 auto SecondBases = SecondDD->bases();
10321 unsigned i = 0;
10322 for (i = 0; i < FirstNumBases; ++i) {
10323 auto FirstBase = FirstBases[i];
10324 auto SecondBase = SecondBases[i];
10325 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10326 ComputeQualTypeODRHash(SecondBase.getType())) {
10327 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10328 BaseType)
10329 << (i + 1) << FirstBase.getType();
10330 ODRDiagNote(SecondRecord->getLocation(),
10331 SecondBase.getSourceRange(), BaseType)
10332 << (i + 1) << SecondBase.getType();
10333 break;
10334 }
10335
10336 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10337 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10338 BaseVirtual)
10339 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10340 ODRDiagNote(SecondRecord->getLocation(),
10341 SecondBase.getSourceRange(), BaseVirtual)
10342 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10343 break;
10344 }
10345
10346 if (FirstBase.getAccessSpecifierAsWritten() !=
10347 SecondBase.getAccessSpecifierAsWritten()) {
10348 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10349 BaseAccess)
10350 << (i + 1) << FirstBase.getType()
10351 << (int)FirstBase.getAccessSpecifierAsWritten();
10352 ODRDiagNote(SecondRecord->getLocation(),
10353 SecondBase.getSourceRange(), BaseAccess)
10354 << (i + 1) << SecondBase.getType()
10355 << (int)SecondBase.getAccessSpecifierAsWritten();
10356 break;
10357 }
10358 }
10359
10360 if (i != FirstNumBases) {
10361 Diagnosed = true;
10362 break;
10363 }
10364 }
10365
Richard Trieue7f7ed22017-02-22 01:11:25 +000010366 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +000010367
10368 const ClassTemplateDecl *FirstTemplate =
10369 FirstRecord->getDescribedClassTemplate();
10370 const ClassTemplateDecl *SecondTemplate =
10371 SecondRecord->getDescribedClassTemplate();
10372
10373 assert(!FirstTemplate == !SecondTemplate &&
10374 "Both pointers should be null or non-null");
10375
10376 enum ODRTemplateDifference {
10377 ParamEmptyName,
10378 ParamName,
10379 ParamSingleDefaultArgument,
10380 ParamDifferentDefaultArgument,
10381 };
10382
10383 if (FirstTemplate && SecondTemplate) {
10384 DeclHashes FirstTemplateHashes;
10385 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010386
10387 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010388 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10389 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010390 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010391 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010392 }
10393 };
10394
10395 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10396 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10397
10398 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10399 "Number of template parameters should be equal.");
10400
10401 auto FirstIt = FirstTemplateHashes.begin();
10402 auto FirstEnd = FirstTemplateHashes.end();
10403 auto SecondIt = SecondTemplateHashes.begin();
10404 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10405 if (FirstIt->second == SecondIt->second)
10406 continue;
10407
10408 auto ODRDiagError = [FirstRecord, &FirstModule,
10409 this](SourceLocation Loc, SourceRange Range,
10410 ODRTemplateDifference DiffType) {
10411 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10412 << FirstRecord << FirstModule.empty() << FirstModule << Range
10413 << DiffType;
10414 };
10415 auto ODRDiagNote = [&SecondModule,
10416 this](SourceLocation Loc, SourceRange Range,
10417 ODRTemplateDifference DiffType) {
10418 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10419 << SecondModule << Range << DiffType;
10420 };
10421
Vedant Kumar48b4f762018-04-14 01:40:48 +000010422 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10423 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010424
10425 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10426 "Parameter Decl's should be the same kind.");
10427
10428 DeclarationName FirstName = FirstDecl->getDeclName();
10429 DeclarationName SecondName = SecondDecl->getDeclName();
10430
10431 if (FirstName != SecondName) {
10432 const bool FirstNameEmpty =
10433 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10434 const bool SecondNameEmpty =
10435 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10436 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10437 "Both template parameters cannot be unnamed.");
10438 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10439 FirstNameEmpty ? ParamEmptyName : ParamName)
10440 << FirstName;
10441 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10442 SecondNameEmpty ? ParamEmptyName : ParamName)
10443 << SecondName;
10444 break;
10445 }
10446
10447 switch (FirstDecl->getKind()) {
10448 default:
10449 llvm_unreachable("Invalid template parameter type.");
10450 case Decl::TemplateTypeParm: {
10451 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10452 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10453 const bool HasFirstDefaultArgument =
10454 FirstParam->hasDefaultArgument() &&
10455 !FirstParam->defaultArgumentWasInherited();
10456 const bool HasSecondDefaultArgument =
10457 SecondParam->hasDefaultArgument() &&
10458 !SecondParam->defaultArgumentWasInherited();
10459
10460 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10461 ODRDiagError(FirstDecl->getLocation(),
10462 FirstDecl->getSourceRange(),
10463 ParamSingleDefaultArgument)
10464 << HasFirstDefaultArgument;
10465 ODRDiagNote(SecondDecl->getLocation(),
10466 SecondDecl->getSourceRange(),
10467 ParamSingleDefaultArgument)
10468 << HasSecondDefaultArgument;
10469 break;
10470 }
10471
10472 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10473 "Expecting default arguments.");
10474
10475 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10476 ParamDifferentDefaultArgument);
10477 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10478 ParamDifferentDefaultArgument);
10479
10480 break;
10481 }
10482 case Decl::NonTypeTemplateParm: {
10483 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10484 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10485 const bool HasFirstDefaultArgument =
10486 FirstParam->hasDefaultArgument() &&
10487 !FirstParam->defaultArgumentWasInherited();
10488 const bool HasSecondDefaultArgument =
10489 SecondParam->hasDefaultArgument() &&
10490 !SecondParam->defaultArgumentWasInherited();
10491
10492 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10493 ODRDiagError(FirstDecl->getLocation(),
10494 FirstDecl->getSourceRange(),
10495 ParamSingleDefaultArgument)
10496 << HasFirstDefaultArgument;
10497 ODRDiagNote(SecondDecl->getLocation(),
10498 SecondDecl->getSourceRange(),
10499 ParamSingleDefaultArgument)
10500 << HasSecondDefaultArgument;
10501 break;
10502 }
10503
10504 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10505 "Expecting default arguments.");
10506
10507 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10508 ParamDifferentDefaultArgument);
10509 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10510 ParamDifferentDefaultArgument);
10511
10512 break;
10513 }
10514 case Decl::TemplateTemplateParm: {
10515 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10516 const auto *SecondParam =
10517 cast<TemplateTemplateParmDecl>(SecondDecl);
10518 const bool HasFirstDefaultArgument =
10519 FirstParam->hasDefaultArgument() &&
10520 !FirstParam->defaultArgumentWasInherited();
10521 const bool HasSecondDefaultArgument =
10522 SecondParam->hasDefaultArgument() &&
10523 !SecondParam->defaultArgumentWasInherited();
10524
10525 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10526 ODRDiagError(FirstDecl->getLocation(),
10527 FirstDecl->getSourceRange(),
10528 ParamSingleDefaultArgument)
10529 << HasFirstDefaultArgument;
10530 ODRDiagNote(SecondDecl->getLocation(),
10531 SecondDecl->getSourceRange(),
10532 ParamSingleDefaultArgument)
10533 << HasSecondDefaultArgument;
10534 break;
10535 }
10536
10537 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10538 "Expecting default arguments.");
10539
10540 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10541 ParamDifferentDefaultArgument);
10542 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10543 ParamDifferentDefaultArgument);
10544
10545 break;
10546 }
10547 }
10548
10549 break;
10550 }
10551
10552 if (FirstIt != FirstEnd) {
10553 Diagnosed = true;
10554 break;
10555 }
10556 }
10557
Richard Trieue7f7ed22017-02-22 01:11:25 +000010558 DeclHashes FirstHashes;
10559 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010560
Richard Trieue6caa262017-12-23 00:41:01 +000010561 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10562 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010563 for (auto *D : Record->decls()) {
10564 // Due to decl merging, the first CXXRecordDecl is the parent of
10565 // Decls in both records.
10566 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10567 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010568 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010569 }
10570 };
10571 PopulateHashes(FirstHashes, FirstRecord);
10572 PopulateHashes(SecondHashes, SecondRecord);
10573
10574 // Used with err_module_odr_violation_mismatch_decl and
10575 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010576 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010577 enum {
10578 EndOfClass,
10579 PublicSpecifer,
10580 PrivateSpecifer,
10581 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010582 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010583 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010584 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010585 TypeAlias,
10586 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010587 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010588 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010589 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010590 Other
10591 } FirstDiffType = Other,
10592 SecondDiffType = Other;
10593
10594 auto DifferenceSelector = [](Decl *D) {
10595 assert(D && "valid Decl required");
10596 switch (D->getKind()) {
10597 default:
10598 return Other;
10599 case Decl::AccessSpec:
10600 switch (D->getAccess()) {
10601 case AS_public:
10602 return PublicSpecifer;
10603 case AS_private:
10604 return PrivateSpecifer;
10605 case AS_protected:
10606 return ProtectedSpecifer;
10607 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010608 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010609 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010610 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010611 case Decl::StaticAssert:
10612 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010613 case Decl::Field:
10614 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010615 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010616 case Decl::CXXConstructor:
10617 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010618 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010619 case Decl::TypeAlias:
10620 return TypeAlias;
10621 case Decl::Typedef:
10622 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010623 case Decl::Var:
10624 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010625 case Decl::Friend:
10626 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010627 case Decl::FunctionTemplate:
10628 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010629 }
10630 };
10631
10632 Decl *FirstDecl = nullptr;
10633 Decl *SecondDecl = nullptr;
10634 auto FirstIt = FirstHashes.begin();
10635 auto SecondIt = SecondHashes.begin();
10636
10637 // If there is a diagnoseable difference, FirstDiffType and
10638 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10639 // filled in if not EndOfClass.
10640 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010641 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10642 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010643 ++FirstIt;
10644 ++SecondIt;
10645 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010646 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010647
Richard Trieue7f7ed22017-02-22 01:11:25 +000010648 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10649 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10650
10651 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10652 SecondDiffType =
10653 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10654
10655 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010656 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010657
10658 if (FirstDiffType == Other || SecondDiffType == Other) {
10659 // Reaching this point means an unexpected Decl was encountered
10660 // or no difference was detected. This causes a generic error
10661 // message to be emitted.
10662 Diag(FirstRecord->getLocation(),
10663 diag::err_module_odr_violation_different_definitions)
10664 << FirstRecord << FirstModule.empty() << FirstModule;
10665
Richard Trieuca48d362017-06-21 01:43:13 +000010666 if (FirstDecl) {
10667 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10668 << FirstRecord << FirstDecl->getSourceRange();
10669 }
10670
Richard Trieue7f7ed22017-02-22 01:11:25 +000010671 Diag(SecondRecord->getLocation(),
10672 diag::note_module_odr_violation_different_definitions)
10673 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010674
10675 if (SecondDecl) {
10676 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10677 << SecondDecl->getSourceRange();
10678 }
10679
Richard Trieue7f7ed22017-02-22 01:11:25 +000010680 Diagnosed = true;
10681 break;
10682 }
10683
10684 if (FirstDiffType != SecondDiffType) {
10685 SourceLocation FirstLoc;
10686 SourceRange FirstRange;
10687 if (FirstDiffType == EndOfClass) {
10688 FirstLoc = FirstRecord->getBraceRange().getEnd();
10689 } else {
10690 FirstLoc = FirstIt->first->getLocation();
10691 FirstRange = FirstIt->first->getSourceRange();
10692 }
10693 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10694 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10695 << FirstDiffType;
10696
10697 SourceLocation SecondLoc;
10698 SourceRange SecondRange;
10699 if (SecondDiffType == EndOfClass) {
10700 SecondLoc = SecondRecord->getBraceRange().getEnd();
10701 } else {
10702 SecondLoc = SecondDecl->getLocation();
10703 SecondRange = SecondDecl->getSourceRange();
10704 }
10705 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10706 << SecondModule << SecondRange << SecondDiffType;
10707 Diagnosed = true;
10708 break;
10709 }
10710
Richard Trieu639d7b62017-02-22 22:22:42 +000010711 assert(FirstDiffType == SecondDiffType);
10712
10713 // Used with err_module_odr_violation_mismatch_decl_diff and
10714 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010715 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010716 StaticAssertCondition,
10717 StaticAssertMessage,
10718 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010719 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010720 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010721 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010722 FieldDifferentWidthBitField,
10723 FieldSingleMutable,
10724 FieldSingleInitializer,
10725 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010726 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010727 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010728 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010729 MethodVirtual,
10730 MethodStatic,
10731 MethodVolatile,
10732 MethodConst,
10733 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010734 MethodNumberParameters,
10735 MethodParameterType,
10736 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010737 MethodParameterSingleDefaultArgument,
10738 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010739 MethodNoTemplateArguments,
10740 MethodDifferentNumberTemplateArguments,
10741 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010742 MethodSingleBody,
10743 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010744 TypedefName,
10745 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010746 VarName,
10747 VarType,
10748 VarSingleInitializer,
10749 VarDifferentInitializer,
10750 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010751 FriendTypeFunction,
10752 FriendType,
10753 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010754 FunctionTemplateDifferentNumberParameters,
10755 FunctionTemplateParameterDifferentKind,
10756 FunctionTemplateParameterName,
10757 FunctionTemplateParameterSingleDefaultArgument,
10758 FunctionTemplateParameterDifferentDefaultArgument,
10759 FunctionTemplateParameterDifferentType,
10760 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010761 };
10762
10763 // These lambdas have the common portions of the ODR diagnostics. This
10764 // has the same return as Diag(), so addition parameters can be passed
10765 // in with operator<<
10766 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10767 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10768 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10769 << FirstRecord << FirstModule.empty() << FirstModule << Range
10770 << DiffType;
10771 };
10772 auto ODRDiagNote = [&SecondModule, this](
10773 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10774 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10775 << SecondModule << Range << DiffType;
10776 };
10777
Richard Trieu639d7b62017-02-22 22:22:42 +000010778 switch (FirstDiffType) {
10779 case Other:
10780 case EndOfClass:
10781 case PublicSpecifer:
10782 case PrivateSpecifer:
10783 case ProtectedSpecifer:
10784 llvm_unreachable("Invalid diff type");
10785
10786 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010787 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10788 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010789
10790 Expr *FirstExpr = FirstSA->getAssertExpr();
10791 Expr *SecondExpr = SecondSA->getAssertExpr();
10792 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10793 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10794 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010795 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010796 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010797 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10798 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010799 Diagnosed = true;
10800 break;
10801 }
10802
10803 StringLiteral *FirstStr = FirstSA->getMessage();
10804 StringLiteral *SecondStr = SecondSA->getMessage();
10805 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10806 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10807 SourceLocation FirstLoc, SecondLoc;
10808 SourceRange FirstRange, SecondRange;
10809 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010810 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010811 FirstRange = FirstStr->getSourceRange();
10812 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010813 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010814 FirstRange = FirstSA->getSourceRange();
10815 }
10816 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010817 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010818 SecondRange = SecondStr->getSourceRange();
10819 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010820 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010821 SecondRange = SecondSA->getSourceRange();
10822 }
10823 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10824 << (FirstStr == nullptr);
10825 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10826 << (SecondStr == nullptr);
10827 Diagnosed = true;
10828 break;
10829 }
10830
10831 if (FirstStr && SecondStr &&
10832 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010833 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010834 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010835 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010836 StaticAssertMessage);
10837 Diagnosed = true;
10838 break;
10839 }
10840 break;
10841 }
Richard Trieud0786092017-02-23 00:23:01 +000010842 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010843 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10844 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010845 IdentifierInfo *FirstII = FirstField->getIdentifier();
10846 IdentifierInfo *SecondII = SecondField->getIdentifier();
10847 if (FirstII->getName() != SecondII->getName()) {
10848 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10849 FieldName)
10850 << FirstII;
10851 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10852 FieldName)
10853 << SecondII;
10854
10855 Diagnosed = true;
10856 break;
10857 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010858
Richard Smithdbafb6c2017-06-29 23:23:46 +000010859 assert(getContext().hasSameType(FirstField->getType(),
10860 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010861
10862 QualType FirstType = FirstField->getType();
10863 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010864 if (ComputeQualTypeODRHash(FirstType) !=
10865 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010866 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10867 FieldTypeName)
10868 << FirstII << FirstType;
10869 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10870 FieldTypeName)
10871 << SecondII << SecondType;
10872
10873 Diagnosed = true;
10874 break;
10875 }
10876
Richard Trieu93772fc2017-02-24 20:59:28 +000010877 const bool IsFirstBitField = FirstField->isBitField();
10878 const bool IsSecondBitField = SecondField->isBitField();
10879 if (IsFirstBitField != IsSecondBitField) {
10880 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10881 FieldSingleBitField)
10882 << FirstII << IsFirstBitField;
10883 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10884 FieldSingleBitField)
10885 << SecondII << IsSecondBitField;
10886 Diagnosed = true;
10887 break;
10888 }
10889
10890 if (IsFirstBitField && IsSecondBitField) {
10891 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10892 FieldDifferentWidthBitField)
10893 << FirstII << FirstField->getBitWidth()->getSourceRange();
10894 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10895 FieldDifferentWidthBitField)
10896 << SecondII << SecondField->getBitWidth()->getSourceRange();
10897 Diagnosed = true;
10898 break;
10899 }
10900
Richard Trieu8d543e22017-02-24 23:35:37 +000010901 const bool IsFirstMutable = FirstField->isMutable();
10902 const bool IsSecondMutable = SecondField->isMutable();
10903 if (IsFirstMutable != IsSecondMutable) {
10904 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10905 FieldSingleMutable)
10906 << FirstII << IsFirstMutable;
10907 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10908 FieldSingleMutable)
10909 << SecondII << IsSecondMutable;
10910 Diagnosed = true;
10911 break;
10912 }
10913
10914 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10915 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10916 if ((!FirstInitializer && SecondInitializer) ||
10917 (FirstInitializer && !SecondInitializer)) {
10918 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10919 FieldSingleInitializer)
10920 << FirstII << (FirstInitializer != nullptr);
10921 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10922 FieldSingleInitializer)
10923 << SecondII << (SecondInitializer != nullptr);
10924 Diagnosed = true;
10925 break;
10926 }
10927
10928 if (FirstInitializer && SecondInitializer) {
10929 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10930 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10931 if (FirstInitHash != SecondInitHash) {
10932 ODRDiagError(FirstField->getLocation(),
10933 FirstField->getSourceRange(),
10934 FieldDifferentInitializers)
10935 << FirstII << FirstInitializer->getSourceRange();
10936 ODRDiagNote(SecondField->getLocation(),
10937 SecondField->getSourceRange(),
10938 FieldDifferentInitializers)
10939 << SecondII << SecondInitializer->getSourceRange();
10940 Diagnosed = true;
10941 break;
10942 }
10943 }
10944
Richard Trieud0786092017-02-23 00:23:01 +000010945 break;
10946 }
Richard Trieu48143742017-02-28 21:24:38 +000010947 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010948 enum {
10949 DiagMethod,
10950 DiagConstructor,
10951 DiagDestructor,
10952 } FirstMethodType,
10953 SecondMethodType;
10954 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10955 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10956 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10957 return DiagMethod;
10958 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010959 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10960 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010961 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10962 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010963 auto FirstName = FirstMethod->getDeclName();
10964 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010965 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010966 ODRDiagError(FirstMethod->getLocation(),
10967 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010968 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010969 ODRDiagNote(SecondMethod->getLocation(),
10970 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010971 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010972
10973 Diagnosed = true;
10974 break;
10975 }
10976
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010977 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10978 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010979 if (FirstDeleted != SecondDeleted) {
10980 ODRDiagError(FirstMethod->getLocation(),
10981 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010982 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010983
10984 ODRDiagNote(SecondMethod->getLocation(),
10985 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010986 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010987 Diagnosed = true;
10988 break;
10989 }
10990
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010991 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10992 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10993 if (FirstDefaulted != SecondDefaulted) {
10994 ODRDiagError(FirstMethod->getLocation(),
10995 FirstMethod->getSourceRange(), MethodDefaulted)
10996 << FirstMethodType << FirstName << FirstDefaulted;
10997
10998 ODRDiagNote(SecondMethod->getLocation(),
10999 SecondMethod->getSourceRange(), MethodDefaulted)
11000 << SecondMethodType << SecondName << SecondDefaulted;
11001 Diagnosed = true;
11002 break;
11003 }
11004
Richard Trieu583e2c12017-03-04 00:08:58 +000011005 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
11006 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
11007 const bool FirstPure = FirstMethod->isPure();
11008 const bool SecondPure = SecondMethod->isPure();
11009 if ((FirstVirtual || SecondVirtual) &&
11010 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
11011 ODRDiagError(FirstMethod->getLocation(),
11012 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000011013 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000011014 ODRDiagNote(SecondMethod->getLocation(),
11015 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000011016 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000011017 Diagnosed = true;
11018 break;
11019 }
11020
11021 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
11022 // FirstDecl is the canonical Decl of SecondDecl, so the storage
11023 // class needs to be checked instead.
11024 const auto FirstStorage = FirstMethod->getStorageClass();
11025 const auto SecondStorage = SecondMethod->getStorageClass();
11026 const bool FirstStatic = FirstStorage == SC_Static;
11027 const bool SecondStatic = SecondStorage == SC_Static;
11028 if (FirstStatic != SecondStatic) {
11029 ODRDiagError(FirstMethod->getLocation(),
11030 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000011031 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000011032 ODRDiagNote(SecondMethod->getLocation(),
11033 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000011034 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000011035 Diagnosed = true;
11036 break;
11037 }
11038
11039 const bool FirstVolatile = FirstMethod->isVolatile();
11040 const bool SecondVolatile = SecondMethod->isVolatile();
11041 if (FirstVolatile != SecondVolatile) {
11042 ODRDiagError(FirstMethod->getLocation(),
11043 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000011044 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000011045 ODRDiagNote(SecondMethod->getLocation(),
11046 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000011047 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000011048 Diagnosed = true;
11049 break;
11050 }
11051
11052 const bool FirstConst = FirstMethod->isConst();
11053 const bool SecondConst = SecondMethod->isConst();
11054 if (FirstConst != SecondConst) {
11055 ODRDiagError(FirstMethod->getLocation(),
11056 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000011057 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000011058 ODRDiagNote(SecondMethod->getLocation(),
11059 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000011060 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000011061 Diagnosed = true;
11062 break;
11063 }
11064
11065 const bool FirstInline = FirstMethod->isInlineSpecified();
11066 const bool SecondInline = SecondMethod->isInlineSpecified();
11067 if (FirstInline != SecondInline) {
11068 ODRDiagError(FirstMethod->getLocation(),
11069 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011070 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011071 ODRDiagNote(SecondMethod->getLocation(),
11072 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011073 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011074 Diagnosed = true;
11075 break;
11076 }
11077
Richard Trieu02552272017-05-02 23:58:52 +000011078 const unsigned FirstNumParameters = FirstMethod->param_size();
11079 const unsigned SecondNumParameters = SecondMethod->param_size();
11080 if (FirstNumParameters != SecondNumParameters) {
11081 ODRDiagError(FirstMethod->getLocation(),
11082 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011083 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011084 ODRDiagNote(SecondMethod->getLocation(),
11085 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011086 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011087 Diagnosed = true;
11088 break;
11089 }
11090
11091 // Need this status boolean to know when break out of the switch.
11092 bool ParameterMismatch = false;
11093 for (unsigned I = 0; I < FirstNumParameters; ++I) {
11094 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
11095 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
11096
11097 QualType FirstParamType = FirstParam->getType();
11098 QualType SecondParamType = SecondParam->getType();
11099 if (FirstParamType != SecondParamType &&
11100 ComputeQualTypeODRHash(FirstParamType) !=
11101 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011102 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011103 FirstParamType->getAs<DecayedType>()) {
11104 ODRDiagError(FirstMethod->getLocation(),
11105 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011106 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11107 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000011108 } else {
11109 ODRDiagError(FirstMethod->getLocation(),
11110 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011111 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11112 << false;
Richard Trieu02552272017-05-02 23:58:52 +000011113 }
11114
Vedant Kumar48b4f762018-04-14 01:40:48 +000011115 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011116 SecondParamType->getAs<DecayedType>()) {
11117 ODRDiagNote(SecondMethod->getLocation(),
11118 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011119 << SecondMethodType << SecondName << (I + 1)
11120 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000011121 << ParamDecayedType->getOriginalType();
11122 } else {
11123 ODRDiagNote(SecondMethod->getLocation(),
11124 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011125 << SecondMethodType << SecondName << (I + 1)
11126 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000011127 }
11128 ParameterMismatch = true;
11129 break;
11130 }
11131
11132 DeclarationName FirstParamName = FirstParam->getDeclName();
11133 DeclarationName SecondParamName = SecondParam->getDeclName();
11134 if (FirstParamName != SecondParamName) {
11135 ODRDiagError(FirstMethod->getLocation(),
11136 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011137 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011138 ODRDiagNote(SecondMethod->getLocation(),
11139 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011140 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011141 ParameterMismatch = true;
11142 break;
11143 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011144
11145 const Expr *FirstInit = FirstParam->getInit();
11146 const Expr *SecondInit = SecondParam->getInit();
11147 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11148 ODRDiagError(FirstMethod->getLocation(),
11149 FirstMethod->getSourceRange(),
11150 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011151 << FirstMethodType << FirstName << (I + 1)
11152 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011153 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11154 ODRDiagNote(SecondMethod->getLocation(),
11155 SecondMethod->getSourceRange(),
11156 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011157 << SecondMethodType << SecondName << (I + 1)
11158 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011159 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11160 ParameterMismatch = true;
11161 break;
11162 }
11163
11164 if (FirstInit && SecondInit &&
11165 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11166 ODRDiagError(FirstMethod->getLocation(),
11167 FirstMethod->getSourceRange(),
11168 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011169 << FirstMethodType << FirstName << (I + 1)
11170 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011171 ODRDiagNote(SecondMethod->getLocation(),
11172 SecondMethod->getSourceRange(),
11173 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011174 << SecondMethodType << SecondName << (I + 1)
11175 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011176 ParameterMismatch = true;
11177 break;
11178
11179 }
Richard Trieu02552272017-05-02 23:58:52 +000011180 }
11181
11182 if (ParameterMismatch) {
11183 Diagnosed = true;
11184 break;
11185 }
11186
Richard Trieu7282d322018-04-25 00:31:15 +000011187 const auto *FirstTemplateArgs =
11188 FirstMethod->getTemplateSpecializationArgs();
11189 const auto *SecondTemplateArgs =
11190 SecondMethod->getTemplateSpecializationArgs();
11191
11192 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
11193 (!FirstTemplateArgs && SecondTemplateArgs)) {
11194 ODRDiagError(FirstMethod->getLocation(),
11195 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
11196 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
11197 ODRDiagNote(SecondMethod->getLocation(),
11198 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
11199 << SecondMethodType << SecondName
11200 << (SecondTemplateArgs != nullptr);
11201
11202 Diagnosed = true;
11203 break;
11204 }
11205
11206 if (FirstTemplateArgs && SecondTemplateArgs) {
11207 // Remove pack expansions from argument list.
11208 auto ExpandTemplateArgumentList =
11209 [](const TemplateArgumentList *TAL) {
11210 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
11211 for (const TemplateArgument &TA : TAL->asArray()) {
11212 if (TA.getKind() != TemplateArgument::Pack) {
11213 ExpandedList.push_back(&TA);
11214 continue;
11215 }
11216 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
11217 ExpandedList.push_back(&PackTA);
11218 }
11219 }
11220 return ExpandedList;
11221 };
11222 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
11223 ExpandTemplateArgumentList(FirstTemplateArgs);
11224 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
11225 ExpandTemplateArgumentList(SecondTemplateArgs);
11226
11227 if (FirstExpandedList.size() != SecondExpandedList.size()) {
11228 ODRDiagError(FirstMethod->getLocation(),
11229 FirstMethod->getSourceRange(),
11230 MethodDifferentNumberTemplateArguments)
11231 << FirstMethodType << FirstName
11232 << (unsigned)FirstExpandedList.size();
11233 ODRDiagNote(SecondMethod->getLocation(),
11234 SecondMethod->getSourceRange(),
11235 MethodDifferentNumberTemplateArguments)
11236 << SecondMethodType << SecondName
11237 << (unsigned)SecondExpandedList.size();
11238
11239 Diagnosed = true;
11240 break;
11241 }
11242
11243 bool TemplateArgumentMismatch = false;
11244 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
11245 const TemplateArgument &FirstTA = *FirstExpandedList[i],
11246 &SecondTA = *SecondExpandedList[i];
11247 if (ComputeTemplateArgumentODRHash(FirstTA) ==
11248 ComputeTemplateArgumentODRHash(SecondTA)) {
11249 continue;
11250 }
11251
11252 ODRDiagError(FirstMethod->getLocation(),
11253 FirstMethod->getSourceRange(),
11254 MethodDifferentTemplateArgument)
11255 << FirstMethodType << FirstName << FirstTA << i + 1;
11256 ODRDiagNote(SecondMethod->getLocation(),
11257 SecondMethod->getSourceRange(),
11258 MethodDifferentTemplateArgument)
11259 << SecondMethodType << SecondName << SecondTA << i + 1;
11260
11261 TemplateArgumentMismatch = true;
11262 break;
11263 }
11264
11265 if (TemplateArgumentMismatch) {
11266 Diagnosed = true;
11267 break;
11268 }
11269 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000011270
11271 // Compute the hash of the method as if it has no body.
11272 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
11273 Hash.clear();
11274 Hash.AddFunctionDecl(D, true /*SkipBody*/);
11275 return Hash.CalculateHash();
11276 };
11277
11278 // Compare the hash generated to the hash stored. A difference means
11279 // that a body was present in the original source. Due to merging,
11280 // the stardard way of detecting a body will not work.
11281 const bool HasFirstBody =
11282 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
11283 const bool HasSecondBody =
11284 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
11285
11286 if (HasFirstBody != HasSecondBody) {
11287 ODRDiagError(FirstMethod->getLocation(),
11288 FirstMethod->getSourceRange(), MethodSingleBody)
11289 << FirstMethodType << FirstName << HasFirstBody;
11290 ODRDiagNote(SecondMethod->getLocation(),
11291 SecondMethod->getSourceRange(), MethodSingleBody)
11292 << SecondMethodType << SecondName << HasSecondBody;
11293 Diagnosed = true;
11294 break;
11295 }
11296
11297 if (HasFirstBody && HasSecondBody) {
11298 ODRDiagError(FirstMethod->getLocation(),
11299 FirstMethod->getSourceRange(), MethodDifferentBody)
11300 << FirstMethodType << FirstName;
11301 ODRDiagNote(SecondMethod->getLocation(),
11302 SecondMethod->getSourceRange(), MethodDifferentBody)
11303 << SecondMethodType << SecondName;
11304 Diagnosed = true;
11305 break;
11306 }
11307
Richard Trieu48143742017-02-28 21:24:38 +000011308 break;
11309 }
Richard Trieu11d566a2017-06-12 21:58:22 +000011310 case TypeAlias:
11311 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011312 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
11313 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000011314 auto FirstName = FirstTD->getDeclName();
11315 auto SecondName = SecondTD->getDeclName();
11316 if (FirstName != SecondName) {
11317 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11318 TypedefName)
11319 << (FirstDiffType == TypeAlias) << FirstName;
11320 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11321 TypedefName)
11322 << (FirstDiffType == TypeAlias) << SecondName;
11323 Diagnosed = true;
11324 break;
11325 }
11326
11327 QualType FirstType = FirstTD->getUnderlyingType();
11328 QualType SecondType = SecondTD->getUnderlyingType();
11329 if (ComputeQualTypeODRHash(FirstType) !=
11330 ComputeQualTypeODRHash(SecondType)) {
11331 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11332 TypedefType)
11333 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
11334 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11335 TypedefType)
11336 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
11337 Diagnosed = true;
11338 break;
11339 }
11340 break;
11341 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011342 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011343 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
11344 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000011345 auto FirstName = FirstVD->getDeclName();
11346 auto SecondName = SecondVD->getDeclName();
11347 if (FirstName != SecondName) {
11348 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11349 VarName)
11350 << FirstName;
11351 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11352 VarName)
11353 << SecondName;
11354 Diagnosed = true;
11355 break;
11356 }
11357
11358 QualType FirstType = FirstVD->getType();
11359 QualType SecondType = SecondVD->getType();
11360 if (ComputeQualTypeODRHash(FirstType) !=
11361 ComputeQualTypeODRHash(SecondType)) {
11362 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11363 VarType)
11364 << FirstName << FirstType;
11365 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11366 VarType)
11367 << SecondName << SecondType;
11368 Diagnosed = true;
11369 break;
11370 }
11371
11372 const Expr *FirstInit = FirstVD->getInit();
11373 const Expr *SecondInit = SecondVD->getInit();
11374 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11375 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11376 VarSingleInitializer)
11377 << FirstName << (FirstInit == nullptr)
11378 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
11379 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11380 VarSingleInitializer)
11381 << SecondName << (SecondInit == nullptr)
11382 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11383 Diagnosed = true;
11384 break;
11385 }
11386
11387 if (FirstInit && SecondInit &&
11388 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11389 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11390 VarDifferentInitializer)
11391 << FirstName << FirstInit->getSourceRange();
11392 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11393 VarDifferentInitializer)
11394 << SecondName << SecondInit->getSourceRange();
11395 Diagnosed = true;
11396 break;
11397 }
11398
11399 const bool FirstIsConstexpr = FirstVD->isConstexpr();
11400 const bool SecondIsConstexpr = SecondVD->isConstexpr();
11401 if (FirstIsConstexpr != SecondIsConstexpr) {
11402 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11403 VarConstexpr)
11404 << FirstName << FirstIsConstexpr;
11405 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11406 VarConstexpr)
11407 << SecondName << SecondIsConstexpr;
11408 Diagnosed = true;
11409 break;
11410 }
11411 break;
11412 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000011413 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011414 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
11415 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000011416
11417 NamedDecl *FirstND = FirstFriend->getFriendDecl();
11418 NamedDecl *SecondND = SecondFriend->getFriendDecl();
11419
11420 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
11421 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
11422
11423 if (FirstND && SecondND) {
11424 ODRDiagError(FirstFriend->getFriendLoc(),
11425 FirstFriend->getSourceRange(), FriendFunction)
11426 << FirstND;
11427 ODRDiagNote(SecondFriend->getFriendLoc(),
11428 SecondFriend->getSourceRange(), FriendFunction)
11429 << SecondND;
11430
11431 Diagnosed = true;
11432 break;
11433 }
11434
11435 if (FirstTSI && SecondTSI) {
11436 QualType FirstFriendType = FirstTSI->getType();
11437 QualType SecondFriendType = SecondTSI->getType();
11438 assert(ComputeQualTypeODRHash(FirstFriendType) !=
11439 ComputeQualTypeODRHash(SecondFriendType));
11440 ODRDiagError(FirstFriend->getFriendLoc(),
11441 FirstFriend->getSourceRange(), FriendType)
11442 << FirstFriendType;
11443 ODRDiagNote(SecondFriend->getFriendLoc(),
11444 SecondFriend->getSourceRange(), FriendType)
11445 << SecondFriendType;
11446 Diagnosed = true;
11447 break;
11448 }
11449
11450 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
11451 FriendTypeFunction)
11452 << (FirstTSI == nullptr);
11453 ODRDiagNote(SecondFriend->getFriendLoc(),
11454 SecondFriend->getSourceRange(), FriendTypeFunction)
11455 << (SecondTSI == nullptr);
11456
11457 Diagnosed = true;
11458 break;
11459 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000011460 case FunctionTemplate: {
11461 FunctionTemplateDecl *FirstTemplate =
11462 cast<FunctionTemplateDecl>(FirstDecl);
11463 FunctionTemplateDecl *SecondTemplate =
11464 cast<FunctionTemplateDecl>(SecondDecl);
11465
11466 TemplateParameterList *FirstTPL =
11467 FirstTemplate->getTemplateParameters();
11468 TemplateParameterList *SecondTPL =
11469 SecondTemplate->getTemplateParameters();
11470
11471 if (FirstTPL->size() != SecondTPL->size()) {
11472 ODRDiagError(FirstTemplate->getLocation(),
11473 FirstTemplate->getSourceRange(),
11474 FunctionTemplateDifferentNumberParameters)
11475 << FirstTemplate << FirstTPL->size();
11476 ODRDiagNote(SecondTemplate->getLocation(),
11477 SecondTemplate->getSourceRange(),
11478 FunctionTemplateDifferentNumberParameters)
11479 << SecondTemplate << SecondTPL->size();
11480
11481 Diagnosed = true;
11482 break;
11483 }
11484
11485 bool ParameterMismatch = false;
11486 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
11487 NamedDecl *FirstParam = FirstTPL->getParam(i);
11488 NamedDecl *SecondParam = SecondTPL->getParam(i);
11489
11490 if (FirstParam->getKind() != SecondParam->getKind()) {
11491 enum {
11492 TemplateTypeParameter,
11493 NonTypeTemplateParameter,
11494 TemplateTemplateParameter,
11495 };
11496 auto GetParamType = [](NamedDecl *D) {
11497 switch (D->getKind()) {
11498 default:
11499 llvm_unreachable("Unexpected template parameter type");
11500 case Decl::TemplateTypeParm:
11501 return TemplateTypeParameter;
11502 case Decl::NonTypeTemplateParm:
11503 return NonTypeTemplateParameter;
11504 case Decl::TemplateTemplateParm:
11505 return TemplateTemplateParameter;
11506 }
11507 };
11508
11509 ODRDiagError(FirstTemplate->getLocation(),
11510 FirstTemplate->getSourceRange(),
11511 FunctionTemplateParameterDifferentKind)
11512 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11513 ODRDiagNote(SecondTemplate->getLocation(),
11514 SecondTemplate->getSourceRange(),
11515 FunctionTemplateParameterDifferentKind)
11516 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11517
11518 ParameterMismatch = true;
11519 break;
11520 }
11521
11522 if (FirstParam->getName() != SecondParam->getName()) {
11523 ODRDiagError(FirstTemplate->getLocation(),
11524 FirstTemplate->getSourceRange(),
11525 FunctionTemplateParameterName)
11526 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11527 << FirstParam;
11528 ODRDiagNote(SecondTemplate->getLocation(),
11529 SecondTemplate->getSourceRange(),
11530 FunctionTemplateParameterName)
11531 << SecondTemplate << (i + 1)
11532 << (bool)SecondParam->getIdentifier() << SecondParam;
11533 ParameterMismatch = true;
11534 break;
11535 }
11536
11537 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11538 isa<TemplateTypeParmDecl>(SecondParam)) {
11539 TemplateTypeParmDecl *FirstTTPD =
11540 cast<TemplateTypeParmDecl>(FirstParam);
11541 TemplateTypeParmDecl *SecondTTPD =
11542 cast<TemplateTypeParmDecl>(SecondParam);
11543 bool HasFirstDefaultArgument =
11544 FirstTTPD->hasDefaultArgument() &&
11545 !FirstTTPD->defaultArgumentWasInherited();
11546 bool HasSecondDefaultArgument =
11547 SecondTTPD->hasDefaultArgument() &&
11548 !SecondTTPD->defaultArgumentWasInherited();
11549 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11550 ODRDiagError(FirstTemplate->getLocation(),
11551 FirstTemplate->getSourceRange(),
11552 FunctionTemplateParameterSingleDefaultArgument)
11553 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11554 ODRDiagNote(SecondTemplate->getLocation(),
11555 SecondTemplate->getSourceRange(),
11556 FunctionTemplateParameterSingleDefaultArgument)
11557 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11558 ParameterMismatch = true;
11559 break;
11560 }
11561
11562 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11563 QualType FirstType = FirstTTPD->getDefaultArgument();
11564 QualType SecondType = SecondTTPD->getDefaultArgument();
11565 if (ComputeQualTypeODRHash(FirstType) !=
11566 ComputeQualTypeODRHash(SecondType)) {
11567 ODRDiagError(FirstTemplate->getLocation(),
11568 FirstTemplate->getSourceRange(),
11569 FunctionTemplateParameterDifferentDefaultArgument)
11570 << FirstTemplate << (i + 1) << FirstType;
11571 ODRDiagNote(SecondTemplate->getLocation(),
11572 SecondTemplate->getSourceRange(),
11573 FunctionTemplateParameterDifferentDefaultArgument)
11574 << SecondTemplate << (i + 1) << SecondType;
11575 ParameterMismatch = true;
11576 break;
11577 }
11578 }
11579
11580 if (FirstTTPD->isParameterPack() !=
11581 SecondTTPD->isParameterPack()) {
11582 ODRDiagError(FirstTemplate->getLocation(),
11583 FirstTemplate->getSourceRange(),
11584 FunctionTemplatePackParameter)
11585 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11586 ODRDiagNote(SecondTemplate->getLocation(),
11587 SecondTemplate->getSourceRange(),
11588 FunctionTemplatePackParameter)
11589 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11590 ParameterMismatch = true;
11591 break;
11592 }
11593 }
11594
11595 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11596 isa<TemplateTemplateParmDecl>(SecondParam)) {
11597 TemplateTemplateParmDecl *FirstTTPD =
11598 cast<TemplateTemplateParmDecl>(FirstParam);
11599 TemplateTemplateParmDecl *SecondTTPD =
11600 cast<TemplateTemplateParmDecl>(SecondParam);
11601
11602 TemplateParameterList *FirstTPL =
11603 FirstTTPD->getTemplateParameters();
11604 TemplateParameterList *SecondTPL =
11605 SecondTTPD->getTemplateParameters();
11606
11607 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11608 ComputeTemplateParameterListODRHash(SecondTPL)) {
11609 ODRDiagError(FirstTemplate->getLocation(),
11610 FirstTemplate->getSourceRange(),
11611 FunctionTemplateParameterDifferentType)
11612 << FirstTemplate << (i + 1);
11613 ODRDiagNote(SecondTemplate->getLocation(),
11614 SecondTemplate->getSourceRange(),
11615 FunctionTemplateParameterDifferentType)
11616 << SecondTemplate << (i + 1);
11617 ParameterMismatch = true;
11618 break;
11619 }
11620
11621 bool HasFirstDefaultArgument =
11622 FirstTTPD->hasDefaultArgument() &&
11623 !FirstTTPD->defaultArgumentWasInherited();
11624 bool HasSecondDefaultArgument =
11625 SecondTTPD->hasDefaultArgument() &&
11626 !SecondTTPD->defaultArgumentWasInherited();
11627 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11628 ODRDiagError(FirstTemplate->getLocation(),
11629 FirstTemplate->getSourceRange(),
11630 FunctionTemplateParameterSingleDefaultArgument)
11631 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11632 ODRDiagNote(SecondTemplate->getLocation(),
11633 SecondTemplate->getSourceRange(),
11634 FunctionTemplateParameterSingleDefaultArgument)
11635 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11636 ParameterMismatch = true;
11637 break;
11638 }
11639
11640 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11641 TemplateArgument FirstTA =
11642 FirstTTPD->getDefaultArgument().getArgument();
11643 TemplateArgument SecondTA =
11644 SecondTTPD->getDefaultArgument().getArgument();
11645 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11646 ComputeTemplateArgumentODRHash(SecondTA)) {
11647 ODRDiagError(FirstTemplate->getLocation(),
11648 FirstTemplate->getSourceRange(),
11649 FunctionTemplateParameterDifferentDefaultArgument)
11650 << FirstTemplate << (i + 1) << FirstTA;
11651 ODRDiagNote(SecondTemplate->getLocation(),
11652 SecondTemplate->getSourceRange(),
11653 FunctionTemplateParameterDifferentDefaultArgument)
11654 << SecondTemplate << (i + 1) << SecondTA;
11655 ParameterMismatch = true;
11656 break;
11657 }
11658 }
11659
11660 if (FirstTTPD->isParameterPack() !=
11661 SecondTTPD->isParameterPack()) {
11662 ODRDiagError(FirstTemplate->getLocation(),
11663 FirstTemplate->getSourceRange(),
11664 FunctionTemplatePackParameter)
11665 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11666 ODRDiagNote(SecondTemplate->getLocation(),
11667 SecondTemplate->getSourceRange(),
11668 FunctionTemplatePackParameter)
11669 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11670 ParameterMismatch = true;
11671 break;
11672 }
11673 }
11674
11675 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11676 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11677 NonTypeTemplateParmDecl *FirstNTTPD =
11678 cast<NonTypeTemplateParmDecl>(FirstParam);
11679 NonTypeTemplateParmDecl *SecondNTTPD =
11680 cast<NonTypeTemplateParmDecl>(SecondParam);
11681
11682 QualType FirstType = FirstNTTPD->getType();
11683 QualType SecondType = SecondNTTPD->getType();
11684 if (ComputeQualTypeODRHash(FirstType) !=
11685 ComputeQualTypeODRHash(SecondType)) {
11686 ODRDiagError(FirstTemplate->getLocation(),
11687 FirstTemplate->getSourceRange(),
11688 FunctionTemplateParameterDifferentType)
11689 << FirstTemplate << (i + 1);
11690 ODRDiagNote(SecondTemplate->getLocation(),
11691 SecondTemplate->getSourceRange(),
11692 FunctionTemplateParameterDifferentType)
11693 << SecondTemplate << (i + 1);
11694 ParameterMismatch = true;
11695 break;
11696 }
11697
11698 bool HasFirstDefaultArgument =
11699 FirstNTTPD->hasDefaultArgument() &&
11700 !FirstNTTPD->defaultArgumentWasInherited();
11701 bool HasSecondDefaultArgument =
11702 SecondNTTPD->hasDefaultArgument() &&
11703 !SecondNTTPD->defaultArgumentWasInherited();
11704 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11705 ODRDiagError(FirstTemplate->getLocation(),
11706 FirstTemplate->getSourceRange(),
11707 FunctionTemplateParameterSingleDefaultArgument)
11708 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11709 ODRDiagNote(SecondTemplate->getLocation(),
11710 SecondTemplate->getSourceRange(),
11711 FunctionTemplateParameterSingleDefaultArgument)
11712 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11713 ParameterMismatch = true;
11714 break;
11715 }
11716
11717 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11718 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11719 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11720 if (ComputeODRHash(FirstDefaultArgument) !=
11721 ComputeODRHash(SecondDefaultArgument)) {
11722 ODRDiagError(FirstTemplate->getLocation(),
11723 FirstTemplate->getSourceRange(),
11724 FunctionTemplateParameterDifferentDefaultArgument)
11725 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11726 ODRDiagNote(SecondTemplate->getLocation(),
11727 SecondTemplate->getSourceRange(),
11728 FunctionTemplateParameterDifferentDefaultArgument)
11729 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11730 ParameterMismatch = true;
11731 break;
11732 }
11733 }
11734
11735 if (FirstNTTPD->isParameterPack() !=
11736 SecondNTTPD->isParameterPack()) {
11737 ODRDiagError(FirstTemplate->getLocation(),
11738 FirstTemplate->getSourceRange(),
11739 FunctionTemplatePackParameter)
11740 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11741 ODRDiagNote(SecondTemplate->getLocation(),
11742 SecondTemplate->getSourceRange(),
11743 FunctionTemplatePackParameter)
11744 << SecondTemplate << (i + 1)
11745 << SecondNTTPD->isParameterPack();
11746 ParameterMismatch = true;
11747 break;
11748 }
11749 }
11750 }
11751
11752 if (ParameterMismatch) {
11753 Diagnosed = true;
11754 break;
11755 }
11756
11757 break;
11758 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011759 }
11760
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011761 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011762 continue;
11763
Richard Trieu708859a2017-06-08 00:56:21 +000011764 Diag(FirstDecl->getLocation(),
11765 diag::err_module_odr_violation_mismatch_decl_unknown)
11766 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11767 << FirstDecl->getSourceRange();
11768 Diag(SecondDecl->getLocation(),
11769 diag::note_module_odr_violation_mismatch_decl_unknown)
11770 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011771 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011772 }
11773
11774 if (!Diagnosed) {
11775 // All definitions are updates to the same declaration. This happens if a
11776 // module instantiates the declaration of a class template specialization
11777 // and two or more other modules instantiate its definition.
11778 //
11779 // FIXME: Indicate which modules had instantiations of this definition.
11780 // FIXME: How can this even happen?
11781 Diag(Merge.first->getLocation(),
11782 diag::err_module_odr_violation_different_instantiations)
11783 << Merge.first;
11784 }
11785 }
Richard Trieue6caa262017-12-23 00:41:01 +000011786
11787 // Issue ODR failures diagnostics for functions.
11788 for (auto &Merge : FunctionOdrMergeFailures) {
11789 enum ODRFunctionDifference {
11790 ReturnType,
11791 ParameterName,
11792 ParameterType,
11793 ParameterSingleDefaultArgument,
11794 ParameterDifferentDefaultArgument,
11795 FunctionBody,
11796 };
11797
11798 FunctionDecl *FirstFunction = Merge.first;
11799 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11800
11801 bool Diagnosed = false;
11802 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011803
Richard Trieue6caa262017-12-23 00:41:01 +000011804 if (FirstFunction == SecondFunction)
11805 continue;
11806
11807 std::string SecondModule =
11808 getOwningModuleNameForDiagnostic(SecondFunction);
11809
11810 auto ODRDiagError = [FirstFunction, &FirstModule,
11811 this](SourceLocation Loc, SourceRange Range,
11812 ODRFunctionDifference DiffType) {
11813 return Diag(Loc, diag::err_module_odr_violation_function)
11814 << FirstFunction << FirstModule.empty() << FirstModule << Range
11815 << DiffType;
11816 };
11817 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11818 SourceRange Range,
11819 ODRFunctionDifference DiffType) {
11820 return Diag(Loc, diag::note_module_odr_violation_function)
11821 << SecondModule << Range << DiffType;
11822 };
11823
11824 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11825 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11826 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11827 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11828 << FirstFunction->getReturnType();
11829 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11830 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11831 << SecondFunction->getReturnType();
11832 Diagnosed = true;
11833 break;
11834 }
11835
11836 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11837 "Merged functions with different number of parameters");
11838
11839 auto ParamSize = FirstFunction->param_size();
11840 bool ParameterMismatch = false;
11841 for (unsigned I = 0; I < ParamSize; ++I) {
11842 auto *FirstParam = FirstFunction->getParamDecl(I);
11843 auto *SecondParam = SecondFunction->getParamDecl(I);
11844
11845 assert(getContext().hasSameType(FirstParam->getType(),
11846 SecondParam->getType()) &&
11847 "Merged function has different parameter types.");
11848
11849 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11850 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11851 ParameterName)
11852 << I + 1 << FirstParam->getDeclName();
11853 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11854 ParameterName)
11855 << I + 1 << SecondParam->getDeclName();
11856 ParameterMismatch = true;
11857 break;
11858 };
11859
11860 QualType FirstParamType = FirstParam->getType();
11861 QualType SecondParamType = SecondParam->getType();
11862 if (FirstParamType != SecondParamType &&
11863 ComputeQualTypeODRHash(FirstParamType) !=
11864 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011865 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011866 FirstParamType->getAs<DecayedType>()) {
11867 ODRDiagError(FirstParam->getLocation(),
11868 FirstParam->getSourceRange(), ParameterType)
11869 << (I + 1) << FirstParamType << true
11870 << ParamDecayedType->getOriginalType();
11871 } else {
11872 ODRDiagError(FirstParam->getLocation(),
11873 FirstParam->getSourceRange(), ParameterType)
11874 << (I + 1) << FirstParamType << false;
11875 }
11876
Vedant Kumar48b4f762018-04-14 01:40:48 +000011877 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011878 SecondParamType->getAs<DecayedType>()) {
11879 ODRDiagNote(SecondParam->getLocation(),
11880 SecondParam->getSourceRange(), ParameterType)
11881 << (I + 1) << SecondParamType << true
11882 << ParamDecayedType->getOriginalType();
11883 } else {
11884 ODRDiagNote(SecondParam->getLocation(),
11885 SecondParam->getSourceRange(), ParameterType)
11886 << (I + 1) << SecondParamType << false;
11887 }
11888 ParameterMismatch = true;
11889 break;
11890 }
11891
11892 const Expr *FirstInit = FirstParam->getInit();
11893 const Expr *SecondInit = SecondParam->getInit();
11894 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11895 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11896 ParameterSingleDefaultArgument)
11897 << (I + 1) << (FirstInit == nullptr)
11898 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11899 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11900 ParameterSingleDefaultArgument)
11901 << (I + 1) << (SecondInit == nullptr)
11902 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11903 ParameterMismatch = true;
11904 break;
11905 }
11906
11907 if (FirstInit && SecondInit &&
11908 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11909 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11910 ParameterDifferentDefaultArgument)
11911 << (I + 1) << FirstInit->getSourceRange();
11912 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11913 ParameterDifferentDefaultArgument)
11914 << (I + 1) << SecondInit->getSourceRange();
11915 ParameterMismatch = true;
11916 break;
11917 }
11918
11919 assert(ComputeSubDeclODRHash(FirstParam) ==
11920 ComputeSubDeclODRHash(SecondParam) &&
11921 "Undiagnosed parameter difference.");
11922 }
11923
11924 if (ParameterMismatch) {
11925 Diagnosed = true;
11926 break;
11927 }
11928
11929 // If no error has been generated before now, assume the problem is in
11930 // the body and generate a message.
11931 ODRDiagError(FirstFunction->getLocation(),
11932 FirstFunction->getSourceRange(), FunctionBody);
11933 ODRDiagNote(SecondFunction->getLocation(),
11934 SecondFunction->getSourceRange(), FunctionBody);
11935 Diagnosed = true;
11936 break;
11937 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011938 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011939 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11940 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011941
11942 // Issue ODR failures diagnostics for enums.
11943 for (auto &Merge : EnumOdrMergeFailures) {
11944 enum ODREnumDifference {
11945 SingleScopedEnum,
11946 EnumTagKeywordMismatch,
11947 SingleSpecifiedType,
11948 DifferentSpecifiedTypes,
11949 DifferentNumberEnumConstants,
11950 EnumConstantName,
11951 EnumConstantSingleInitilizer,
11952 EnumConstantDifferentInitilizer,
11953 };
11954
11955 // If we've already pointed out a specific problem with this enum, don't
11956 // bother issuing a general "something's different" diagnostic.
11957 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11958 continue;
11959
11960 EnumDecl *FirstEnum = Merge.first;
11961 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11962
11963 using DeclHashes =
11964 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11965 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11966 DeclHashes &Hashes, EnumDecl *Enum) {
11967 for (auto *D : Enum->decls()) {
11968 // Due to decl merging, the first EnumDecl is the parent of
11969 // Decls in both records.
11970 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11971 continue;
11972 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11973 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11974 ComputeSubDeclODRHash(D));
11975 }
11976 };
11977 DeclHashes FirstHashes;
11978 PopulateHashes(FirstHashes, FirstEnum);
11979 bool Diagnosed = false;
11980 for (auto &SecondEnum : Merge.second) {
11981
11982 if (FirstEnum == SecondEnum)
11983 continue;
11984
11985 std::string SecondModule =
11986 getOwningModuleNameForDiagnostic(SecondEnum);
11987
11988 auto ODRDiagError = [FirstEnum, &FirstModule,
11989 this](SourceLocation Loc, SourceRange Range,
11990 ODREnumDifference DiffType) {
11991 return Diag(Loc, diag::err_module_odr_violation_enum)
11992 << FirstEnum << FirstModule.empty() << FirstModule << Range
11993 << DiffType;
11994 };
11995 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11996 SourceRange Range,
11997 ODREnumDifference DiffType) {
11998 return Diag(Loc, diag::note_module_odr_violation_enum)
11999 << SecondModule << Range << DiffType;
12000 };
12001
12002 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
12003 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12004 SingleScopedEnum)
12005 << FirstEnum->isScoped();
12006 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12007 SingleScopedEnum)
12008 << SecondEnum->isScoped();
12009 Diagnosed = true;
12010 continue;
12011 }
12012
12013 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
12014 if (FirstEnum->isScopedUsingClassTag() !=
12015 SecondEnum->isScopedUsingClassTag()) {
12016 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12017 EnumTagKeywordMismatch)
12018 << FirstEnum->isScopedUsingClassTag();
12019 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12020 EnumTagKeywordMismatch)
12021 << SecondEnum->isScopedUsingClassTag();
12022 Diagnosed = true;
12023 continue;
12024 }
12025 }
12026
12027 QualType FirstUnderlyingType =
12028 FirstEnum->getIntegerTypeSourceInfo()
12029 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
12030 : QualType();
12031 QualType SecondUnderlyingType =
12032 SecondEnum->getIntegerTypeSourceInfo()
12033 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
12034 : QualType();
12035 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
12036 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12037 SingleSpecifiedType)
12038 << !FirstUnderlyingType.isNull();
12039 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12040 SingleSpecifiedType)
12041 << !SecondUnderlyingType.isNull();
12042 Diagnosed = true;
12043 continue;
12044 }
12045
12046 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
12047 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
12048 ComputeQualTypeODRHash(SecondUnderlyingType)) {
12049 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12050 DifferentSpecifiedTypes)
12051 << FirstUnderlyingType;
12052 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12053 DifferentSpecifiedTypes)
12054 << SecondUnderlyingType;
12055 Diagnosed = true;
12056 continue;
12057 }
12058 }
12059
12060 DeclHashes SecondHashes;
12061 PopulateHashes(SecondHashes, SecondEnum);
12062
12063 if (FirstHashes.size() != SecondHashes.size()) {
12064 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12065 DifferentNumberEnumConstants)
12066 << (int)FirstHashes.size();
12067 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12068 DifferentNumberEnumConstants)
12069 << (int)SecondHashes.size();
12070 Diagnosed = true;
12071 continue;
12072 }
12073
12074 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
12075 if (FirstHashes[I].second == SecondHashes[I].second)
12076 continue;
12077 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
12078 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
12079
12080 if (FirstEnumConstant->getDeclName() !=
12081 SecondEnumConstant->getDeclName()) {
12082
12083 ODRDiagError(FirstEnumConstant->getLocation(),
12084 FirstEnumConstant->getSourceRange(), EnumConstantName)
12085 << I + 1 << FirstEnumConstant;
12086 ODRDiagNote(SecondEnumConstant->getLocation(),
12087 SecondEnumConstant->getSourceRange(), EnumConstantName)
12088 << I + 1 << SecondEnumConstant;
12089 Diagnosed = true;
12090 break;
12091 }
12092
12093 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
12094 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
12095 if (!FirstInit && !SecondInit)
12096 continue;
12097
12098 if (!FirstInit || !SecondInit) {
12099 ODRDiagError(FirstEnumConstant->getLocation(),
12100 FirstEnumConstant->getSourceRange(),
12101 EnumConstantSingleInitilizer)
12102 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
12103 ODRDiagNote(SecondEnumConstant->getLocation(),
12104 SecondEnumConstant->getSourceRange(),
12105 EnumConstantSingleInitilizer)
12106 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
12107 Diagnosed = true;
12108 break;
12109 }
12110
12111 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
12112 ODRDiagError(FirstEnumConstant->getLocation(),
12113 FirstEnumConstant->getSourceRange(),
12114 EnumConstantDifferentInitilizer)
12115 << I + 1 << FirstEnumConstant;
12116 ODRDiagNote(SecondEnumConstant->getLocation(),
12117 SecondEnumConstant->getSourceRange(),
12118 EnumConstantDifferentInitilizer)
12119 << I + 1 << SecondEnumConstant;
12120 Diagnosed = true;
12121 break;
12122 }
12123 }
12124 }
12125
12126 (void)Diagnosed;
12127 assert(Diagnosed && "Unable to emit ODR diagnostic.");
12128 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012129}
12130
Richard Smithce18a182015-07-14 00:26:00 +000012131void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000012132 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000012133 ReadTimer->startTimer();
12134}
12135
Guy Benyei11169dd2012-12-18 14:30:41 +000012136void ASTReader::FinishedDeserializing() {
12137 assert(NumCurrentElementsDeserializing &&
12138 "FinishedDeserializing not paired with StartedDeserializing");
12139 if (NumCurrentElementsDeserializing == 1) {
12140 // We decrease NumCurrentElementsDeserializing only after pending actions
12141 // are finished, to avoid recursively re-calling finishPendingActions().
12142 finishPendingActions();
12143 }
12144 --NumCurrentElementsDeserializing;
12145
Richard Smitha0ce9c42014-07-29 23:23:27 +000012146 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000012147 // Propagate exception specification and deduced type updates along
12148 // redeclaration chains.
12149 //
12150 // We do this now rather than in finishPendingActions because we want to
12151 // be able to walk the complete redeclaration chains of the updated decls.
12152 while (!PendingExceptionSpecUpdates.empty() ||
12153 !PendingDeducedTypeUpdates.empty()) {
12154 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000012155 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000012156 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000012157 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000012158 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000012159 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000012160 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000012161 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000012162 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000012163 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000012164 }
Richard Smitha62d1982018-08-03 01:00:01 +000012165
12166 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
12167 PendingDeducedTypeUpdates.clear();
12168 for (auto Update : DTUpdates) {
12169 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
12170 // FIXME: If the return type is already deduced, check that it matches.
12171 getContext().adjustDeducedFunctionResultType(Update.first,
12172 Update.second);
12173 }
Richard Smith9e2341d2015-03-23 03:25:59 +000012174 }
12175
Richard Smithce18a182015-07-14 00:26:00 +000012176 if (ReadTimer)
12177 ReadTimer->stopTimer();
12178
Richard Smith0f4e2c42015-08-06 04:23:48 +000012179 diagnoseOdrViolations();
12180
Richard Smith04d05b52014-03-23 00:27:18 +000012181 // We are not in recursive loading, so it's safe to pass the "interesting"
12182 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000012183 if (Consumer)
12184 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000012185 }
12186}
12187
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012188void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000012189 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
12190 // Remove any fake results before adding any real ones.
12191 auto It = PendingFakeLookupResults.find(II);
12192 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000012193 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000012194 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000012195 // FIXME: this works around module+PCH performance issue.
12196 // Rather than erase the result from the map, which is O(n), just clear
12197 // the vector of NamedDecls.
12198 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000012199 }
12200 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012201
12202 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
12203 SemaObj->TUScope->AddDecl(D);
12204 } else if (SemaObj->TUScope) {
12205 // Adding the decl to IdResolver may have failed because it was already in
12206 // (even though it was not added in scope). If it is already in, make sure
12207 // it gets in the scope as well.
12208 if (std::find(SemaObj->IdResolver.begin(Name),
12209 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
12210 SemaObj->TUScope->AddDecl(D);
12211 }
12212}
12213
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012214ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
12215 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000012216 const PCHContainerReader &PCHContainerRdr,
12217 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
12218 StringRef isysroot, bool DisableValidation,
12219 bool AllowASTWithCompilerErrors,
12220 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000012221 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000012222 std::unique_ptr<llvm::Timer> ReadTimer)
12223 : Listener(DisableValidation
12224 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
12225 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000012226 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012227 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012228 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
12229 PCHContainerRdr, PP.getHeaderSearchInfo()),
12230 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000012231 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000012232 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
12233 AllowConfigurationMismatch(AllowConfigurationMismatch),
12234 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000012235 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012236 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000012237 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000012238
12239 for (const auto &Ext : Extensions) {
12240 auto BlockName = Ext->getExtensionMetadata().BlockName;
12241 auto Known = ModuleFileExtensions.find(BlockName);
12242 if (Known != ModuleFileExtensions.end()) {
12243 Diags.Report(diag::warn_duplicate_module_file_extension)
12244 << BlockName;
12245 continue;
12246 }
12247
12248 ModuleFileExtensions.insert({BlockName, Ext});
12249 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012250}
12251
12252ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000012253 if (OwnsDeserializationListener)
12254 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000012255}
Richard Smith10379092016-05-06 23:14:07 +000012256
12257IdentifierResolver &ASTReader::getIdResolver() {
12258 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
12259}
David L. Jonesbe1557a2016-12-21 00:17:49 +000012260
JF Bastien0e828952019-06-26 19:50:12 +000012261Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
12262 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000012263 Idx = 0;
12264 Record.clear();
12265 return Cursor.readRecord(AbbrevID, Record);
12266}
Kelvin Libe286f52018-09-15 13:54:15 +000012267//===----------------------------------------------------------------------===//
12268//// OMPClauseReader implementation
12269////===----------------------------------------------------------------------===//
12270
12271OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012272 OMPClause *C = nullptr;
Kelvin Libe286f52018-09-15 13:54:15 +000012273 switch (Record.readInt()) {
12274 case OMPC_if:
12275 C = new (Context) OMPIfClause();
12276 break;
12277 case OMPC_final:
12278 C = new (Context) OMPFinalClause();
12279 break;
12280 case OMPC_num_threads:
12281 C = new (Context) OMPNumThreadsClause();
12282 break;
12283 case OMPC_safelen:
12284 C = new (Context) OMPSafelenClause();
12285 break;
12286 case OMPC_simdlen:
12287 C = new (Context) OMPSimdlenClause();
12288 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012289 case OMPC_allocator:
12290 C = new (Context) OMPAllocatorClause();
12291 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012292 case OMPC_collapse:
12293 C = new (Context) OMPCollapseClause();
12294 break;
12295 case OMPC_default:
12296 C = new (Context) OMPDefaultClause();
12297 break;
12298 case OMPC_proc_bind:
12299 C = new (Context) OMPProcBindClause();
12300 break;
12301 case OMPC_schedule:
12302 C = new (Context) OMPScheduleClause();
12303 break;
12304 case OMPC_ordered:
12305 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
12306 break;
12307 case OMPC_nowait:
12308 C = new (Context) OMPNowaitClause();
12309 break;
12310 case OMPC_untied:
12311 C = new (Context) OMPUntiedClause();
12312 break;
12313 case OMPC_mergeable:
12314 C = new (Context) OMPMergeableClause();
12315 break;
12316 case OMPC_read:
12317 C = new (Context) OMPReadClause();
12318 break;
12319 case OMPC_write:
12320 C = new (Context) OMPWriteClause();
12321 break;
12322 case OMPC_update:
12323 C = new (Context) OMPUpdateClause();
12324 break;
12325 case OMPC_capture:
12326 C = new (Context) OMPCaptureClause();
12327 break;
12328 case OMPC_seq_cst:
12329 C = new (Context) OMPSeqCstClause();
12330 break;
12331 case OMPC_threads:
12332 C = new (Context) OMPThreadsClause();
12333 break;
12334 case OMPC_simd:
12335 C = new (Context) OMPSIMDClause();
12336 break;
12337 case OMPC_nogroup:
12338 C = new (Context) OMPNogroupClause();
12339 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012340 case OMPC_unified_address:
12341 C = new (Context) OMPUnifiedAddressClause();
12342 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012343 case OMPC_unified_shared_memory:
12344 C = new (Context) OMPUnifiedSharedMemoryClause();
12345 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012346 case OMPC_reverse_offload:
12347 C = new (Context) OMPReverseOffloadClause();
12348 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012349 case OMPC_dynamic_allocators:
12350 C = new (Context) OMPDynamicAllocatorsClause();
12351 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012352 case OMPC_atomic_default_mem_order:
12353 C = new (Context) OMPAtomicDefaultMemOrderClause();
12354 break;
12355 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000012356 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
12357 break;
12358 case OMPC_firstprivate:
12359 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
12360 break;
12361 case OMPC_lastprivate:
12362 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
12363 break;
12364 case OMPC_shared:
12365 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
12366 break;
12367 case OMPC_reduction:
12368 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
12369 break;
12370 case OMPC_task_reduction:
12371 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
12372 break;
12373 case OMPC_in_reduction:
12374 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
12375 break;
12376 case OMPC_linear:
12377 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
12378 break;
12379 case OMPC_aligned:
12380 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
12381 break;
12382 case OMPC_copyin:
12383 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
12384 break;
12385 case OMPC_copyprivate:
12386 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
12387 break;
12388 case OMPC_flush:
12389 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
12390 break;
12391 case OMPC_depend: {
12392 unsigned NumVars = Record.readInt();
12393 unsigned NumLoops = Record.readInt();
12394 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
12395 break;
12396 }
12397 case OMPC_device:
12398 C = new (Context) OMPDeviceClause();
12399 break;
12400 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012401 OMPMappableExprListSizeTy Sizes;
12402 Sizes.NumVars = Record.readInt();
12403 Sizes.NumUniqueDeclarations = Record.readInt();
12404 Sizes.NumComponentLists = Record.readInt();
12405 Sizes.NumComponents = Record.readInt();
12406 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012407 break;
12408 }
12409 case OMPC_num_teams:
12410 C = new (Context) OMPNumTeamsClause();
12411 break;
12412 case OMPC_thread_limit:
12413 C = new (Context) OMPThreadLimitClause();
12414 break;
12415 case OMPC_priority:
12416 C = new (Context) OMPPriorityClause();
12417 break;
12418 case OMPC_grainsize:
12419 C = new (Context) OMPGrainsizeClause();
12420 break;
12421 case OMPC_num_tasks:
12422 C = new (Context) OMPNumTasksClause();
12423 break;
12424 case OMPC_hint:
12425 C = new (Context) OMPHintClause();
12426 break;
12427 case OMPC_dist_schedule:
12428 C = new (Context) OMPDistScheduleClause();
12429 break;
12430 case OMPC_defaultmap:
12431 C = new (Context) OMPDefaultmapClause();
12432 break;
12433 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012434 OMPMappableExprListSizeTy Sizes;
12435 Sizes.NumVars = Record.readInt();
12436 Sizes.NumUniqueDeclarations = Record.readInt();
12437 Sizes.NumComponentLists = Record.readInt();
12438 Sizes.NumComponents = Record.readInt();
12439 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012440 break;
12441 }
12442 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012443 OMPMappableExprListSizeTy Sizes;
12444 Sizes.NumVars = Record.readInt();
12445 Sizes.NumUniqueDeclarations = Record.readInt();
12446 Sizes.NumComponentLists = Record.readInt();
12447 Sizes.NumComponents = Record.readInt();
12448 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012449 break;
12450 }
12451 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012452 OMPMappableExprListSizeTy Sizes;
12453 Sizes.NumVars = Record.readInt();
12454 Sizes.NumUniqueDeclarations = Record.readInt();
12455 Sizes.NumComponentLists = Record.readInt();
12456 Sizes.NumComponents = Record.readInt();
12457 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012458 break;
12459 }
12460 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012461 OMPMappableExprListSizeTy Sizes;
12462 Sizes.NumVars = Record.readInt();
12463 Sizes.NumUniqueDeclarations = Record.readInt();
12464 Sizes.NumComponentLists = Record.readInt();
12465 Sizes.NumComponents = Record.readInt();
12466 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012467 break;
12468 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000012469 case OMPC_allocate:
12470 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
12471 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012472 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012473 assert(C && "Unknown OMPClause type");
12474
Kelvin Libe286f52018-09-15 13:54:15 +000012475 Visit(C);
12476 C->setLocStart(Record.readSourceLocation());
12477 C->setLocEnd(Record.readSourceLocation());
12478
12479 return C;
12480}
12481
12482void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12483 C->setPreInitStmt(Record.readSubStmt(),
12484 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12485}
12486
12487void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12488 VisitOMPClauseWithPreInit(C);
12489 C->setPostUpdateExpr(Record.readSubExpr());
12490}
12491
12492void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12493 VisitOMPClauseWithPreInit(C);
12494 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12495 C->setNameModifierLoc(Record.readSourceLocation());
12496 C->setColonLoc(Record.readSourceLocation());
12497 C->setCondition(Record.readSubExpr());
12498 C->setLParenLoc(Record.readSourceLocation());
12499}
12500
12501void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12502 C->setCondition(Record.readSubExpr());
12503 C->setLParenLoc(Record.readSourceLocation());
12504}
12505
12506void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12507 VisitOMPClauseWithPreInit(C);
12508 C->setNumThreads(Record.readSubExpr());
12509 C->setLParenLoc(Record.readSourceLocation());
12510}
12511
12512void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12513 C->setSafelen(Record.readSubExpr());
12514 C->setLParenLoc(Record.readSourceLocation());
12515}
12516
12517void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12518 C->setSimdlen(Record.readSubExpr());
12519 C->setLParenLoc(Record.readSourceLocation());
12520}
12521
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012522void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12523 C->setAllocator(Record.readExpr());
12524 C->setLParenLoc(Record.readSourceLocation());
12525}
12526
Kelvin Libe286f52018-09-15 13:54:15 +000012527void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12528 C->setNumForLoops(Record.readSubExpr());
12529 C->setLParenLoc(Record.readSourceLocation());
12530}
12531
12532void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12533 C->setDefaultKind(
12534 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12535 C->setLParenLoc(Record.readSourceLocation());
12536 C->setDefaultKindKwLoc(Record.readSourceLocation());
12537}
12538
12539void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12540 C->setProcBindKind(
12541 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12542 C->setLParenLoc(Record.readSourceLocation());
12543 C->setProcBindKindKwLoc(Record.readSourceLocation());
12544}
12545
12546void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12547 VisitOMPClauseWithPreInit(C);
12548 C->setScheduleKind(
12549 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12550 C->setFirstScheduleModifier(
12551 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12552 C->setSecondScheduleModifier(
12553 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12554 C->setChunkSize(Record.readSubExpr());
12555 C->setLParenLoc(Record.readSourceLocation());
12556 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12557 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12558 C->setScheduleKindLoc(Record.readSourceLocation());
12559 C->setCommaLoc(Record.readSourceLocation());
12560}
12561
12562void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12563 C->setNumForLoops(Record.readSubExpr());
12564 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12565 C->setLoopNumIterations(I, Record.readSubExpr());
12566 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12567 C->setLoopCounter(I, Record.readSubExpr());
12568 C->setLParenLoc(Record.readSourceLocation());
12569}
12570
12571void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12572
12573void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12574
12575void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12576
12577void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12578
12579void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12580
12581void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12582
12583void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12584
12585void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12586
12587void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12588
12589void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12590
12591void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12592
Kelvin Li1408f912018-09-26 04:28:39 +000012593void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12594
Patrick Lyster4a370b92018-10-01 13:47:43 +000012595void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12596 OMPUnifiedSharedMemoryClause *) {}
12597
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012598void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12599
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012600void
12601OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12602}
12603
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012604void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12605 OMPAtomicDefaultMemOrderClause *C) {
12606 C->setAtomicDefaultMemOrderKind(
12607 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12608 C->setLParenLoc(Record.readSourceLocation());
12609 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12610}
12611
Kelvin Libe286f52018-09-15 13:54:15 +000012612void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12613 C->setLParenLoc(Record.readSourceLocation());
12614 unsigned NumVars = C->varlist_size();
12615 SmallVector<Expr *, 16> Vars;
12616 Vars.reserve(NumVars);
12617 for (unsigned i = 0; i != NumVars; ++i)
12618 Vars.push_back(Record.readSubExpr());
12619 C->setVarRefs(Vars);
12620 Vars.clear();
12621 for (unsigned i = 0; i != NumVars; ++i)
12622 Vars.push_back(Record.readSubExpr());
12623 C->setPrivateCopies(Vars);
12624}
12625
12626void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12627 VisitOMPClauseWithPreInit(C);
12628 C->setLParenLoc(Record.readSourceLocation());
12629 unsigned NumVars = C->varlist_size();
12630 SmallVector<Expr *, 16> Vars;
12631 Vars.reserve(NumVars);
12632 for (unsigned i = 0; i != NumVars; ++i)
12633 Vars.push_back(Record.readSubExpr());
12634 C->setVarRefs(Vars);
12635 Vars.clear();
12636 for (unsigned i = 0; i != NumVars; ++i)
12637 Vars.push_back(Record.readSubExpr());
12638 C->setPrivateCopies(Vars);
12639 Vars.clear();
12640 for (unsigned i = 0; i != NumVars; ++i)
12641 Vars.push_back(Record.readSubExpr());
12642 C->setInits(Vars);
12643}
12644
12645void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12646 VisitOMPClauseWithPostUpdate(C);
12647 C->setLParenLoc(Record.readSourceLocation());
12648 unsigned NumVars = C->varlist_size();
12649 SmallVector<Expr *, 16> Vars;
12650 Vars.reserve(NumVars);
12651 for (unsigned i = 0; i != NumVars; ++i)
12652 Vars.push_back(Record.readSubExpr());
12653 C->setVarRefs(Vars);
12654 Vars.clear();
12655 for (unsigned i = 0; i != NumVars; ++i)
12656 Vars.push_back(Record.readSubExpr());
12657 C->setPrivateCopies(Vars);
12658 Vars.clear();
12659 for (unsigned i = 0; i != NumVars; ++i)
12660 Vars.push_back(Record.readSubExpr());
12661 C->setSourceExprs(Vars);
12662 Vars.clear();
12663 for (unsigned i = 0; i != NumVars; ++i)
12664 Vars.push_back(Record.readSubExpr());
12665 C->setDestinationExprs(Vars);
12666 Vars.clear();
12667 for (unsigned i = 0; i != NumVars; ++i)
12668 Vars.push_back(Record.readSubExpr());
12669 C->setAssignmentOps(Vars);
12670}
12671
12672void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12673 C->setLParenLoc(Record.readSourceLocation());
12674 unsigned NumVars = C->varlist_size();
12675 SmallVector<Expr *, 16> Vars;
12676 Vars.reserve(NumVars);
12677 for (unsigned i = 0; i != NumVars; ++i)
12678 Vars.push_back(Record.readSubExpr());
12679 C->setVarRefs(Vars);
12680}
12681
12682void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12683 VisitOMPClauseWithPostUpdate(C);
12684 C->setLParenLoc(Record.readSourceLocation());
12685 C->setColonLoc(Record.readSourceLocation());
12686 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12687 DeclarationNameInfo DNI;
12688 Record.readDeclarationNameInfo(DNI);
12689 C->setQualifierLoc(NNSL);
12690 C->setNameInfo(DNI);
12691
12692 unsigned NumVars = C->varlist_size();
12693 SmallVector<Expr *, 16> Vars;
12694 Vars.reserve(NumVars);
12695 for (unsigned i = 0; i != NumVars; ++i)
12696 Vars.push_back(Record.readSubExpr());
12697 C->setVarRefs(Vars);
12698 Vars.clear();
12699 for (unsigned i = 0; i != NumVars; ++i)
12700 Vars.push_back(Record.readSubExpr());
12701 C->setPrivates(Vars);
12702 Vars.clear();
12703 for (unsigned i = 0; i != NumVars; ++i)
12704 Vars.push_back(Record.readSubExpr());
12705 C->setLHSExprs(Vars);
12706 Vars.clear();
12707 for (unsigned i = 0; i != NumVars; ++i)
12708 Vars.push_back(Record.readSubExpr());
12709 C->setRHSExprs(Vars);
12710 Vars.clear();
12711 for (unsigned i = 0; i != NumVars; ++i)
12712 Vars.push_back(Record.readSubExpr());
12713 C->setReductionOps(Vars);
12714}
12715
12716void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12717 VisitOMPClauseWithPostUpdate(C);
12718 C->setLParenLoc(Record.readSourceLocation());
12719 C->setColonLoc(Record.readSourceLocation());
12720 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12721 DeclarationNameInfo DNI;
12722 Record.readDeclarationNameInfo(DNI);
12723 C->setQualifierLoc(NNSL);
12724 C->setNameInfo(DNI);
12725
12726 unsigned NumVars = C->varlist_size();
12727 SmallVector<Expr *, 16> Vars;
12728 Vars.reserve(NumVars);
12729 for (unsigned I = 0; I != NumVars; ++I)
12730 Vars.push_back(Record.readSubExpr());
12731 C->setVarRefs(Vars);
12732 Vars.clear();
12733 for (unsigned I = 0; I != NumVars; ++I)
12734 Vars.push_back(Record.readSubExpr());
12735 C->setPrivates(Vars);
12736 Vars.clear();
12737 for (unsigned I = 0; I != NumVars; ++I)
12738 Vars.push_back(Record.readSubExpr());
12739 C->setLHSExprs(Vars);
12740 Vars.clear();
12741 for (unsigned I = 0; I != NumVars; ++I)
12742 Vars.push_back(Record.readSubExpr());
12743 C->setRHSExprs(Vars);
12744 Vars.clear();
12745 for (unsigned I = 0; I != NumVars; ++I)
12746 Vars.push_back(Record.readSubExpr());
12747 C->setReductionOps(Vars);
12748}
12749
12750void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12751 VisitOMPClauseWithPostUpdate(C);
12752 C->setLParenLoc(Record.readSourceLocation());
12753 C->setColonLoc(Record.readSourceLocation());
12754 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12755 DeclarationNameInfo DNI;
12756 Record.readDeclarationNameInfo(DNI);
12757 C->setQualifierLoc(NNSL);
12758 C->setNameInfo(DNI);
12759
12760 unsigned NumVars = C->varlist_size();
12761 SmallVector<Expr *, 16> Vars;
12762 Vars.reserve(NumVars);
12763 for (unsigned I = 0; I != NumVars; ++I)
12764 Vars.push_back(Record.readSubExpr());
12765 C->setVarRefs(Vars);
12766 Vars.clear();
12767 for (unsigned I = 0; I != NumVars; ++I)
12768 Vars.push_back(Record.readSubExpr());
12769 C->setPrivates(Vars);
12770 Vars.clear();
12771 for (unsigned I = 0; I != NumVars; ++I)
12772 Vars.push_back(Record.readSubExpr());
12773 C->setLHSExprs(Vars);
12774 Vars.clear();
12775 for (unsigned I = 0; I != NumVars; ++I)
12776 Vars.push_back(Record.readSubExpr());
12777 C->setRHSExprs(Vars);
12778 Vars.clear();
12779 for (unsigned I = 0; I != NumVars; ++I)
12780 Vars.push_back(Record.readSubExpr());
12781 C->setReductionOps(Vars);
12782 Vars.clear();
12783 for (unsigned I = 0; I != NumVars; ++I)
12784 Vars.push_back(Record.readSubExpr());
12785 C->setTaskgroupDescriptors(Vars);
12786}
12787
12788void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12789 VisitOMPClauseWithPostUpdate(C);
12790 C->setLParenLoc(Record.readSourceLocation());
12791 C->setColonLoc(Record.readSourceLocation());
12792 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12793 C->setModifierLoc(Record.readSourceLocation());
12794 unsigned NumVars = C->varlist_size();
12795 SmallVector<Expr *, 16> Vars;
12796 Vars.reserve(NumVars);
12797 for (unsigned i = 0; i != NumVars; ++i)
12798 Vars.push_back(Record.readSubExpr());
12799 C->setVarRefs(Vars);
12800 Vars.clear();
12801 for (unsigned i = 0; i != NumVars; ++i)
12802 Vars.push_back(Record.readSubExpr());
12803 C->setPrivates(Vars);
12804 Vars.clear();
12805 for (unsigned i = 0; i != NumVars; ++i)
12806 Vars.push_back(Record.readSubExpr());
12807 C->setInits(Vars);
12808 Vars.clear();
12809 for (unsigned i = 0; i != NumVars; ++i)
12810 Vars.push_back(Record.readSubExpr());
12811 C->setUpdates(Vars);
12812 Vars.clear();
12813 for (unsigned i = 0; i != NumVars; ++i)
12814 Vars.push_back(Record.readSubExpr());
12815 C->setFinals(Vars);
12816 C->setStep(Record.readSubExpr());
12817 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012818 Vars.clear();
12819 for (unsigned I = 0; I != NumVars + 1; ++I)
12820 Vars.push_back(Record.readSubExpr());
12821 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012822}
12823
12824void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12825 C->setLParenLoc(Record.readSourceLocation());
12826 C->setColonLoc(Record.readSourceLocation());
12827 unsigned NumVars = C->varlist_size();
12828 SmallVector<Expr *, 16> Vars;
12829 Vars.reserve(NumVars);
12830 for (unsigned i = 0; i != NumVars; ++i)
12831 Vars.push_back(Record.readSubExpr());
12832 C->setVarRefs(Vars);
12833 C->setAlignment(Record.readSubExpr());
12834}
12835
12836void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12837 C->setLParenLoc(Record.readSourceLocation());
12838 unsigned NumVars = C->varlist_size();
12839 SmallVector<Expr *, 16> Exprs;
12840 Exprs.reserve(NumVars);
12841 for (unsigned i = 0; i != NumVars; ++i)
12842 Exprs.push_back(Record.readSubExpr());
12843 C->setVarRefs(Exprs);
12844 Exprs.clear();
12845 for (unsigned i = 0; i != NumVars; ++i)
12846 Exprs.push_back(Record.readSubExpr());
12847 C->setSourceExprs(Exprs);
12848 Exprs.clear();
12849 for (unsigned i = 0; i != NumVars; ++i)
12850 Exprs.push_back(Record.readSubExpr());
12851 C->setDestinationExprs(Exprs);
12852 Exprs.clear();
12853 for (unsigned i = 0; i != NumVars; ++i)
12854 Exprs.push_back(Record.readSubExpr());
12855 C->setAssignmentOps(Exprs);
12856}
12857
12858void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12859 C->setLParenLoc(Record.readSourceLocation());
12860 unsigned NumVars = C->varlist_size();
12861 SmallVector<Expr *, 16> Exprs;
12862 Exprs.reserve(NumVars);
12863 for (unsigned i = 0; i != NumVars; ++i)
12864 Exprs.push_back(Record.readSubExpr());
12865 C->setVarRefs(Exprs);
12866 Exprs.clear();
12867 for (unsigned i = 0; i != NumVars; ++i)
12868 Exprs.push_back(Record.readSubExpr());
12869 C->setSourceExprs(Exprs);
12870 Exprs.clear();
12871 for (unsigned i = 0; i != NumVars; ++i)
12872 Exprs.push_back(Record.readSubExpr());
12873 C->setDestinationExprs(Exprs);
12874 Exprs.clear();
12875 for (unsigned i = 0; i != NumVars; ++i)
12876 Exprs.push_back(Record.readSubExpr());
12877 C->setAssignmentOps(Exprs);
12878}
12879
12880void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12881 C->setLParenLoc(Record.readSourceLocation());
12882 unsigned NumVars = C->varlist_size();
12883 SmallVector<Expr *, 16> Vars;
12884 Vars.reserve(NumVars);
12885 for (unsigned i = 0; i != NumVars; ++i)
12886 Vars.push_back(Record.readSubExpr());
12887 C->setVarRefs(Vars);
12888}
12889
12890void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12891 C->setLParenLoc(Record.readSourceLocation());
12892 C->setDependencyKind(
12893 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12894 C->setDependencyLoc(Record.readSourceLocation());
12895 C->setColonLoc(Record.readSourceLocation());
12896 unsigned NumVars = C->varlist_size();
12897 SmallVector<Expr *, 16> Vars;
12898 Vars.reserve(NumVars);
12899 for (unsigned I = 0; I != NumVars; ++I)
12900 Vars.push_back(Record.readSubExpr());
12901 C->setVarRefs(Vars);
12902 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12903 C->setLoopData(I, Record.readSubExpr());
12904}
12905
12906void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12907 VisitOMPClauseWithPreInit(C);
12908 C->setDevice(Record.readSubExpr());
12909 C->setLParenLoc(Record.readSourceLocation());
12910}
12911
12912void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12913 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012914 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12915 C->setMapTypeModifier(
12916 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12917 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12918 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012919 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12920 DeclarationNameInfo DNI;
12921 Record.readDeclarationNameInfo(DNI);
12922 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012923 C->setMapType(
12924 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12925 C->setMapLoc(Record.readSourceLocation());
12926 C->setColonLoc(Record.readSourceLocation());
12927 auto NumVars = C->varlist_size();
12928 auto UniqueDecls = C->getUniqueDeclarationsNum();
12929 auto TotalLists = C->getTotalComponentListNum();
12930 auto TotalComponents = C->getTotalComponentsNum();
12931
12932 SmallVector<Expr *, 16> Vars;
12933 Vars.reserve(NumVars);
12934 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012935 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012936 C->setVarRefs(Vars);
12937
Michael Kruse4304e9d2019-02-19 16:38:20 +000012938 SmallVector<Expr *, 16> UDMappers;
12939 UDMappers.reserve(NumVars);
12940 for (unsigned I = 0; I < NumVars; ++I)
12941 UDMappers.push_back(Record.readExpr());
12942 C->setUDMapperRefs(UDMappers);
12943
Kelvin Libe286f52018-09-15 13:54:15 +000012944 SmallVector<ValueDecl *, 16> Decls;
12945 Decls.reserve(UniqueDecls);
12946 for (unsigned i = 0; i < UniqueDecls; ++i)
12947 Decls.push_back(Record.readDeclAs<ValueDecl>());
12948 C->setUniqueDecls(Decls);
12949
12950 SmallVector<unsigned, 16> ListsPerDecl;
12951 ListsPerDecl.reserve(UniqueDecls);
12952 for (unsigned i = 0; i < UniqueDecls; ++i)
12953 ListsPerDecl.push_back(Record.readInt());
12954 C->setDeclNumLists(ListsPerDecl);
12955
12956 SmallVector<unsigned, 32> ListSizes;
12957 ListSizes.reserve(TotalLists);
12958 for (unsigned i = 0; i < TotalLists; ++i)
12959 ListSizes.push_back(Record.readInt());
12960 C->setComponentListSizes(ListSizes);
12961
12962 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12963 Components.reserve(TotalComponents);
12964 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012965 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012966 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12967 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12968 AssociatedExpr, AssociatedDecl));
12969 }
12970 C->setComponents(Components, ListSizes);
12971}
12972
Alexey Bataeve04483e2019-03-27 14:14:31 +000012973void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12974 C->setLParenLoc(Record.readSourceLocation());
12975 C->setColonLoc(Record.readSourceLocation());
12976 C->setAllocator(Record.readSubExpr());
12977 unsigned NumVars = C->varlist_size();
12978 SmallVector<Expr *, 16> Vars;
12979 Vars.reserve(NumVars);
12980 for (unsigned i = 0; i != NumVars; ++i)
12981 Vars.push_back(Record.readSubExpr());
12982 C->setVarRefs(Vars);
12983}
12984
Kelvin Libe286f52018-09-15 13:54:15 +000012985void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12986 VisitOMPClauseWithPreInit(C);
12987 C->setNumTeams(Record.readSubExpr());
12988 C->setLParenLoc(Record.readSourceLocation());
12989}
12990
12991void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12992 VisitOMPClauseWithPreInit(C);
12993 C->setThreadLimit(Record.readSubExpr());
12994 C->setLParenLoc(Record.readSourceLocation());
12995}
12996
12997void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12998 C->setPriority(Record.readSubExpr());
12999 C->setLParenLoc(Record.readSourceLocation());
13000}
13001
13002void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000013003 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000013004 C->setGrainsize(Record.readSubExpr());
13005 C->setLParenLoc(Record.readSourceLocation());
13006}
13007
13008void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000013009 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000013010 C->setNumTasks(Record.readSubExpr());
13011 C->setLParenLoc(Record.readSourceLocation());
13012}
13013
13014void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
13015 C->setHint(Record.readSubExpr());
13016 C->setLParenLoc(Record.readSourceLocation());
13017}
13018
13019void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
13020 VisitOMPClauseWithPreInit(C);
13021 C->setDistScheduleKind(
13022 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
13023 C->setChunkSize(Record.readSubExpr());
13024 C->setLParenLoc(Record.readSourceLocation());
13025 C->setDistScheduleKindLoc(Record.readSourceLocation());
13026 C->setCommaLoc(Record.readSourceLocation());
13027}
13028
13029void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
13030 C->setDefaultmapKind(
13031 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
13032 C->setDefaultmapModifier(
13033 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
13034 C->setLParenLoc(Record.readSourceLocation());
13035 C->setDefaultmapModifierLoc(Record.readSourceLocation());
13036 C->setDefaultmapKindLoc(Record.readSourceLocation());
13037}
13038
13039void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
13040 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000013041 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13042 DeclarationNameInfo DNI;
13043 Record.readDeclarationNameInfo(DNI);
13044 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013045 auto NumVars = C->varlist_size();
13046 auto UniqueDecls = C->getUniqueDeclarationsNum();
13047 auto TotalLists = C->getTotalComponentListNum();
13048 auto TotalComponents = C->getTotalComponentsNum();
13049
13050 SmallVector<Expr *, 16> Vars;
13051 Vars.reserve(NumVars);
13052 for (unsigned i = 0; i != NumVars; ++i)
13053 Vars.push_back(Record.readSubExpr());
13054 C->setVarRefs(Vars);
13055
Michael Kruse01f670d2019-02-22 22:29:42 +000013056 SmallVector<Expr *, 16> UDMappers;
13057 UDMappers.reserve(NumVars);
13058 for (unsigned I = 0; I < NumVars; ++I)
13059 UDMappers.push_back(Record.readSubExpr());
13060 C->setUDMapperRefs(UDMappers);
13061
Kelvin Libe286f52018-09-15 13:54:15 +000013062 SmallVector<ValueDecl *, 16> Decls;
13063 Decls.reserve(UniqueDecls);
13064 for (unsigned i = 0; i < UniqueDecls; ++i)
13065 Decls.push_back(Record.readDeclAs<ValueDecl>());
13066 C->setUniqueDecls(Decls);
13067
13068 SmallVector<unsigned, 16> ListsPerDecl;
13069 ListsPerDecl.reserve(UniqueDecls);
13070 for (unsigned i = 0; i < UniqueDecls; ++i)
13071 ListsPerDecl.push_back(Record.readInt());
13072 C->setDeclNumLists(ListsPerDecl);
13073
13074 SmallVector<unsigned, 32> ListSizes;
13075 ListSizes.reserve(TotalLists);
13076 for (unsigned i = 0; i < TotalLists; ++i)
13077 ListSizes.push_back(Record.readInt());
13078 C->setComponentListSizes(ListSizes);
13079
13080 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13081 Components.reserve(TotalComponents);
13082 for (unsigned i = 0; i < TotalComponents; ++i) {
13083 Expr *AssociatedExpr = Record.readSubExpr();
13084 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13085 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13086 AssociatedExpr, AssociatedDecl));
13087 }
13088 C->setComponents(Components, ListSizes);
13089}
13090
13091void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
13092 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000013093 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13094 DeclarationNameInfo DNI;
13095 Record.readDeclarationNameInfo(DNI);
13096 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013097 auto NumVars = C->varlist_size();
13098 auto UniqueDecls = C->getUniqueDeclarationsNum();
13099 auto TotalLists = C->getTotalComponentListNum();
13100 auto TotalComponents = C->getTotalComponentsNum();
13101
13102 SmallVector<Expr *, 16> Vars;
13103 Vars.reserve(NumVars);
13104 for (unsigned i = 0; i != NumVars; ++i)
13105 Vars.push_back(Record.readSubExpr());
13106 C->setVarRefs(Vars);
13107
Michael Kruse0336c752019-02-25 20:34:15 +000013108 SmallVector<Expr *, 16> UDMappers;
13109 UDMappers.reserve(NumVars);
13110 for (unsigned I = 0; I < NumVars; ++I)
13111 UDMappers.push_back(Record.readSubExpr());
13112 C->setUDMapperRefs(UDMappers);
13113
Kelvin Libe286f52018-09-15 13:54:15 +000013114 SmallVector<ValueDecl *, 16> Decls;
13115 Decls.reserve(UniqueDecls);
13116 for (unsigned i = 0; i < UniqueDecls; ++i)
13117 Decls.push_back(Record.readDeclAs<ValueDecl>());
13118 C->setUniqueDecls(Decls);
13119
13120 SmallVector<unsigned, 16> ListsPerDecl;
13121 ListsPerDecl.reserve(UniqueDecls);
13122 for (unsigned i = 0; i < UniqueDecls; ++i)
13123 ListsPerDecl.push_back(Record.readInt());
13124 C->setDeclNumLists(ListsPerDecl);
13125
13126 SmallVector<unsigned, 32> ListSizes;
13127 ListSizes.reserve(TotalLists);
13128 for (unsigned i = 0; i < TotalLists; ++i)
13129 ListSizes.push_back(Record.readInt());
13130 C->setComponentListSizes(ListSizes);
13131
13132 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13133 Components.reserve(TotalComponents);
13134 for (unsigned i = 0; i < TotalComponents; ++i) {
13135 Expr *AssociatedExpr = Record.readSubExpr();
13136 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13137 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13138 AssociatedExpr, AssociatedDecl));
13139 }
13140 C->setComponents(Components, ListSizes);
13141}
13142
13143void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13144 C->setLParenLoc(Record.readSourceLocation());
13145 auto NumVars = C->varlist_size();
13146 auto UniqueDecls = C->getUniqueDeclarationsNum();
13147 auto TotalLists = C->getTotalComponentListNum();
13148 auto TotalComponents = C->getTotalComponentsNum();
13149
13150 SmallVector<Expr *, 16> Vars;
13151 Vars.reserve(NumVars);
13152 for (unsigned i = 0; i != NumVars; ++i)
13153 Vars.push_back(Record.readSubExpr());
13154 C->setVarRefs(Vars);
13155 Vars.clear();
13156 for (unsigned i = 0; i != NumVars; ++i)
13157 Vars.push_back(Record.readSubExpr());
13158 C->setPrivateCopies(Vars);
13159 Vars.clear();
13160 for (unsigned i = 0; i != NumVars; ++i)
13161 Vars.push_back(Record.readSubExpr());
13162 C->setInits(Vars);
13163
13164 SmallVector<ValueDecl *, 16> Decls;
13165 Decls.reserve(UniqueDecls);
13166 for (unsigned i = 0; i < UniqueDecls; ++i)
13167 Decls.push_back(Record.readDeclAs<ValueDecl>());
13168 C->setUniqueDecls(Decls);
13169
13170 SmallVector<unsigned, 16> ListsPerDecl;
13171 ListsPerDecl.reserve(UniqueDecls);
13172 for (unsigned i = 0; i < UniqueDecls; ++i)
13173 ListsPerDecl.push_back(Record.readInt());
13174 C->setDeclNumLists(ListsPerDecl);
13175
13176 SmallVector<unsigned, 32> ListSizes;
13177 ListSizes.reserve(TotalLists);
13178 for (unsigned i = 0; i < TotalLists; ++i)
13179 ListSizes.push_back(Record.readInt());
13180 C->setComponentListSizes(ListSizes);
13181
13182 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13183 Components.reserve(TotalComponents);
13184 for (unsigned i = 0; i < TotalComponents; ++i) {
13185 Expr *AssociatedExpr = Record.readSubExpr();
13186 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13187 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13188 AssociatedExpr, AssociatedDecl));
13189 }
13190 C->setComponents(Components, ListSizes);
13191}
13192
13193void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13194 C->setLParenLoc(Record.readSourceLocation());
13195 auto NumVars = C->varlist_size();
13196 auto UniqueDecls = C->getUniqueDeclarationsNum();
13197 auto TotalLists = C->getTotalComponentListNum();
13198 auto TotalComponents = C->getTotalComponentsNum();
13199
13200 SmallVector<Expr *, 16> Vars;
13201 Vars.reserve(NumVars);
13202 for (unsigned i = 0; i != NumVars; ++i)
13203 Vars.push_back(Record.readSubExpr());
13204 C->setVarRefs(Vars);
13205 Vars.clear();
13206
13207 SmallVector<ValueDecl *, 16> Decls;
13208 Decls.reserve(UniqueDecls);
13209 for (unsigned i = 0; i < UniqueDecls; ++i)
13210 Decls.push_back(Record.readDeclAs<ValueDecl>());
13211 C->setUniqueDecls(Decls);
13212
13213 SmallVector<unsigned, 16> ListsPerDecl;
13214 ListsPerDecl.reserve(UniqueDecls);
13215 for (unsigned i = 0; i < UniqueDecls; ++i)
13216 ListsPerDecl.push_back(Record.readInt());
13217 C->setDeclNumLists(ListsPerDecl);
13218
13219 SmallVector<unsigned, 32> ListSizes;
13220 ListSizes.reserve(TotalLists);
13221 for (unsigned i = 0; i < TotalLists; ++i)
13222 ListSizes.push_back(Record.readInt());
13223 C->setComponentListSizes(ListSizes);
13224
13225 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13226 Components.reserve(TotalComponents);
13227 for (unsigned i = 0; i < TotalComponents; ++i) {
13228 Expr *AssociatedExpr = Record.readSubExpr();
13229 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13230 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13231 AssociatedExpr, AssociatedDecl));
13232 }
13233 C->setComponents(Components, ListSizes);
13234}