blob: 10276736414b59c6440f8c2dcfeaf308e0c7a6ec [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
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013#include "clang/Basic/OpenMPKinds.h"
John McCallc2f18312019-12-14 03:01:28 -050014#include "clang/Serialization/ASTRecordReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
John McCalld505e572019-12-13 21:54:44 -050017#include "clang/AST/AbstractTypeReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000020#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/ASTUnresolvedSet.h"
22#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000023#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000025#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000026#include "clang/AST/DeclGroup.h"
27#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000029#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000032#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/AST/NestedNameSpecifier.h"
John McCallc2f18312019-12-14 03:01:28 -050034#include "clang/AST/OpenMPClause.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000035#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000037#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000039#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000040#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000042#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000044#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000045#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000049#include "clang/Basic/IdentifierTable.h"
50#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000051#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000052#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include "clang/Basic/ObjCRuntime.h"
54#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000055#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000057#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include "clang/Basic/SourceManager.h"
59#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Basic/TargetInfo.h"
62#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000063#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000064#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000065#include "clang/Lex/HeaderSearch.h"
66#include "clang/Lex/HeaderSearchOptions.h"
67#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000069#include "clang/Lex/PreprocessingRecord.h"
70#include "clang/Lex/Preprocessor.h"
71#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000072#include "clang/Lex/Token.h"
73#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000074#include "clang/Sema/Scope.h"
75#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000076#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000077#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000078#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000080#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000081#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080082#include "clang/Serialization/ModuleFile.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000083#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000085#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000086#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000087#include "llvm/ADT/APFloat.h"
88#include "llvm/ADT/APInt.h"
89#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000090#include "llvm/ADT/ArrayRef.h"
91#include "llvm/ADT/DenseMap.h"
Serge Pavlovc7ff5b32020-03-26 14:51:09 +070092#include "llvm/ADT/FloatingPointMode.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000093#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000094#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000095#include "llvm/ADT/IntrusiveRefCntPtr.h"
96#include "llvm/ADT/None.h"
97#include "llvm/ADT/Optional.h"
98#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000099#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000101#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000102#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000103#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000104#include "llvm/ADT/StringMap.h"
105#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000106#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000107#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000108#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000110#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000111#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000112#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000113#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000114#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000115#include "llvm/Support/ErrorHandling.h"
116#include "llvm/Support/FileSystem.h"
117#include "llvm/Support/MemoryBuffer.h"
118#include "llvm/Support/Path.h"
119#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000120#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000121#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000122#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000123#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000125#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000127#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000128#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000129#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000130#include <limits>
131#include <map>
132#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000134#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000135#include <tuple>
136#include <utility>
137#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000138
139using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000140using namespace clang::serialization;
141using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000142using llvm::BitstreamCursor;
Serge Pavlovc7ff5b32020-03-26 14:51:09 +0700143using llvm::RoundingMode;
Guy Benyei11169dd2012-12-18 14:30:41 +0000144
Ben Langmuircb69b572014-03-07 06:40:32 +0000145//===----------------------------------------------------------------------===//
146// ChainedASTReaderListener implementation
147//===----------------------------------------------------------------------===//
148
149bool
150ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
151 return First->ReadFullVersionInformation(FullVersion) ||
152 Second->ReadFullVersionInformation(FullVersion);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
156 First->ReadModuleName(ModuleName);
157 Second->ReadModuleName(ModuleName);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000160void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
161 First->ReadModuleMapFile(ModuleMapPath);
162 Second->ReadModuleMapFile(ModuleMapPath);
163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000164
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000165bool
166ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
167 bool Complain,
168 bool AllowCompatibleDifferences) {
169 return First->ReadLanguageOptions(LangOpts, Complain,
170 AllowCompatibleDifferences) ||
171 Second->ReadLanguageOptions(LangOpts, Complain,
172 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000173}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000174
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000175bool ChainedASTReaderListener::ReadTargetOptions(
176 const TargetOptions &TargetOpts, bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadTargetOptions(TargetOpts, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadTargetOptions(TargetOpts, Complain,
181 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000183
Ben Langmuircb69b572014-03-07 06:40:32 +0000184bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000185 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000186 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
187 Second->ReadDiagnosticOptions(DiagOpts, Complain);
188}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000189
Ben Langmuircb69b572014-03-07 06:40:32 +0000190bool
191ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
192 bool Complain) {
193 return First->ReadFileSystemOptions(FSOpts, Complain) ||
194 Second->ReadFileSystemOptions(FSOpts, Complain);
195}
196
197bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000198 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
199 bool Complain) {
200 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
201 Complain) ||
202 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
203 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000204}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000205
Ben Langmuircb69b572014-03-07 06:40:32 +0000206bool ChainedASTReaderListener::ReadPreprocessorOptions(
207 const PreprocessorOptions &PPOpts, bool Complain,
208 std::string &SuggestedPredefines) {
209 return First->ReadPreprocessorOptions(PPOpts, Complain,
210 SuggestedPredefines) ||
211 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
212}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000213
Ben Langmuircb69b572014-03-07 06:40:32 +0000214void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
215 unsigned Value) {
216 First->ReadCounter(M, Value);
217 Second->ReadCounter(M, Value);
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsInputFileVisitation() {
221 return First->needsInputFileVisitation() ||
222 Second->needsInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Ben Langmuircb69b572014-03-07 06:40:32 +0000225bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
226 return First->needsSystemInputFileVisitation() ||
227 Second->needsSystemInputFileVisitation();
228}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000229
Richard Smith216a3bd2015-08-13 17:57:10 +0000230void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
231 ModuleKind Kind) {
232 First->visitModuleFile(Filename, Kind);
233 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000234}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000235
Ben Langmuircb69b572014-03-07 06:40:32 +0000236bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000237 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 bool isOverridden,
239 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 bool Continue = false;
241 if (First->needsInputFileVisitation() &&
242 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000243 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
244 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000245 if (Second->needsInputFileVisitation() &&
246 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000247 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
248 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000249 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000250}
251
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000252void ChainedASTReaderListener::readModuleFileExtension(
253 const ModuleFileExtensionMetadata &Metadata) {
254 First->readModuleFileExtension(Metadata);
255 Second->readModuleFileExtension(Metadata);
256}
257
Guy Benyei11169dd2012-12-18 14:30:41 +0000258//===----------------------------------------------------------------------===//
259// PCH validator implementation
260//===----------------------------------------------------------------------===//
261
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000262ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000265/// language options.
266///
267/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000268/// \param AllowCompatibleDifferences If true, differences between compatible
269/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000270///
271/// \returns true if the languagae options mis-match, false otherwise.
272static bool checkLanguageOptions(const LangOptions &LangOpts,
273 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000274 DiagnosticsEngine *Diags,
275 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000276#define LANGOPT(Name, Bits, Default, Description) \
277 if (ExistingLangOpts.Name != LangOpts.Name) { \
278 if (Diags) \
279 Diags->Report(diag::err_pch_langopt_mismatch) \
280 << Description << LangOpts.Name << ExistingLangOpts.Name; \
281 return true; \
282 }
283
284#define VALUE_LANGOPT(Name, Bits, Default, Description) \
285 if (ExistingLangOpts.Name != LangOpts.Name) { \
286 if (Diags) \
287 Diags->Report(diag::err_pch_langopt_value_mismatch) \
288 << Description; \
289 return true; \
290 }
291
292#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
293 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
294 if (Diags) \
295 Diags->Report(diag::err_pch_langopt_value_mismatch) \
296 << Description; \
297 return true; \
298 }
299
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000300#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
301 if (!AllowCompatibleDifferences) \
302 LANGOPT(Name, Bits, Default, Description)
303
304#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
305 if (!AllowCompatibleDifferences) \
306 ENUM_LANGOPT(Name, Bits, Default, Description)
307
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000308#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
309 if (!AllowCompatibleDifferences) \
310 VALUE_LANGOPT(Name, Bits, Default, Description)
311
Guy Benyei11169dd2012-12-18 14:30:41 +0000312#define BENIGN_LANGOPT(Name, Bits, Default, Description)
313#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000314#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000315#include "clang/Basic/LangOptions.def"
316
Ben Langmuircd98cb72015-06-23 18:20:18 +0000317 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
318 if (Diags)
319 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
320 return true;
321 }
322
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
324 if (Diags)
325 Diags->Report(diag::err_pch_langopt_value_mismatch)
326 << "target Objective-C runtime";
327 return true;
328 }
329
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000330 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
331 LangOpts.CommentOpts.BlockCommandNames) {
332 if (Diags)
333 Diags->Report(diag::err_pch_langopt_value_mismatch)
334 << "block command names";
335 return true;
336 }
337
Vedant Kumar85a83c22017-06-01 20:01:01 +0000338 // Sanitizer feature mismatches are treated as compatible differences. If
339 // compatible differences aren't allowed, we still only want to check for
340 // mismatches of non-modular sanitizers (the only ones which can affect AST
341 // generation).
342 if (!AllowCompatibleDifferences) {
343 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
344 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
345 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
346 ExistingSanitizers.clear(ModularSanitizers);
347 ImportedSanitizers.clear(ModularSanitizers);
348 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
349 const std::string Flag = "-fsanitize=";
350 if (Diags) {
351#define SANITIZER(NAME, ID) \
352 { \
353 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
354 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
355 if (InExistingModule != InImportedModule) \
356 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
357 << InExistingModule << (Flag + NAME); \
358 }
359#include "clang/Basic/Sanitizers.def"
360 }
361 return true;
362 }
363 }
364
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 return false;
366}
367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000368/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000369/// target options.
370///
371/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
372///
373/// \returns true if the target options mis-match, false otherwise.
374static bool checkTargetOptions(const TargetOptions &TargetOpts,
375 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000376 DiagnosticsEngine *Diags,
377 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000378#define CHECK_TARGET_OPT(Field, Name) \
379 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
380 if (Diags) \
381 Diags->Report(diag::err_pch_targetopt_mismatch) \
382 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
383 return true; \
384 }
385
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000386 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000389
390 // We can tolerate different CPUs in many cases, notably when one CPU
391 // supports a strict superset of another. When allowing compatible
392 // differences skip this check.
393 if (!AllowCompatibleDifferences)
394 CHECK_TARGET_OPT(CPU, "target CPU");
395
Guy Benyei11169dd2012-12-18 14:30:41 +0000396#undef CHECK_TARGET_OPT
397
398 // Compare feature sets.
399 SmallVector<StringRef, 4> ExistingFeatures(
400 ExistingTargetOpts.FeaturesAsWritten.begin(),
401 ExistingTargetOpts.FeaturesAsWritten.end());
402 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
403 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000404 llvm::sort(ExistingFeatures);
405 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000406
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000407 // We compute the set difference in both directions explicitly so that we can
408 // diagnose the differences differently.
409 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
410 std::set_difference(
411 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
412 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
413 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
414 ExistingFeatures.begin(), ExistingFeatures.end(),
415 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 // If we are allowing compatible differences and the read feature set is
418 // a strict subset of the existing feature set, there is nothing to diagnose.
419 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
420 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000421
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000422 if (Diags) {
423 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000425 << /* is-existing-feature */ false << Feature;
426 for (StringRef Feature : UnmatchedExistingFeatures)
427 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
428 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000429 }
430
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000431 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000432}
433
434bool
435PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000436 bool Complain,
437 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000438 const LangOptions &ExistingLangOpts = PP.getLangOpts();
439 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000440 Complain ? &Reader.Diags : nullptr,
441 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000442}
443
444bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000445 bool Complain,
446 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
448 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000449 Complain ? &Reader.Diags : nullptr,
450 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000451}
452
453namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000454
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000455using MacroDefinitionsMap =
456 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
457using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000458
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000460
Ben Langmuirb92de022014-04-29 16:25:26 +0000461static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
462 DiagnosticsEngine &Diags,
463 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000464 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000465
466 // Check current mappings for new -Werror mappings, and the stored mappings
467 // for cases that were explicitly mapped to *not* be errors that are now
468 // errors because of options like -Werror.
469 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
470
Vedant Kumar48b4f762018-04-14 01:40:48 +0000471 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000472 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
473 diag::kind DiagID = DiagIDMappingPair.first;
474 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
475 if (CurLevel < DiagnosticsEngine::Error)
476 continue; // not significant
477 Level StoredLevel =
478 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
479 if (StoredLevel < DiagnosticsEngine::Error) {
480 if (Complain)
481 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
482 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
483 return true;
484 }
485 }
486 }
487
488 return false;
489}
490
Alp Tokerac4e8e52014-06-22 21:58:33 +0000491static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
492 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
493 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
494 return true;
495 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000496}
497
498static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
499 DiagnosticsEngine &Diags,
500 bool IsSystem, bool Complain) {
501 // Top-level options
502 if (IsSystem) {
503 if (Diags.getSuppressSystemWarnings())
504 return false;
505 // If -Wsystem-headers was not enabled before, be conservative
506 if (StoredDiags.getSuppressSystemWarnings()) {
507 if (Complain)
508 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
509 return true;
510 }
511 }
512
513 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
514 if (Complain)
515 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
516 return true;
517 }
518
519 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
520 !StoredDiags.getEnableAllWarnings()) {
521 if (Complain)
522 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
523 return true;
524 }
525
526 if (isExtHandlingFromDiagsError(Diags) &&
527 !isExtHandlingFromDiagsError(StoredDiags)) {
528 if (Complain)
529 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
530 return true;
531 }
532
533 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
534}
535
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000536/// Return the top import module if it is implicit, nullptr otherwise.
537static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
538 Preprocessor &PP) {
539 // If the original import came from a file explicitly generated by the user,
540 // don't check the diagnostic mappings.
541 // FIXME: currently this is approximated by checking whether this is not a
542 // module import of an implicitly-loaded module file.
543 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
544 // the transitive closure of its imports, since unrelated modules cannot be
545 // imported until after this module finishes validation.
546 ModuleFile *TopImport = &*ModuleMgr.rbegin();
547 while (!TopImport->ImportedBy.empty())
548 TopImport = TopImport->ImportedBy[0];
549 if (TopImport->Kind != MK_ImplicitModule)
550 return nullptr;
551
552 StringRef ModuleName = TopImport->ModuleName;
553 assert(!ModuleName.empty() && "diagnostic options read before module name");
554
555 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
556 assert(M && "missing module");
557 return M;
558}
559
Ben Langmuirb92de022014-04-29 16:25:26 +0000560bool PCHValidator::ReadDiagnosticOptions(
561 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
562 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
563 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
564 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000565 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000566 // This should never fail, because we would have processed these options
567 // before writing them to an ASTFile.
568 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
569
570 ModuleManager &ModuleMgr = Reader.getModuleManager();
571 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
572
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000573 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
574 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000575 return false;
576
Ben Langmuirb92de022014-04-29 16:25:26 +0000577 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
578 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000579 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
580 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000581}
582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000583/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000584/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000585static void
586collectMacroDefinitions(const PreprocessorOptions &PPOpts,
587 MacroDefinitionsMap &Macros,
588 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000589 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
590 StringRef Macro = PPOpts.Macros[I].first;
591 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000592
593 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
594 StringRef MacroName = MacroPair.first;
595 StringRef MacroBody = MacroPair.second;
596
597 // For an #undef'd macro, we only care about the name.
598 if (IsUndef) {
599 if (MacroNames && !Macros.count(MacroName))
600 MacroNames->push_back(MacroName);
601
602 Macros[MacroName] = std::make_pair("", true);
603 continue;
604 }
605
606 // For a #define'd macro, figure out the actual definition.
607 if (MacroName.size() == Macro.size())
608 MacroBody = "1";
609 else {
610 // Note: GCC drops anything following an end-of-line character.
611 StringRef::size_type End = MacroBody.find_first_of("\n\r");
612 MacroBody = MacroBody.substr(0, End);
613 }
614
615 if (MacroNames && !Macros.count(MacroName))
616 MacroNames->push_back(MacroName);
617 Macros[MacroName] = std::make_pair(MacroBody, false);
618 }
619}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000622/// against the preprocessor options in an existing preprocessor.
623///
624/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000625/// \param Validate If true, validate preprocessor options. If false, allow
626/// macros defined by \p ExistingPPOpts to override those defined by
627/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000628static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
629 const PreprocessorOptions &ExistingPPOpts,
630 DiagnosticsEngine *Diags,
631 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000632 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000633 const LangOptions &LangOpts,
634 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 // Check macro definitions.
636 MacroDefinitionsMap ASTFileMacros;
637 collectMacroDefinitions(PPOpts, ASTFileMacros);
638 MacroDefinitionsMap ExistingMacros;
639 SmallVector<StringRef, 4> ExistingMacroNames;
640 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
641
Vedant Kumar48b4f762018-04-14 01:40:48 +0000642 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000644 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
646
647 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000648 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
649 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000650 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 // FIXME: Check whether this identifier was referenced anywhere in the
652 // AST file. If so, we should reject the AST file. Unfortunately, this
653 // information isn't in the control block. What shall we do about it?
654
655 if (Existing.second) {
656 SuggestedPredefines += "#undef ";
657 SuggestedPredefines += MacroName.str();
658 SuggestedPredefines += '\n';
659 } else {
660 SuggestedPredefines += "#define ";
661 SuggestedPredefines += MacroName.str();
662 SuggestedPredefines += ' ';
663 SuggestedPredefines += Existing.first.str();
664 SuggestedPredefines += '\n';
665 }
666 continue;
667 }
668
669 // If the macro was defined in one but undef'd in the other, we have a
670 // conflict.
671 if (Existing.second != Known->second.second) {
672 if (Diags) {
673 Diags->Report(diag::err_pch_macro_def_undef)
674 << MacroName << Known->second.second;
675 }
676 return true;
677 }
678
679 // If the macro was #undef'd in both, or if the macro bodies are identical,
680 // it's fine.
681 if (Existing.second || Existing.first == Known->second.first)
682 continue;
683
684 // The macro bodies differ; complain.
685 if (Diags) {
686 Diags->Report(diag::err_pch_macro_def_conflict)
687 << MacroName << Known->second.first << Existing.first;
688 }
689 return true;
690 }
691
692 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000693 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000694 if (Diags) {
695 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
696 }
697 return true;
698 }
699
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000700 // Detailed record is important since it is used for the module cache hash.
701 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000702 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000703 if (Diags) {
704 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
705 }
706 return true;
707 }
708
Guy Benyei11169dd2012-12-18 14:30:41 +0000709 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000710 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
711 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000712
713 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
714 !ExistingPPOpts.PCHThroughHeader.empty()) {
715 // In case the through header is an include, we must add all the includes
716 // to the predefines so the start point can be determined.
717 SuggestedPredefines += "#include \"";
718 SuggestedPredefines += File;
719 SuggestedPredefines += "\"\n";
720 continue;
721 }
722
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 if (File == ExistingPPOpts.ImplicitPCHInclude)
724 continue;
725
726 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
727 != PPOpts.Includes.end())
728 continue;
729
730 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000731 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 SuggestedPredefines += "\"\n";
733 }
734
Vedant Kumar48b4f762018-04-14 01:40:48 +0000735 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
736 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
738 File)
739 != PPOpts.MacroIncludes.end())
740 continue;
741
742 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000743 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 SuggestedPredefines += "\"\n##\n";
745 }
746
747 return false;
748}
749
750bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
751 bool Complain,
752 std::string &SuggestedPredefines) {
753 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
754
755 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000756 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000758 SuggestedPredefines,
759 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000760}
761
Yaxun Liu43712e02016-09-07 18:40:20 +0000762bool SimpleASTReaderListener::ReadPreprocessorOptions(
763 const PreprocessorOptions &PPOpts,
764 bool Complain,
765 std::string &SuggestedPredefines) {
766 return checkPreprocessorOptions(PPOpts,
767 PP.getPreprocessorOpts(),
768 nullptr,
769 PP.getFileManager(),
770 SuggestedPredefines,
771 PP.getLangOpts(),
772 false);
773}
774
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000775/// Check the header search options deserialized from the control block
776/// against the header search options in an existing preprocessor.
777///
778/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
779static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
780 StringRef SpecificModuleCachePath,
781 StringRef ExistingModuleCachePath,
782 DiagnosticsEngine *Diags,
783 const LangOptions &LangOpts) {
784 if (LangOpts.Modules) {
785 if (SpecificModuleCachePath != ExistingModuleCachePath) {
786 if (Diags)
787 Diags->Report(diag::err_pch_modulecache_mismatch)
788 << SpecificModuleCachePath << ExistingModuleCachePath;
789 return true;
790 }
791 }
792
793 return false;
794}
795
796bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
797 StringRef SpecificModuleCachePath,
798 bool Complain) {
799 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
800 PP.getHeaderSearchInfo().getModuleCachePath(),
801 Complain ? &Reader.Diags : nullptr,
802 PP.getLangOpts());
803}
804
Guy Benyei11169dd2012-12-18 14:30:41 +0000805void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
806 PP.setCounterValue(Value);
807}
808
809//===----------------------------------------------------------------------===//
810// AST reader implementation
811//===----------------------------------------------------------------------===//
812
Nico Weber824285e2014-05-08 04:26:47 +0000813void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
814 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000816 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000817}
818
Guy Benyei11169dd2012-12-18 14:30:41 +0000819unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
820 return serialization::ComputeHash(Sel);
821}
822
Guy Benyei11169dd2012-12-18 14:30:41 +0000823std::pair<unsigned, unsigned>
824ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000826
Justin Bogner57ba0b22014-03-28 22:03:24 +0000827 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
828 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 return std::make_pair(KeyLen, DataLen);
830}
831
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000832ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000833ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000834 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000835
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000837 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
838 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
839 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 if (N == 0)
841 return SelTable.getNullarySelector(FirstII);
842 else if (N == 1)
843 return SelTable.getUnarySelector(FirstII);
844
845 SmallVector<IdentifierInfo *, 16> Args;
846 Args.push_back(FirstII);
847 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000848 Args.push_back(Reader.getLocalIdentifier(
849 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000850
851 return SelTable.getSelector(N, Args.data());
852}
853
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000854ASTSelectorLookupTrait::data_type
855ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000856 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000857 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000858
859 data_type Result;
860
Justin Bogner57ba0b22014-03-28 22:03:24 +0000861 Result.ID = Reader.getGlobalSelectorID(
862 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000863 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
864 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
865 Result.InstanceBits = FullInstanceBits & 0x3;
866 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
867 Result.FactoryBits = FullFactoryBits & 0x3;
868 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
869 unsigned NumInstanceMethods = FullInstanceBits >> 3;
870 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000871
872 // Load instance methods
873 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000874 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000875 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 Result.Instance.push_back(Method);
877 }
878
879 // Load factory methods
880 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000881 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000882 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 Result.Factory.push_back(Method);
884 }
885
886 return Result;
887}
888
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000890 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000891}
892
893std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000894ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000895 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000896
Justin Bogner57ba0b22014-03-28 22:03:24 +0000897 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
898 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 return std::make_pair(KeyLen, DataLen);
900}
901
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000902ASTIdentifierLookupTraitBase::internal_key_type
903ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000905 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000906}
907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000908/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000909static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
910 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000911 return II.hadMacroDefinition() ||
912 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000913 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000914 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000915 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000916 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000917}
918
Richard Smith76c2f2c2015-07-17 20:09:43 +0000919static bool readBit(unsigned &Bits) {
920 bool Value = Bits & 0x1;
921 Bits >>= 1;
922 return Value;
923}
924
Richard Smith79bf9202015-08-24 03:33:22 +0000925IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
926 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000927
Richard Smith79bf9202015-08-24 03:33:22 +0000928 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
929 return Reader.getGlobalIdentifierID(F, RawID >> 1);
930}
931
Richard Smitheb4b58f62016-02-05 01:40:54 +0000932static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
933 if (!II.isFromAST()) {
934 II.setIsFromAST();
935 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
936 if (isInterestingIdentifier(Reader, II, IsModule))
937 II.setChangedSinceDeserialization();
938 }
939}
940
Guy Benyei11169dd2012-12-18 14:30:41 +0000941IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
942 const unsigned char* d,
943 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000945
Justin Bogner57ba0b22014-03-28 22:03:24 +0000946 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 bool IsInteresting = RawID & 0x01;
948
949 // Wipe out the "is interesting" bit.
950 RawID = RawID >> 1;
951
Richard Smith76c2f2c2015-07-17 20:09:43 +0000952 // Build the IdentifierInfo and link the identifier ID with it.
953 IdentifierInfo *II = KnownII;
954 if (!II) {
955 II = &Reader.getIdentifierTable().getOwn(k);
956 KnownII = II;
957 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000958 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000959 Reader.markIdentifierUpToDate(II);
960
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
962 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000963 // For uninteresting identifiers, there's nothing else to do. Just notify
964 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 return II;
967 }
968
Justin Bogner57ba0b22014-03-28 22:03:24 +0000969 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
970 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000971 bool CPlusPlusOperatorKeyword = readBit(Bits);
972 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000973 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000974 bool Poisoned = readBit(Bits);
975 bool ExtensionToken = readBit(Bits);
976 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977
978 assert(Bits == 0 && "Extra bits in the identifier?");
979 DataLen -= 8;
980
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 // Set or check the various bits in the IdentifierInfo structure.
982 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000983 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000984 II->revertTokenIDToIdentifier();
985 if (!F.isModule())
986 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
987 else if (HasRevertedBuiltin && II->getBuiltinID()) {
988 II->revertBuiltin();
989 assert((II->hasRevertedBuiltin() ||
990 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
991 "Incorrect ObjC keyword or builtin ID");
992 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 assert(II->isExtensionToken() == ExtensionToken &&
994 "Incorrect extension token flag");
995 (void)ExtensionToken;
996 if (Poisoned)
997 II->setIsPoisoned(true);
998 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
999 "Incorrect C++ operator keyword flag");
1000 (void)CPlusPlusOperatorKeyword;
1001
1002 // If this identifier is a macro, deserialize the macro
1003 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +00001004 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001005 uint32_t MacroDirectivesOffset =
1006 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001007 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001008
Richard Smithd7329392015-04-21 21:46:32 +00001009 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 }
1011
1012 Reader.SetIdentifierInfo(ID, II);
1013
1014 // Read all of the declarations visible at global scope with this
1015 // name.
1016 if (DataLen > 0) {
1017 SmallVector<uint32_t, 4> DeclIDs;
1018 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001019 DeclIDs.push_back(Reader.getGlobalDeclID(
1020 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1022 }
1023
1024 return II;
1025}
1026
Richard Smitha06c7e62015-08-26 23:55:49 +00001027DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1028 : Kind(Name.getNameKind()) {
1029 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 case DeclarationName::ObjCZeroArgSelector:
1034 case DeclarationName::ObjCOneArgSelector:
1035 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001036 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 break;
1038 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001039 Data = Name.getCXXOverloadedOperator();
1040 break;
1041 case DeclarationName::CXXLiteralOperatorName:
1042 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1043 break;
Richard Smith35845152017-02-07 01:37:30 +00001044 case DeclarationName::CXXDeductionGuideName:
1045 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1046 ->getDeclName().getAsIdentifierInfo();
1047 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001048 case DeclarationName::CXXConstructorName:
1049 case DeclarationName::CXXDestructorName:
1050 case DeclarationName::CXXConversionFunctionName:
1051 case DeclarationName::CXXUsingDirective:
1052 Data = 0;
1053 break;
1054 }
1055}
1056
1057unsigned DeclarationNameKey::getHash() const {
1058 llvm::FoldingSetNodeID ID;
1059 ID.AddInteger(Kind);
1060
1061 switch (Kind) {
1062 case DeclarationName::Identifier:
1063 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001064 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001065 ID.AddString(((IdentifierInfo*)Data)->getName());
1066 break;
1067 case DeclarationName::ObjCZeroArgSelector:
1068 case DeclarationName::ObjCOneArgSelector:
1069 case DeclarationName::ObjCMultiArgSelector:
1070 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1071 break;
1072 case DeclarationName::CXXOperatorName:
1073 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 break;
1075 case DeclarationName::CXXConstructorName:
1076 case DeclarationName::CXXDestructorName:
1077 case DeclarationName::CXXConversionFunctionName:
1078 case DeclarationName::CXXUsingDirective:
1079 break;
1080 }
1081
1082 return ID.ComputeHash();
1083}
1084
Richard Smithd88a7f12015-09-01 20:35:42 +00001085ModuleFile *
1086ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1087 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001088
Richard Smithd88a7f12015-09-01 20:35:42 +00001089 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1090 return Reader.getLocalModuleFile(F, ModuleFileID);
1091}
1092
Guy Benyei11169dd2012-12-18 14:30:41 +00001093std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001094ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001095 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001096
Justin Bogner57ba0b22014-03-28 22:03:24 +00001097 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1098 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 return std::make_pair(KeyLen, DataLen);
1100}
1101
Richard Smitha06c7e62015-08-26 23:55:49 +00001102ASTDeclContextNameLookupTrait::internal_key_type
1103ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001104 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001105
Vedant Kumar48b4f762018-04-14 01:40:48 +00001106 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 uint64_t Data;
1108 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001110 case DeclarationName::CXXLiteralOperatorName:
1111 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001112 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001113 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 break;
1115 case DeclarationName::ObjCZeroArgSelector:
1116 case DeclarationName::ObjCOneArgSelector:
1117 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001118 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001119 (uint64_t)Reader.getLocalSelector(
1120 F, endian::readNext<uint32_t, little, unaligned>(
1121 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 break;
1123 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001124 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001126 case DeclarationName::CXXConstructorName:
1127 case DeclarationName::CXXDestructorName:
1128 case DeclarationName::CXXConversionFunctionName:
1129 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001130 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 break;
1132 }
1133
Richard Smitha06c7e62015-08-26 23:55:49 +00001134 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001135}
1136
Richard Smithd88a7f12015-09-01 20:35:42 +00001137void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1138 const unsigned char *d,
1139 unsigned DataLen,
1140 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001141 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001142
Richard Smithd88a7f12015-09-01 20:35:42 +00001143 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1144 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1145 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001147}
1148
Richard Smith0f4e2c42015-08-06 04:23:48 +00001149bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1150 BitstreamCursor &Cursor,
1151 uint64_t Offset,
1152 DeclContext *DC) {
1153 assert(Offset != 0);
1154
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001156 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1157 Error(std::move(Err));
1158 return true;
1159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001160
Richard Smith0f4e2c42015-08-06 04:23:48 +00001161 RecordData Record;
1162 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001163 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1164 if (!MaybeCode) {
1165 Error(MaybeCode.takeError());
1166 return true;
1167 }
1168 unsigned Code = MaybeCode.get();
1169
1170 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1171 if (!MaybeRecCode) {
1172 Error(MaybeRecCode.takeError());
1173 return true;
1174 }
1175 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001176 if (RecCode != DECL_CONTEXT_LEXICAL) {
1177 Error("Expected lexical block");
1178 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 }
1180
Richard Smith82f8fcd2015-08-06 22:07:25 +00001181 assert(!isa<TranslationUnitDecl>(DC) &&
1182 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001183 // If we are handling a C++ class template instantiation, we can see multiple
1184 // lexical updates for the same record. It's important that we select only one
1185 // of them, so that field numbering works properly. Just pick the first one we
1186 // see.
1187 auto &Lex = LexicalDecls[DC];
1188 if (!Lex.first) {
1189 Lex = std::make_pair(
1190 &M, llvm::makeArrayRef(
1191 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1192 Blob.data()),
1193 Blob.size() / 4));
1194 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001195 DC->setHasExternalLexicalStorage(true);
1196 return false;
1197}
Guy Benyei11169dd2012-12-18 14:30:41 +00001198
Richard Smith0f4e2c42015-08-06 04:23:48 +00001199bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1200 BitstreamCursor &Cursor,
1201 uint64_t Offset,
1202 DeclID ID) {
1203 assert(Offset != 0);
1204
1205 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001206 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1207 Error(std::move(Err));
1208 return true;
1209 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001210
1211 RecordData Record;
1212 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001213 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1214 if (!MaybeCode) {
1215 Error(MaybeCode.takeError());
1216 return true;
1217 }
1218 unsigned Code = MaybeCode.get();
1219
1220 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1221 if (!MaybeRecCode) {
1222 Error(MaybeRecCode.takeError());
1223 return true;
1224 }
1225 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001226 if (RecCode != DECL_CONTEXT_VISIBLE) {
1227 Error("Expected visible lookup table block");
1228 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 }
1230
Richard Smith0f4e2c42015-08-06 04:23:48 +00001231 // We can't safely determine the primary context yet, so delay attaching the
1232 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001233 auto *Data = (const unsigned char*)Blob.data();
1234 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 return false;
1236}
1237
Richard Smith37a93df2017-02-18 00:32:02 +00001238void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001240 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001241 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001242 Diag(diag::note_module_cache_path)
1243 << PP.getHeaderSearchInfo().getModuleCachePath();
1244 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001245}
1246
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001247void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1248 StringRef Arg3) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001249 if (Diags.isDiagnosticInFlight())
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001250 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 else
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001252 Diag(DiagID) << Arg1 << Arg2 << Arg3;
Guy Benyei11169dd2012-12-18 14:30:41 +00001253}
1254
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001255void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1256 unsigned Select) const {
1257 if (!Diags.isDiagnosticInFlight())
1258 Diag(DiagID) << Arg1 << Arg2 << Select;
1259}
1260
JF Bastien0e828952019-06-26 19:50:12 +00001261void ASTReader::Error(llvm::Error &&Err) const {
1262 Error(toString(std::move(Err)));
1263}
1264
Guy Benyei11169dd2012-12-18 14:30:41 +00001265//===----------------------------------------------------------------------===//
1266// Source Manager Deserialization
1267//===----------------------------------------------------------------------===//
1268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001269/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001270/// \returns true if there was an error.
1271bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001272 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 unsigned Idx = 0;
1274 LineTableInfo &LineTable = SourceMgr.getLineTable();
1275
1276 // Parse the file names
1277 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001278 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001279 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001281 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1283 }
Richard Smith63078492015-09-01 07:41:55 +00001284 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001285
1286 // Parse the line entries
1287 std::vector<LineEntry> Entries;
1288 while (Idx < Record.size()) {
1289 int FID = Record[Idx++];
1290 assert(FID >= 0 && "Serialized line entries for non-local file.");
1291 // Remap FileID from 1-based old view.
1292 FID += F.SLocEntryBaseID - 1;
1293
1294 // Extract the line entries
1295 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001296 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 Entries.clear();
1298 Entries.reserve(NumEntries);
1299 for (unsigned I = 0; I != NumEntries; ++I) {
1300 unsigned FileOffset = Record[Idx++];
1301 unsigned LineNo = Record[Idx++];
1302 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001303 SrcMgr::CharacteristicKind FileKind
1304 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 unsigned IncludeOffset = Record[Idx++];
1306 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1307 FileKind, IncludeOffset));
1308 }
1309 LineTable.AddEntry(FileID::get(FID), Entries);
1310 }
1311
1312 return false;
1313}
1314
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001315/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001316bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1317 using namespace SrcMgr;
1318
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001320
1321 // Set the source-location entry cursor to the current position in
1322 // the stream. This cursor will be used to read the contents of the
1323 // source manager block initially, and then lazily read
1324 // source-location entries as needed.
1325 SLocEntryCursor = F.Stream;
1326
1327 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001328 if (llvm::Error Err = F.Stream.SkipBlock()) {
1329 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 return true;
1331 }
1332
1333 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001334 if (llvm::Error Err =
1335 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1336 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 return true;
1338 }
1339
1340 RecordData Record;
1341 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001342 Expected<llvm::BitstreamEntry> MaybeE =
1343 SLocEntryCursor.advanceSkippingSubblocks();
1344 if (!MaybeE) {
1345 Error(MaybeE.takeError());
1346 return true;
1347 }
1348 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001349
Chris Lattnere7b154b2013-01-19 21:39:22 +00001350 switch (E.Kind) {
1351 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1352 case llvm::BitstreamEntry::Error:
1353 Error("malformed block record in AST file");
1354 return true;
1355 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001356 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001357 case llvm::BitstreamEntry::Record:
1358 // The interesting case.
1359 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001364 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001365 Expected<unsigned> MaybeRecord =
1366 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1367 if (!MaybeRecord) {
1368 Error(MaybeRecord.takeError());
1369 return true;
1370 }
1371 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 default: // Default behavior: ignore.
1373 break;
1374
1375 case SM_SLOC_FILE_ENTRY:
1376 case SM_SLOC_BUFFER_ENTRY:
1377 case SM_SLOC_EXPANSION_ENTRY:
1378 // Once we hit one of the source location entries, we're done.
1379 return false;
1380 }
1381 }
1382}
1383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001384/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001385/// and the PCH file was moved from its original location, try to resolve the
1386/// file by assuming that header+PCH were moved together and the header is in
1387/// the same place relative to the PCH.
1388static std::string
1389resolveFileRelativeToOriginalDir(const std::string &Filename,
1390 const std::string &OriginalDir,
1391 const std::string &CurrDir) {
1392 assert(OriginalDir != CurrDir &&
1393 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001396
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 SmallString<128> filePath(Filename);
1398 fs::make_absolute(filePath);
1399 assert(path::is_absolute(OriginalDir));
1400 SmallString<128> currPCHPath(CurrDir);
1401
1402 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1403 fileDirE = path::end(path::parent_path(filePath));
1404 path::const_iterator origDirI = path::begin(OriginalDir),
1405 origDirE = path::end(OriginalDir);
1406 // Skip the common path components from filePath and OriginalDir.
1407 while (fileDirI != fileDirE && origDirI != origDirE &&
1408 *fileDirI == *origDirI) {
1409 ++fileDirI;
1410 ++origDirI;
1411 }
1412 for (; origDirI != origDirE; ++origDirI)
1413 path::append(currPCHPath, "..");
1414 path::append(currPCHPath, fileDirI, fileDirE);
1415 path::append(currPCHPath, path::filename(Filename));
Benjamin Krameradcd0262020-01-28 20:23:46 +01001416 return std::string(currPCHPath.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001417}
1418
1419bool ASTReader::ReadSLocEntry(int ID) {
1420 if (ID == 0)
1421 return false;
1422
1423 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1424 Error("source location entry ID out-of-range for AST file");
1425 return true;
1426 }
1427
Richard Smithaada85c2016-02-06 02:06:43 +00001428 // Local helper to read the (possibly-compressed) buffer data following the
1429 // entry record.
1430 auto ReadBuffer = [this](
1431 BitstreamCursor &SLocEntryCursor,
1432 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1433 RecordData Record;
1434 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001435 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1436 if (!MaybeCode) {
1437 Error(MaybeCode.takeError());
1438 return nullptr;
1439 }
1440 unsigned Code = MaybeCode.get();
1441
1442 Expected<unsigned> MaybeRecCode =
1443 SLocEntryCursor.readRecord(Code, Record, &Blob);
1444 if (!MaybeRecCode) {
1445 Error(MaybeRecCode.takeError());
1446 return nullptr;
1447 }
1448 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001449
1450 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001451 if (!llvm::zlib::isAvailable()) {
1452 Error("zlib is not available");
1453 return nullptr;
1454 }
Richard Smithaada85c2016-02-06 02:06:43 +00001455 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001456 if (llvm::Error E =
1457 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1458 Error("could not decompress embedded file contents: " +
1459 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001460 return nullptr;
1461 }
1462 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1463 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1464 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1465 } else {
1466 Error("AST record has invalid code");
1467 return nullptr;
1468 }
1469 };
1470
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001472 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1473 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1474 Error(std::move(Err));
1475 return true;
1476 }
1477
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001478 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 unsigned BaseOffset = F->SLocEntryBaseOffset;
1480
1481 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001482 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1483 if (!MaybeEntry) {
1484 Error(MaybeEntry.takeError());
1485 return true;
1486 }
1487 llvm::BitstreamEntry Entry = MaybeEntry.get();
1488
Chris Lattnere7b154b2013-01-19 21:39:22 +00001489 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 Error("incorrectly-formatted source location entry in AST file");
1491 return true;
1492 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001493
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001495 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001496 Expected<unsigned> MaybeSLOC =
1497 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1498 if (!MaybeSLOC) {
1499 Error(MaybeSLOC.takeError());
1500 return true;
1501 }
1502 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001503 default:
1504 Error("incorrectly-formatted source location entry in AST file");
1505 return true;
1506
1507 case SM_SLOC_FILE_ENTRY: {
1508 // We will detect whether a file changed and return 'Failure' for it, but
1509 // we will also try to fail gracefully by setting up the SLocEntry.
1510 unsigned InputID = Record[4];
1511 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001512 const FileEntry *File = IF.getFile();
1513 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001515 // Note that we only check if a File was returned. If it was out-of-date
1516 // we have complained but we will continue creating a FileID to recover
1517 // gracefully.
1518 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 return true;
1520
1521 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1522 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1523 // This is the module's main file.
1524 IncludeLoc = getImportLocation(F);
1525 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001526 SrcMgr::CharacteristicKind
1527 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001528 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1530 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001531 SrcMgr::FileInfo &FileInfo =
1532 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 FileInfo.NumCreatedFIDs = Record[5];
1534 if (Record[3])
1535 FileInfo.setHasLineDirectives();
1536
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001538 if (NumFileDecls && ContextObj) {
Roman Lebedevbf4f1e02019-10-10 12:22:42 +00001539 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00001540 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1541 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1542 NumFileDecls));
1543 }
Richard Smithaada85c2016-02-06 02:06:43 +00001544
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001546 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001548 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1549 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001550 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1551 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001553 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 }
1555
1556 break;
1557 }
1558
1559 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001560 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001562 SrcMgr::CharacteristicKind
1563 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001565 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 IncludeLoc = getImportLocation(F);
1567 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001568
Richard Smithaada85c2016-02-06 02:06:43 +00001569 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1570 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001572 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001573 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001574 break;
1575 }
1576
1577 case SM_SLOC_EXPANSION_ENTRY: {
1578 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1579 SourceMgr.createExpansionLoc(SpellingLoc,
1580 ReadSourceLocation(*F, Record[2]),
1581 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001582 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001583 Record[4],
1584 ID,
1585 BaseOffset + Record[0]);
1586 break;
1587 }
1588 }
1589
1590 return false;
1591}
1592
1593std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1594 if (ID == 0)
1595 return std::make_pair(SourceLocation(), "");
1596
1597 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1598 Error("source location entry ID out-of-range for AST file");
1599 return std::make_pair(SourceLocation(), "");
1600 }
1601
1602 // Find which module file this entry lands in.
1603 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001604 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 return std::make_pair(SourceLocation(), "");
1606
1607 // FIXME: Can we map this down to a particular submodule? That would be
1608 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001609 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001610}
1611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001612/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001613SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1614 if (F->ImportLoc.isValid())
1615 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001616
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 // Otherwise we have a PCH. It's considered to be "imported" at the first
1618 // location of its includer.
1619 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001620 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001621 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001622 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 return F->ImportedBy[0]->FirstLoc;
1625}
1626
JF Bastien0e828952019-06-26 19:50:12 +00001627/// Enter a subblock of the specified BlockID with the specified cursor. Read
1628/// the abbreviations that are at the top of the block and then leave the cursor
1629/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001630bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001631 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1632 // FIXME this drops errors on the floor.
1633 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001634 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001636
1637 while (true) {
1638 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001639 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1640 if (!MaybeCode) {
1641 // FIXME this drops errors on the floor.
1642 consumeError(MaybeCode.takeError());
1643 return true;
1644 }
1645 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001646
1647 // We expect all abbrevs to be at the start of the block.
1648 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001649 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1650 // FIXME this drops errors on the floor.
1651 consumeError(std::move(Err));
1652 return true;
1653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 return false;
1655 }
JF Bastien0e828952019-06-26 19:50:12 +00001656 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1657 // FIXME this drops errors on the floor.
1658 consumeError(std::move(Err));
1659 return true;
1660 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 }
1662}
1663
Richard Smithe40f2ba2013-08-07 21:41:30 +00001664Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001665 unsigned &Idx) {
1666 Token Tok;
1667 Tok.startToken();
1668 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1669 Tok.setLength(Record[Idx++]);
1670 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1671 Tok.setIdentifierInfo(II);
1672 Tok.setKind((tok::TokenKind)Record[Idx++]);
1673 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1674 return Tok;
1675}
1676
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001677MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001678 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001679
1680 // Keep track of where we are in the stream, then jump back there
1681 // after reading this macro.
1682 SavedStreamPosition SavedPosition(Stream);
1683
JF Bastien0e828952019-06-26 19:50:12 +00001684 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1685 // FIXME this drops errors on the floor.
1686 consumeError(std::move(Err));
1687 return nullptr;
1688 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001690 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001691 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001694 // Advance to the next record, but if we get to the end of the block, don't
1695 // pop it (removing all the abbreviations from the cursor) since we want to
1696 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001697 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001698 Expected<llvm::BitstreamEntry> MaybeEntry =
1699 Stream.advanceSkippingSubblocks(Flags);
1700 if (!MaybeEntry) {
1701 Error(MaybeEntry.takeError());
1702 return Macro;
1703 }
1704 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001705
Chris Lattnerefa77172013-01-20 00:00:22 +00001706 switch (Entry.Kind) {
1707 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1708 case llvm::BitstreamEntry::Error:
1709 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001710 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001711 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001712 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001713 case llvm::BitstreamEntry::Record:
1714 // The interesting case.
1715 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 }
1717
1718 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001720 PreprocessorRecordTypes RecType;
1721 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1722 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1723 else {
1724 Error(MaybeRecType.takeError());
1725 return Macro;
1726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001728 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729 case PP_MACRO_DIRECTIVE_HISTORY:
1730 return Macro;
1731
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 case PP_MACRO_OBJECT_LIKE:
1733 case PP_MACRO_FUNCTION_LIKE: {
1734 // If we already have a macro, that means that we've hit the end
1735 // of the definition of the macro we were looking for. We're
1736 // done.
1737 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001738 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001739
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001740 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001742 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001743 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001745 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001746
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1748 // Decode function-like macro info.
1749 bool isC99VarArgs = Record[NextIndex++];
1750 bool isGNUVarArgs = Record[NextIndex++];
1751 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001752 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 unsigned NumArgs = Record[NextIndex++];
1754 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001755 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001756
1757 // Install function-like macro info.
1758 MI->setIsFunctionLike();
1759 if (isC99VarArgs) MI->setIsC99Varargs();
1760 if (isGNUVarArgs) MI->setIsGNUVarargs();
1761 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001762 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 }
1764
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 // Remember that we saw this macro last so that we add the tokens that
1766 // form its body to it.
1767 Macro = MI;
1768
1769 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1770 Record[NextIndex]) {
1771 // We have a macro definition. Register the association
1772 PreprocessedEntityID
1773 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1774 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001775 PreprocessingRecord::PPEntityID PPID =
1776 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001777 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001778 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001779 if (PPDef)
1780 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 }
1782
1783 ++NumMacrosRead;
1784 break;
1785 }
1786
1787 case PP_TOKEN: {
1788 // If we see a TOKEN before a PP_MACRO_*, then the file is
1789 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001790 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001791
John McCallf413f5e2013-05-03 00:10:13 +00001792 unsigned Idx = 0;
1793 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 Macro->AddTokenToBody(Tok);
1795 break;
1796 }
1797 }
1798 }
1799}
1800
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001801PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001802ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1803 unsigned LocalID) const {
1804 if (!M.ModuleOffsetMap.empty())
1805 ReadModuleOffsetMap(M);
1806
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001807 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001809 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001811
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 return LocalID + I->second;
1813}
1814
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001815unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1816 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001817}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001818
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001819HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001820HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001821 internal_key_type ikey = {FE->getSize(),
1822 M.HasTimestamps ? FE->getModificationTime() : 0,
1823 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001824 return ikey;
1825}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001826
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001827bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001828 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 return false;
1830
Mehdi Amini004b9c72016-10-10 22:52:47 +00001831 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001832 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001833
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001835 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001836 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001837 if (!Key.Imported) {
1838 if (auto File = FileMgr.getFile(Key.Filename))
1839 return *File;
1840 return nullptr;
1841 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001842
Benjamin Krameradcd0262020-01-28 20:23:46 +01001843 std::string Resolved = std::string(Key.Filename);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001844 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001845 if (auto File = FileMgr.getFile(Resolved))
1846 return *File;
1847 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001848 };
1849
1850 const FileEntry *FEA = GetFile(a);
1851 const FileEntry *FEB = GetFile(b);
1852 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001854
Guy Benyei11169dd2012-12-18 14:30:41 +00001855std::pair<unsigned, unsigned>
1856HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001857 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001858
Vedant Kumar48b4f762018-04-14 01:40:48 +00001859 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1860 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001861 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001862}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001863
1864HeaderFileInfoTrait::internal_key_type
1865HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001866 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001867
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001868 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001869 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1870 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001871 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001872 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001873 return ikey;
1874}
1875
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001876HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001877HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001879 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001880
1881 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 HeaderFileInfo HFI;
1883 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001884 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001885 HFI.isImport |= (Flags >> 5) & 0x01;
1886 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1887 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001888 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001889 // FIXME: Find a better way to handle this. Maybe just store a
1890 // "has been included" flag?
1891 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1892 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001893 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1894 M, endian::readNext<uint32_t, little, unaligned>(d));
1895 if (unsigned FrameworkOffset =
1896 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001897 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 // since 0 is used as an indicator for "no framework name".
1899 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1900 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1901 }
Richard Smith386bb072015-08-18 23:42:23 +00001902
1903 assert((End - d) % 4 == 0 &&
1904 "Wrong data length in HeaderFileInfo deserialization");
1905 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001906 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001907 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1908 LocalSMID >>= 2;
1909
1910 // This header is part of a module. Associate it with the module to enable
1911 // implicit module import.
1912 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1913 Module *Mod = Reader.getSubmodule(GlobalSMID);
1914 FileManager &FileMgr = Reader.getFileManager();
1915 ModuleMap &ModMap =
1916 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1917
Benjamin Krameradcd0262020-01-28 20:23:46 +01001918 std::string Filename = std::string(key.Filename);
Richard Smith386bb072015-08-18 23:42:23 +00001919 if (key.Imported)
1920 Reader.ResolveImportedPath(M, Filename);
1921 // FIXME: This is not always the right filename-as-written, but we're not
1922 // going to use this information to rebuild the module, so it doesn't make
1923 // a lot of difference.
Benjamin Krameradcd0262020-01-28 20:23:46 +01001924 Module::Header H = {std::string(key.Filename), *FileMgr.getFile(Filename)};
Richard Smithd8879c82015-08-24 21:59:32 +00001925 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1926 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001927 }
1928
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 // This HeaderFileInfo was externally loaded.
1930 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001931 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 return HFI;
1933}
1934
Richard Smithd7329392015-04-21 21:46:32 +00001935void ASTReader::addPendingMacro(IdentifierInfo *II,
1936 ModuleFile *M,
1937 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001938 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1939 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001940}
1941
1942void ASTReader::ReadDefinedMacros() {
1943 // Note that we are loading defined macros.
1944 Deserializing Macros(this);
1945
Vedant Kumar48b4f762018-04-14 01:40:48 +00001946 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001947 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001948
1949 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001950 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 continue;
1952
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001953 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001954 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1955 Error(std::move(Err));
1956 return;
1957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001958
1959 RecordData Record;
1960 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001961 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1962 if (!MaybeE) {
1963 Error(MaybeE.takeError());
1964 return;
1965 }
1966 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001967
Chris Lattnere7b154b2013-01-19 21:39:22 +00001968 switch (E.Kind) {
1969 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1970 case llvm::BitstreamEntry::Error:
1971 Error("malformed block record in AST file");
1972 return;
1973 case llvm::BitstreamEntry::EndBlock:
1974 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001975
JF Bastien0e828952019-06-26 19:50:12 +00001976 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001977 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001978 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1979 if (!MaybeRecord) {
1980 Error(MaybeRecord.takeError());
1981 return;
1982 }
1983 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001984 default: // Default behavior: ignore.
1985 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001986
Chris Lattnere7b154b2013-01-19 21:39:22 +00001987 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001988 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001989 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001990 if (II->isOutOfDate())
1991 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001992 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001993 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001994
Chris Lattnere7b154b2013-01-19 21:39:22 +00001995 case PP_TOKEN:
1996 // Ignore tokens.
1997 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 break;
2000 }
JF Bastien0e828952019-06-26 19:50:12 +00002001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002003 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00002004 }
2005}
2006
2007namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002009 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 class IdentifierLookupVisitor {
2011 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002012 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002014 unsigned &NumIdentifierLookups;
2015 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002016 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002017
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002019 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2020 unsigned &NumIdentifierLookups,
2021 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002022 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2023 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002024 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002025 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002026
2027 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002029 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002031
Vedant Kumar48b4f762018-04-14 01:40:48 +00002032 ASTIdentifierLookupTable *IdTable
2033 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 if (!IdTable)
2035 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002036
2037 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002038 Found);
2039 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002040 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002041 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 if (Pos == IdTable->end())
2043 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002044
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 // Dereferencing the iterator has the effect of building the
2046 // IdentifierInfo node and populating it with the various
2047 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002048 ++NumIdentifierLookupHits;
2049 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 return true;
2051 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002052
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002053 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 // files.
2055 IdentifierInfo *getIdentifierInfo() const { return Found; }
2056 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002057
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002058} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002059
2060void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2061 // Note that we are loading an identifier.
2062 Deserializing AnIdentifier(this);
2063
2064 unsigned PriorGeneration = 0;
2065 if (getContext().getLangOpts().Modules)
2066 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002067
2068 // If there is a global index, look there first to determine which modules
2069 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002070 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002071 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002072 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002073 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2074 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002075 }
2076 }
2077
Douglas Gregor7211ac12013-01-25 23:32:03 +00002078 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002079 NumIdentifierLookups,
2080 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002081 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 markIdentifierUpToDate(&II);
2083}
2084
2085void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2086 if (!II)
2087 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 II->setOutOfDate(false);
2090
2091 // Update the generation for this identifier.
2092 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002093 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002094}
2095
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002096void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2097 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002098 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002099
2100 BitstreamCursor &Cursor = M.MacroCursor;
2101 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002102 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2103 Error(std::move(Err));
2104 return;
2105 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002106
Richard Smith713369b2015-04-23 20:40:50 +00002107 struct ModuleMacroRecord {
2108 SubmoduleID SubModID;
2109 MacroInfo *MI;
2110 SmallVector<SubmoduleID, 8> Overrides;
2111 };
2112 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002113
Richard Smithd7329392015-04-21 21:46:32 +00002114 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2115 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2116 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002117 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002118 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002119 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002120 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002121 if (!MaybeEntry) {
2122 Error(MaybeEntry.takeError());
2123 return;
2124 }
2125 llvm::BitstreamEntry Entry = MaybeEntry.get();
2126
Richard Smithd7329392015-04-21 21:46:32 +00002127 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2128 Error("malformed block record in AST file");
2129 return;
2130 }
2131
2132 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002133 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2134 if (!MaybePP) {
2135 Error(MaybePP.takeError());
2136 return;
2137 }
2138 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002139 case PP_MACRO_DIRECTIVE_HISTORY:
2140 break;
2141
2142 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002143 ModuleMacros.push_back(ModuleMacroRecord());
2144 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002145 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2146 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002147 for (int I = 2, N = Record.size(); I != N; ++I)
2148 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002149 continue;
2150 }
2151
2152 default:
2153 Error("malformed block record in AST file");
2154 return;
2155 }
2156
2157 // We found the macro directive history; that's the last record
2158 // for this macro.
2159 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002160 }
2161
Richard Smithd7329392015-04-21 21:46:32 +00002162 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002163 {
2164 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002165 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002166 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002167 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002168 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002169 Module *Mod = getSubmodule(ModID);
2170 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002171 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002172 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002173 }
2174
2175 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002176 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002177 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002178 }
2179 }
2180
2181 // Don't read the directive history for a module; we don't have anywhere
2182 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002183 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002184 return;
2185
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002186 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002187 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002188 unsigned Idx = 0, N = Record.size();
2189 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002190 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002191 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002192 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002193 switch (K) {
2194 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002195 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002196 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002197 break;
2198 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002199 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002200 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002201 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002202 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002203 bool isPublic = Record[Idx++];
2204 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2205 break;
2206 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002207
2208 if (!Latest)
2209 Latest = MD;
2210 if (Earliest)
2211 Earliest->setPrevious(MD);
2212 Earliest = MD;
2213 }
2214
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002215 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002216 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002217}
2218
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002219ASTReader::InputFileInfo
2220ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002221 // Go find this input file.
2222 BitstreamCursor &Cursor = F.InputFilesCursor;
2223 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002224 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2225 // FIXME this drops errors on the floor.
2226 consumeError(std::move(Err));
2227 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002228
JF Bastien0e828952019-06-26 19:50:12 +00002229 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2230 if (!MaybeCode) {
2231 // FIXME this drops errors on the floor.
2232 consumeError(MaybeCode.takeError());
2233 }
2234 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002235 RecordData Record;
2236 StringRef Blob;
2237
JF Bastien0e828952019-06-26 19:50:12 +00002238 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2239 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2240 "invalid record type for input file");
2241 else {
2242 // FIXME this drops errors on the floor.
2243 consumeError(Maybe.takeError());
2244 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002245
2246 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002247 InputFileInfo R;
2248 R.StoredSize = static_cast<off_t>(Record[1]);
2249 R.StoredTime = static_cast<time_t>(Record[2]);
2250 R.Overridden = static_cast<bool>(Record[3]);
2251 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002252 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002253 R.Filename = std::string(Blob);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002254 ResolveImportedPath(F, R.Filename);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002255
2256 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2257 if (!MaybeEntry) // FIXME this drops errors on the floor.
2258 consumeError(MaybeEntry.takeError());
2259 llvm::BitstreamEntry Entry = MaybeEntry.get();
2260 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2261 "expected record type for input file hash");
2262
2263 Record.clear();
2264 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2265 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2266 "invalid record type for input file hash");
2267 else {
2268 // FIXME this drops errors on the floor.
2269 consumeError(Maybe.takeError());
2270 }
2271 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2272 static_cast<uint64_t>(Record[0]);
Hans Wennborg73945142014-03-14 17:45:06 +00002273 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002274}
2275
Manman Renc8c94152016-10-21 23:35:03 +00002276static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002277InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 // If this ID is bogus, just return an empty input file.
2279 if (ID == 0 || ID > F.InputFilesLoaded.size())
2280 return InputFile();
2281
2282 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002283 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 return F.InputFilesLoaded[ID-1];
2285
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002286 if (F.InputFilesLoaded[ID-1].isNotFound())
2287 return InputFile();
2288
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002290 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002292 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2293 // FIXME this drops errors on the floor.
2294 consumeError(std::move(Err));
2295 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002296
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002297 InputFileInfo FI = readInputFileInfo(F, ID);
2298 off_t StoredSize = FI.StoredSize;
2299 time_t StoredTime = FI.StoredTime;
2300 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002301 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002302 StringRef Filename = FI.Filename;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002303 uint64_t StoredContentHash = FI.ContentHash;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002304
Harlan Haskins8d323d12019-08-01 21:31:56 +00002305 const FileEntry *File = nullptr;
2306 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2307 File = *FE;
2308
Ben Langmuir198c1682014-03-07 07:27:49 +00002309 // If we didn't find the file, resolve it relative to the
2310 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002311 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2312 F.OriginalDir != F.BaseDirectory) {
2313 std::string Resolved = resolveFileRelativeToOriginalDir(
Benjamin Krameradcd0262020-01-28 20:23:46 +01002314 std::string(Filename), F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002315 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002316 if (auto FE = FileMgr.getFile(Resolved))
2317 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002318 }
2319
2320 // For an overridden file, create a virtual file with the stored
2321 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002322 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002323 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002324
Craig Toppera13603a2014-05-22 05:54:18 +00002325 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002326 if (Complain) {
2327 std::string ErrorStr = "could not find file '";
2328 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002329 ErrorStr += "' referenced by AST file '";
2330 ErrorStr += F.FileName;
2331 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002332 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002334 // Record that we didn't find the file.
2335 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2336 return InputFile();
2337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002338
Ben Langmuir198c1682014-03-07 07:27:49 +00002339 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002340 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002341 // can lead to problems when lexing using the source locations from the
2342 // PCH.
2343 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002344 // FIXME: Reject if the overrides are different.
2345 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002346 if (Complain)
2347 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002348
2349 // After emitting the diagnostic, bypass the overriding file to recover
2350 // (this creates a separate FileEntry).
2351 File = SM.bypassFileContentsOverride(*File);
2352 if (!File) {
2353 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2354 return InputFile();
2355 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002356 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002357
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002358 enum ModificationType {
2359 Size,
2360 ModTime,
2361 Content,
2362 None,
2363 };
2364 auto HasInputFileChanged = [&]() {
2365 if (StoredSize != File->getSize())
2366 return ModificationType::Size;
2367 if (!DisableValidation && StoredTime &&
2368 StoredTime != File->getModificationTime()) {
2369 // In case the modification time changes but not the content,
2370 // accept the cached file as legit.
2371 if (ValidateASTInputFilesContent &&
2372 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2373 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2374 if (!MemBuffOrError) {
2375 if (!Complain)
2376 return ModificationType::ModTime;
2377 std::string ErrorStr = "could not get buffer for file '";
2378 ErrorStr += File->getName();
2379 ErrorStr += "'";
2380 Error(ErrorStr);
2381 return ModificationType::ModTime;
2382 }
Eric Christopher3be91692019-10-14 23:14:24 +00002383
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002384 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2385 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2386 return ModificationType::None;
2387 return ModificationType::Content;
2388 }
2389 return ModificationType::ModTime;
2390 }
2391 return ModificationType::None;
2392 };
2393
2394 bool IsOutOfDate = false;
2395 auto FileChange = HasInputFileChanged();
Ben Langmuir198c1682014-03-07 07:27:49 +00002396 // For an overridden file, there is nothing to validate.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002397 if (!Overridden && FileChange != ModificationType::None) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002398 if (Complain) {
2399 // Build a list of the PCH imports that got us here (in reverse).
2400 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002401 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002402 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002403
Ben Langmuir198c1682014-03-07 07:27:49 +00002404 // The top-level PCH is stale.
2405 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002406 unsigned DiagnosticKind =
2407 moduleKindForDiagnostic(ImportStack.back()->Kind);
Manman Renc8c94152016-10-21 23:35:03 +00002408 if (DiagnosticKind == 0)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002409 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2410 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002411 else if (DiagnosticKind == 1)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002412 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2413 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002414 else
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002415 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2416 (unsigned)FileChange);
Ben Langmuire82630d2014-01-17 00:19:09 +00002417
Ben Langmuir198c1682014-03-07 07:27:49 +00002418 // Print the import stack.
2419 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2420 Diag(diag::note_pch_required_by)
2421 << Filename << ImportStack[0]->FileName;
2422 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002423 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002424 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002425 }
2426
Ben Langmuir198c1682014-03-07 07:27:49 +00002427 if (!Diags.isDiagnosticInFlight())
2428 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
2430
Ben Langmuir198c1682014-03-07 07:27:49 +00002431 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002433 // FIXME: If the file is overridden and we've already opened it,
2434 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002435
Richard Smitha8cfffa2015-11-26 02:04:16 +00002436 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002437
2438 // Note that we've loaded this input file.
2439 F.InputFilesLoaded[ID-1] = IF;
2440 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002441}
2442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002443/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002444/// is not an absolute path, add the system or module root to the beginning of
2445/// the file name.
2446void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2447 // Resolve relative to the base directory, if we have one.
2448 if (!M.BaseDirectory.empty())
2449 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002450}
2451
Richard Smith7ed1bc92014-12-05 22:42:13 +00002452void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2454 return;
2455
Richard Smith7ed1bc92014-12-05 22:42:13 +00002456 SmallString<128> Buffer;
2457 llvm::sys::path::append(Buffer, Prefix, Filename);
2458 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002459}
2460
Richard Smith0f99d6a2015-08-09 08:48:41 +00002461static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2462 switch (ARR) {
2463 case ASTReader::Failure: return true;
2464 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2465 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2466 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2467 case ASTReader::ConfigurationMismatch:
2468 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2469 case ASTReader::HadErrors: return true;
2470 case ASTReader::Success: return false;
2471 }
2472
2473 llvm_unreachable("unknown ASTReadResult");
2474}
2475
Richard Smith0516b182015-09-08 19:40:14 +00002476ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2477 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2478 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002479 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002480 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2481 // FIXME this drops errors on the floor.
2482 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002483 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002484 }
Richard Smith0516b182015-09-08 19:40:14 +00002485
2486 // Read all of the records in the options block.
2487 RecordData Record;
2488 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002489 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002490 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2491 if (!MaybeEntry) {
2492 // FIXME this drops errors on the floor.
2493 consumeError(MaybeEntry.takeError());
2494 return Failure;
2495 }
2496 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002497
Richard Smith0516b182015-09-08 19:40:14 +00002498 switch (Entry.Kind) {
2499 case llvm::BitstreamEntry::Error:
2500 case llvm::BitstreamEntry::SubBlock:
2501 return Failure;
2502
2503 case llvm::BitstreamEntry::EndBlock:
2504 return Result;
2505
2506 case llvm::BitstreamEntry::Record:
2507 // The interesting case.
2508 break;
2509 }
2510
2511 // Read and process a record.
2512 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002513 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2514 if (!MaybeRecordType) {
2515 // FIXME this drops errors on the floor.
2516 consumeError(MaybeRecordType.takeError());
2517 return Failure;
2518 }
2519 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002520 case LANGUAGE_OPTIONS: {
2521 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2522 if (ParseLanguageOptions(Record, Complain, Listener,
2523 AllowCompatibleConfigurationMismatch))
2524 Result = ConfigurationMismatch;
2525 break;
2526 }
2527
2528 case TARGET_OPTIONS: {
2529 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2530 if (ParseTargetOptions(Record, Complain, Listener,
2531 AllowCompatibleConfigurationMismatch))
2532 Result = ConfigurationMismatch;
2533 break;
2534 }
2535
Richard Smith0516b182015-09-08 19:40:14 +00002536 case FILE_SYSTEM_OPTIONS: {
2537 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2538 if (!AllowCompatibleConfigurationMismatch &&
2539 ParseFileSystemOptions(Record, Complain, Listener))
2540 Result = ConfigurationMismatch;
2541 break;
2542 }
2543
2544 case HEADER_SEARCH_OPTIONS: {
2545 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2546 if (!AllowCompatibleConfigurationMismatch &&
2547 ParseHeaderSearchOptions(Record, Complain, Listener))
2548 Result = ConfigurationMismatch;
2549 break;
2550 }
2551
2552 case PREPROCESSOR_OPTIONS:
2553 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2554 if (!AllowCompatibleConfigurationMismatch &&
2555 ParsePreprocessorOptions(Record, Complain, Listener,
2556 SuggestedPredefines))
2557 Result = ConfigurationMismatch;
2558 break;
2559 }
2560 }
2561}
2562
Guy Benyei11169dd2012-12-18 14:30:41 +00002563ASTReader::ASTReadResult
2564ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002565 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002566 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002568 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002569
JF Bastien0e828952019-06-26 19:50:12 +00002570 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2571 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 return Failure;
2573 }
2574
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002575 // Lambda to read the unhashed control block the first time it's called.
2576 //
2577 // For PCM files, the unhashed control block cannot be read until after the
2578 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2579 // need to look ahead before reading the IMPORTS record. For consistency,
2580 // this block is always read somehow (see BitstreamEntry::EndBlock).
2581 bool HasReadUnhashedControlBlock = false;
2582 auto readUnhashedControlBlockOnce = [&]() {
2583 if (!HasReadUnhashedControlBlock) {
2584 HasReadUnhashedControlBlock = true;
2585 if (ASTReadResult Result =
2586 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2587 return Result;
2588 }
2589 return Success;
2590 };
2591
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 // Read all of the records and blocks in the control block.
2593 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002594 unsigned NumInputs = 0;
2595 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002596 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002597 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002598 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2599 if (!MaybeEntry) {
2600 Error(MaybeEntry.takeError());
2601 return Failure;
2602 }
2603 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002604
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 switch (Entry.Kind) {
2606 case llvm::BitstreamEntry::Error:
2607 Error("malformed block record in AST file");
2608 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002609 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002610 // Validate the module before returning. This call catches an AST with
2611 // no module name and no imports.
2612 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2613 return Result;
2614
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002615 // Validate input files.
2616 const HeaderSearchOptions &HSOpts =
2617 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002618
Richard Smitha1825302014-10-23 22:18:29 +00002619 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002620 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2621 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002622 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2623 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002625
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002626 // If we are reading a module, we will create a verification timestamp,
2627 // so we verify all input files. Otherwise, verify only user input
2628 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002629
2630 unsigned N = NumUserInputs;
2631 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002632 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002633 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002634 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002635 N = NumInputs;
2636
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002637 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002638 InputFile IF = getInputFile(F, I+1, Complain);
2639 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002643
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002644 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002645 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002646
Ben Langmuircb69b572014-03-07 06:40:32 +00002647 if (Listener && Listener->needsInputFileVisitation()) {
2648 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2649 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002650 for (unsigned I = 0; I < N; ++I) {
2651 bool IsSystem = I >= NumUserInputs;
2652 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002653 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002654 F.Kind == MK_ExplicitModule ||
2655 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002656 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002657 }
2658
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002659 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002660 }
2661
Chris Lattnere7b154b2013-01-19 21:39:22 +00002662 case llvm::BitstreamEntry::SubBlock:
2663 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 case INPUT_FILES_BLOCK_ID:
2665 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002666 if (llvm::Error Err = Stream.SkipBlock()) {
2667 Error(std::move(Err));
2668 return Failure;
2669 }
2670 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 Error("malformed block record in AST file");
2672 return Failure;
2673 }
2674 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002675
2676 case OPTIONS_BLOCK_ID:
2677 // If we're reading the first module for this group, check its options
2678 // are compatible with ours. For modules it imports, no further checking
2679 // is required, because we checked them when we built it.
2680 if (Listener && !ImportedBy) {
2681 // Should we allow the configuration of the module file to differ from
2682 // the configuration of the current translation unit in a compatible
2683 // way?
2684 //
2685 // FIXME: Allow this for files explicitly specified with -include-pch.
2686 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002687 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002688
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002689 ASTReadResult Result =
2690 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2691 AllowCompatibleConfigurationMismatch, *Listener,
2692 SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002693 if (Result == Failure) {
2694 Error("malformed block record in AST file");
2695 return Result;
2696 }
2697
Richard Smith8a308ec2015-11-05 00:54:55 +00002698 if (DisableValidation ||
2699 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2700 Result = Success;
2701
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002702 // If we can't load the module, exit early since we likely
2703 // will rebuild the module anyway. The stream may be in the
2704 // middle of a block.
2705 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002706 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002707 } else if (llvm::Error Err = Stream.SkipBlock()) {
2708 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002709 return Failure;
2710 }
2711 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002712
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 default:
JF Bastien0e828952019-06-26 19:50:12 +00002714 if (llvm::Error Err = Stream.SkipBlock()) {
2715 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002716 return Failure;
2717 }
2718 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002720
Chris Lattnere7b154b2013-01-19 21:39:22 +00002721 case llvm::BitstreamEntry::Record:
2722 // The interesting case.
2723 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 }
2725
2726 // Read and process a record.
2727 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002728 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002729 Expected<unsigned> MaybeRecordType =
2730 Stream.readRecord(Entry.ID, Record, &Blob);
2731 if (!MaybeRecordType) {
2732 Error(MaybeRecordType.takeError());
2733 return Failure;
2734 }
2735 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 case METADATA: {
2737 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2738 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002739 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2740 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 return VersionMismatch;
2742 }
2743
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002744 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2746 Diag(diag::err_pch_with_compiler_errors);
2747 return HadErrors;
2748 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002749 if (hasErrors) {
2750 Diags.ErrorOccurred = true;
2751 Diags.UncompilableErrorOccurred = true;
2752 Diags.UnrecoverableErrorOccurred = true;
2753 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002754
2755 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002756 // Relative paths in a relocatable PCH are relative to our sysroot.
2757 if (F.RelocatablePCH)
2758 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002759
Richard Smithe75ee0f2015-08-17 07:13:32 +00002760 F.HasTimestamps = Record[5];
2761
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002762 F.PCHHasObjectFile = Record[6];
2763
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002765 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2767 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002768 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002769 return VersionMismatch;
2770 }
2771 break;
2772 }
2773
2774 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002775 // Validate the AST before processing any imports (otherwise, untangling
2776 // them can be error-prone and expensive). A module will have a name and
2777 // will already have been validated, but this catches the PCH case.
2778 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2779 return Result;
2780
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002781 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 unsigned Idx = 0, N = Record.size();
2783 while (Idx < N) {
2784 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002785 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 // The import location will be the local one for now; we will adjust
2787 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002788 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002790 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002791 off_t StoredSize = (off_t)Record[Idx++];
2792 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002793 ASTFileSignature StoredSignature = {
2794 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2795 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2796 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002797
2798 std::string ImportedName = ReadString(Record, Idx);
2799 std::string ImportedFile;
2800
2801 // For prebuilt and explicit modules first consult the file map for
2802 // an override. Note that here we don't search prebuilt module
2803 // directories, only the explicit name to file mappings. Also, we will
2804 // still verify the size/signature making sure it is essentially the
2805 // same file but perhaps in a different location.
2806 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2807 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2808 ImportedName, /*FileMapOnly*/ true);
2809
2810 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002811 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2812 // ModuleCache as when writing.
2813 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002814 else
2815 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002816
Richard Smith0f99d6a2015-08-09 08:48:41 +00002817 // If our client can't cope with us being out of date, we can't cope with
2818 // our dependency being missing.
2819 unsigned Capabilities = ClientLoadCapabilities;
2820 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2821 Capabilities &= ~ARR_Missing;
2822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002824 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2825 Loaded, StoredSize, StoredModTime,
2826 StoredSignature, Capabilities);
2827
2828 // If we diagnosed a problem, produce a backtrace.
2829 if (isDiagnosedResult(Result, Capabilities))
2830 Diag(diag::note_module_file_imported_by)
2831 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2832
2833 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 case Failure: return Failure;
2835 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002836 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 case OutOfDate: return OutOfDate;
2838 case VersionMismatch: return VersionMismatch;
2839 case ConfigurationMismatch: return ConfigurationMismatch;
2840 case HadErrors: return HadErrors;
2841 case Success: break;
2842 }
2843 }
2844 break;
2845 }
2846
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 case ORIGINAL_FILE:
2848 F.OriginalSourceFileID = FileID::get(Record[0]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002849 F.ActualOriginalSourceFileName = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002851 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 break;
2853
2854 case ORIGINAL_FILE_ID:
2855 F.OriginalSourceFileID = FileID::get(Record[0]);
2856 break;
2857
2858 case ORIGINAL_PCH_DIR:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002859 F.OriginalDir = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 break;
2861
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002862 case MODULE_NAME:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002863 F.ModuleName = std::string(Blob);
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002864 Diag(diag::remark_module_import)
2865 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2866 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002867 if (Listener)
2868 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002869
2870 // Validate the AST as soon as we have a name so we can exit early on
2871 // failure.
2872 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2873 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002874
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002875 break;
2876
Richard Smith223d3f22014-12-06 03:21:08 +00002877 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002878 // Save the BaseDirectory as written in the PCM for computing the module
2879 // filename for the ModuleCache.
2880 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002881 assert(!F.ModuleName.empty() &&
2882 "MODULE_DIRECTORY found before MODULE_NAME");
2883 // If we've already loaded a module map file covering this module, we may
2884 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002885 Module *M = PP.getHeaderSearchInfo().lookupModule(
2886 F.ModuleName, /*AllowSearch*/ true,
2887 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002888 if (M && M->Directory) {
2889 // If we're implicitly loading a module, the base directory can't
2890 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002891 // Don't emit module relocation error if we have -fno-validate-pch
2892 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2893 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002894 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2895 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002896 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2897 Diag(diag::err_imported_module_relocated)
2898 << F.ModuleName << Blob << M->Directory->getName();
2899 return OutOfDate;
2900 }
2901 }
Benjamin Krameradcd0262020-01-28 20:23:46 +01002902 F.BaseDirectory = std::string(M->Directory->getName());
Richard Smith223d3f22014-12-06 03:21:08 +00002903 } else {
Benjamin Krameradcd0262020-01-28 20:23:46 +01002904 F.BaseDirectory = std::string(Blob);
Richard Smith223d3f22014-12-06 03:21:08 +00002905 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002906 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002907 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002908
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002909 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002910 if (ASTReadResult Result =
2911 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2912 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002913 break;
2914
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002915 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002916 NumInputs = Record[0];
2917 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002918 F.InputFileOffsets =
2919 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002920 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002921 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 break;
2923 }
2924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002925}
2926
Ben Langmuir2c9af442014-04-10 17:57:43 +00002927ASTReader::ASTReadResult
2928ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002929 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002930
JF Bastien0e828952019-06-26 19:50:12 +00002931 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2932 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002933 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 }
2935
2936 // Read all of the records and blocks for the AST file.
2937 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002938 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002939 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2940 if (!MaybeEntry) {
2941 Error(MaybeEntry.takeError());
2942 return Failure;
2943 }
2944 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002945
Chris Lattnere7b154b2013-01-19 21:39:22 +00002946 switch (Entry.Kind) {
2947 case llvm::BitstreamEntry::Error:
2948 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002949 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002950 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002951 // Outside of C++, we do not store a lookup map for the translation unit.
2952 // Instead, mark it as needing a lookup map to be built if this module
2953 // contains any declarations lexically within it (which it always does!).
2954 // This usually has no cost, since we very rarely need the lookup map for
2955 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002956 if (ASTContext *Ctx = ContextObj) {
2957 DeclContext *DC = Ctx->getTranslationUnitDecl();
2958 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2959 DC->setMustBuildLookupTable();
2960 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002961
Ben Langmuir2c9af442014-04-10 17:57:43 +00002962 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002963 case llvm::BitstreamEntry::SubBlock:
2964 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 case DECLTYPES_BLOCK_ID:
2966 // We lazily load the decls block, but we want to set up the
2967 // DeclsCursor cursor to point into it. Clone our current bitcode
2968 // cursor to it, enter the block and read the abbrevs in that block.
2969 // With the main cursor, we just skip over it.
2970 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002971 if (llvm::Error Err = Stream.SkipBlock()) {
2972 Error(std::move(Err));
2973 return Failure;
2974 }
2975 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002977 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 }
2979 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002980
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 case PREPROCESSOR_BLOCK_ID:
2982 F.MacroCursor = Stream;
2983 if (!PP.getExternalSource())
2984 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002985
JF Bastien0e828952019-06-26 19:50:12 +00002986 if (llvm::Error Err = Stream.SkipBlock()) {
2987 Error(std::move(Err));
2988 return Failure;
2989 }
2990 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002992 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 }
2994 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2995 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002996
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 case PREPROCESSOR_DETAIL_BLOCK_ID:
2998 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002999
3000 if (llvm::Error Err = Stream.SkipBlock()) {
3001 Error(std::move(Err));
3002 return Failure;
3003 }
3004 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00003006 Error("malformed preprocessor detail record in AST file");
3007 return Failure;
3008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00003010 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003011
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 if (!PP.getPreprocessingRecord())
3013 PP.createPreprocessingRecord();
3014 if (!PP.getPreprocessingRecord()->getExternalSource())
3015 PP.getPreprocessingRecord()->SetExternalSource(*this);
3016 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003017
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 case SOURCE_MANAGER_BLOCK_ID:
3019 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003022
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00003024 if (ASTReadResult Result =
3025 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003028
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003030 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003031
3032 if (llvm::Error Err = Stream.SkipBlock()) {
3033 Error(std::move(Err));
3034 return Failure;
3035 }
3036 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
3040 CommentsCursors.push_back(std::make_pair(C, &F));
3041 break;
3042 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003043
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 default:
JF Bastien0e828952019-06-26 19:50:12 +00003045 if (llvm::Error Err = Stream.SkipBlock()) {
3046 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00003047 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003048 }
3049 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
3051 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052
Chris Lattnere7b154b2013-01-19 21:39:22 +00003053 case llvm::BitstreamEntry::Record:
3054 // The interesting case.
3055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
3057
3058 // Read and process a record.
3059 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003060 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003061 Expected<unsigned> MaybeRecordType =
3062 Stream.readRecord(Entry.ID, Record, &Blob);
3063 if (!MaybeRecordType) {
3064 Error(MaybeRecordType.takeError());
3065 return Failure;
3066 }
3067 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003068
3069 // If we're not loading an AST context, we don't care about most records.
3070 if (!ContextObj) {
3071 switch (RecordType) {
3072 case IDENTIFIER_TABLE:
3073 case IDENTIFIER_OFFSET:
3074 case INTERESTING_IDENTIFIERS:
3075 case STATISTICS:
3076 case PP_CONDITIONAL_STACK:
3077 case PP_COUNTER_VALUE:
3078 case SOURCE_LOCATION_OFFSETS:
3079 case MODULE_OFFSET_MAP:
3080 case SOURCE_MANAGER_LINE_TABLE:
3081 case SOURCE_LOCATION_PRELOADS:
3082 case PPD_ENTITIES_OFFSETS:
3083 case HEADER_SEARCH_TABLE:
3084 case IMPORTED_MODULES:
3085 case MACRO_OFFSET:
3086 break;
3087 default:
3088 continue;
3089 }
3090 }
3091
3092 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 default: // Default behavior: ignore.
3094 break;
3095
3096 case TYPE_OFFSET: {
3097 if (F.LocalNumTypes != 0) {
3098 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003099 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003101 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 F.LocalNumTypes = Record[0];
3103 unsigned LocalBaseTypeIndex = Record[1];
3104 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 if (F.LocalNumTypes > 0) {
3107 // Introduce the global -> local mapping for types within this module.
3108 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 // Introduce the local -> global mapping for types within this module.
3111 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003112 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003114
3115 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 }
3117 break;
3118 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 case DECL_OFFSET: {
3121 if (F.LocalNumDecls != 0) {
3122 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003125 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 F.LocalNumDecls = Record[0];
3127 unsigned LocalBaseDeclID = Record[1];
3128 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003129
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003131 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 // module.
3133 GlobalDeclMap.insert(
3134 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 // Introduce the local -> global mapping for declarations within this
3137 // module.
3138 F.DeclRemap.insertOrReplace(
3139 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003140
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 // Introduce the global -> local mapping for declarations within this
3142 // module.
3143 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003144
Ben Langmuir52ca6782014-10-20 16:27:32 +00003145 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 break;
3148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003149
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003151 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003152 LexicalContents Contents(
3153 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3154 Blob.data()),
3155 static_cast<unsigned int>(Blob.size() / 4));
3156 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 TU->setHasExternalLexicalStorage(true);
3158 break;
3159 }
3160
3161 case UPDATE_VISIBLE: {
3162 unsigned Idx = 0;
3163 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003164 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003165 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003166 // If we've already loaded the decl, perform the updates when we finish
3167 // loading this block.
3168 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003169 PendingUpdateRecords.push_back(
3170 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 break;
3172 }
3173
3174 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003175 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003177 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3178 (const unsigned char *)F.IdentifierTableData + Record[0],
3179 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3180 (const unsigned char *)F.IdentifierTableData,
3181 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003182
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3184 }
3185 break;
3186
3187 case IDENTIFIER_OFFSET: {
3188 if (F.LocalNumIdentifiers != 0) {
3189 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003190 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003192 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 F.LocalNumIdentifiers = Record[0];
3194 unsigned LocalBaseIdentifierID = Record[1];
3195 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003196
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 if (F.LocalNumIdentifiers > 0) {
3198 // Introduce the global -> local mapping for identifiers within this
3199 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003200 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003202
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 // Introduce the local -> global mapping for identifiers within this
3204 // module.
3205 F.IdentifierRemap.insertOrReplace(
3206 std::make_pair(LocalBaseIdentifierID,
3207 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003208
Ben Langmuir52ca6782014-10-20 16:27:32 +00003209 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3210 + F.LocalNumIdentifiers);
3211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 break;
3213 }
3214
Richard Smith33e0f7e2015-07-22 02:08:40 +00003215 case INTERESTING_IDENTIFIERS:
3216 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3217 break;
3218
Ben Langmuir332aafe2014-01-31 01:06:56 +00003219 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003220 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3221 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003223 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 break;
3225
David Blaikie9ffe5a32017-01-30 05:00:26 +00003226 case MODULAR_CODEGEN_DECLS:
3227 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3228 // them (ie: if we're not codegenerating this module).
Hans Wennborg7ea9a6e2020-02-27 14:33:43 +01003229 if (F.Kind == MK_MainFile)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003230 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3231 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3232 break;
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003235 if (SpecialTypes.empty()) {
3236 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3237 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3238 break;
3239 }
3240
3241 if (SpecialTypes.size() != Record.size()) {
3242 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003243 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003244 }
3245
3246 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3247 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3248 if (!SpecialTypes[I])
3249 SpecialTypes[I] = ID;
3250 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3251 // merge step?
3252 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 break;
3254
3255 case STATISTICS:
3256 TotalNumStatements += Record[0];
3257 TotalNumMacros += Record[1];
3258 TotalLexicalDeclContexts += Record[2];
3259 TotalVisibleDeclContexts += Record[3];
3260 break;
3261
3262 case UNUSED_FILESCOPED_DECLS:
3263 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3264 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3265 break;
3266
3267 case DELEGATING_CTORS:
3268 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3269 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3270 break;
3271
3272 case WEAK_UNDECLARED_IDENTIFIERS:
3273 if (Record.size() % 4 != 0) {
3274 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003275 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003277
3278 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 // files. This isn't the way to do it :)
3280 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 // Translate the weak, undeclared identifiers into global IDs.
3283 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3284 WeakUndeclaredIdentifiers.push_back(
3285 getGlobalIdentifierID(F, Record[I++]));
3286 WeakUndeclaredIdentifiers.push_back(
3287 getGlobalIdentifierID(F, Record[I++]));
3288 WeakUndeclaredIdentifiers.push_back(
3289 ReadSourceLocation(F, Record, I).getRawEncoding());
3290 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3291 }
3292 break;
3293
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003295 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 F.LocalNumSelectors = Record[0];
3297 unsigned LocalBaseSelectorID = Record[1];
3298 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003301 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 // module.
3303 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003304
3305 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 // module.
3307 F.SelectorRemap.insertOrReplace(
3308 std::make_pair(LocalBaseSelectorID,
3309 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003310
3311 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 }
3313 break;
3314 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003317 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 if (Record[0])
3319 F.SelectorLookupTable
3320 = ASTSelectorLookupTable::Create(
3321 F.SelectorLookupTableData + Record[0],
3322 F.SelectorLookupTableData,
3323 ASTSelectorLookupTrait(*this, F));
3324 TotalNumMethodPoolEntries += Record[1];
3325 break;
3326
3327 case REFERENCED_SELECTOR_POOL:
3328 if (!Record.empty()) {
3329 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003330 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 Record[Idx++]));
3332 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3333 getRawEncoding());
3334 }
3335 }
3336 break;
3337
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003338 case PP_CONDITIONAL_STACK:
3339 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003340 unsigned Idx = 0, End = Record.size() - 1;
3341 bool ReachedEOFWhileSkipping = Record[Idx++];
3342 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3343 if (ReachedEOFWhileSkipping) {
3344 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3345 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3346 bool FoundNonSkipPortion = Record[Idx++];
3347 bool FoundElse = Record[Idx++];
3348 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3349 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3350 FoundElse, ElseLoc);
3351 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003352 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003353 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003354 auto Loc = ReadSourceLocation(F, Record, Idx);
3355 bool WasSkipping = Record[Idx++];
3356 bool FoundNonSkip = Record[Idx++];
3357 bool FoundElse = Record[Idx++];
3358 ConditionalStack.push_back(
3359 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3360 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003361 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003362 }
3363 break;
3364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 case PP_COUNTER_VALUE:
3366 if (!Record.empty() && Listener)
3367 Listener->ReadCounter(F, Record[0]);
3368 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003369
Guy Benyei11169dd2012-12-18 14:30:41 +00003370 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003371 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 F.NumFileSortedDecls = Record[0];
3373 break;
3374
3375 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003376 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 F.LocalNumSLocEntries = Record[0];
3378 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003379 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003380 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003382 if (!F.SLocEntryBaseID) {
3383 Error("ran out of source locations");
3384 break;
3385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 // Make our entry in the range map. BaseID is negative and growing, so
3387 // we invert it. Because we invert it, though, we need the other end of
3388 // the range.
3389 unsigned RangeStart =
3390 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3391 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3392 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3393
3394 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3395 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3396 GlobalSLocOffsetMap.insert(
3397 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3398 - SLocSpaceSize,&F));
3399
3400 // Initialize the remapping table.
3401 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003402 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003404 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003406
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 TotalNumSLocEntries += F.LocalNumSLocEntries;
3408 break;
3409 }
3410
Richard Smith37a93df2017-02-18 00:32:02 +00003411 case MODULE_OFFSET_MAP:
3412 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003414
3415 case SOURCE_MANAGER_LINE_TABLE:
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003416 if (ParseLineTable(F, Record)) {
3417 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003418 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003419 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 break;
3421
3422 case SOURCE_LOCATION_PRELOADS: {
3423 // Need to transform from the local view (1-based IDs) to the global view,
3424 // which is based off F.SLocEntryBaseID.
3425 if (!F.PreloadSLocEntries.empty()) {
3426 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003427 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003429
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 F.PreloadSLocEntries.swap(Record);
3431 break;
3432 }
3433
3434 case EXT_VECTOR_DECLS:
3435 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3436 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3437 break;
3438
3439 case VTABLE_USES:
3440 if (Record.size() % 3 != 0) {
3441 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003444
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 // Later tables overwrite earlier ones.
3446 // FIXME: Modules will have some trouble with this. This is clearly not
3447 // the right way to do this.
3448 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003449
Guy Benyei11169dd2012-12-18 14:30:41 +00003450 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3451 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3452 VTableUses.push_back(
3453 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3454 VTableUses.push_back(Record[Idx++]);
3455 }
3456 break;
3457
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 case PENDING_IMPLICIT_INSTANTIATIONS:
3459 if (PendingInstantiations.size() % 2 != 0) {
3460 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003461 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 }
3463
3464 if (Record.size() % 2 != 0) {
3465 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 }
3468
3469 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3470 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3471 PendingInstantiations.push_back(
3472 ReadSourceLocation(F, Record, I).getRawEncoding());
3473 }
3474 break;
3475
3476 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003477 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003478 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003479 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3482 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3483 break;
3484
3485 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003486 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3487 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3488 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003489
3490 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003491
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 unsigned StartingID;
3493 if (!PP.getPreprocessingRecord())
3494 PP.createPreprocessingRecord();
3495 if (!PP.getPreprocessingRecord()->getExternalSource())
3496 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003497 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003499 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 F.BasePreprocessedEntityID = StartingID;
3501
3502 if (F.NumPreprocessedEntities > 0) {
3503 // Introduce the global -> local mapping for preprocessed entities in
3504 // this module.
3505 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003506
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 // Introduce the local -> global mapping for preprocessed entities in
3508 // this module.
3509 F.PreprocessedEntityRemap.insertOrReplace(
3510 std::make_pair(LocalBasePreprocessedEntityID,
3511 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3512 }
3513
3514 break;
3515 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003516
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003517 case PPD_SKIPPED_RANGES: {
3518 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3519 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3520 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3521
3522 if (!PP.getPreprocessingRecord())
3523 PP.createPreprocessingRecord();
3524 if (!PP.getPreprocessingRecord()->getExternalSource())
3525 PP.getPreprocessingRecord()->SetExternalSource(*this);
3526 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3527 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003528
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003529 if (F.NumPreprocessedSkippedRanges > 0)
3530 GlobalSkippedRangeMap.insert(
3531 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3532 break;
3533 }
3534
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003535 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 if (Record.size() % 2 != 0) {
3537 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003538 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003540 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3541 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3542 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3543
3544 // If we've already loaded the decl, perform the updates when we finish
3545 // loading this block.
3546 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003547 PendingUpdateRecords.push_back(
3548 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003549 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003551
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003552 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 if (F.LocalNumObjCCategoriesInMap != 0) {
3554 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003555 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003557
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003559 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003561
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 case OBJC_CATEGORIES:
3563 F.ObjCCategories.swap(Record);
3564 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003565
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 case CUDA_SPECIAL_DECL_REFS:
3567 // Later tables overwrite earlier ones.
3568 // FIXME: Modules will have trouble with this.
3569 CUDASpecialDeclRefs.clear();
3570 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3571 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3572 break;
3573
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003574 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003575 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 if (Record[0]) {
3578 F.HeaderFileInfoTable
3579 = HeaderFileInfoLookupTable::Create(
3580 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3581 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003582 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003584 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003585
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 PP.getHeaderSearchInfo().SetExternalSource(this);
3587 if (!PP.getHeaderSearchInfo().getExternalLookup())
3588 PP.getHeaderSearchInfo().SetExternalLookup(this);
3589 }
3590 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003591
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 case FP_PRAGMA_OPTIONS:
3593 // Later tables overwrite earlier ones.
3594 FPPragmaOptions.swap(Record);
3595 break;
3596
3597 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003598 for (unsigned I = 0, E = Record.size(); I != E; ) {
3599 auto Name = ReadString(Record, I);
3600 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003601 Opt.Supported = Record[I++] != 0;
3602 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003603 Opt.Avail = Record[I++];
3604 Opt.Core = Record[I++];
3605 }
3606 break;
3607
3608 case OPENCL_EXTENSION_TYPES:
3609 for (unsigned I = 0, E = Record.size(); I != E;) {
3610 auto TypeID = static_cast<::TypeID>(Record[I++]);
3611 auto *Type = GetType(TypeID).getTypePtr();
3612 auto NumExt = static_cast<unsigned>(Record[I++]);
3613 for (unsigned II = 0; II != NumExt; ++II) {
3614 auto Ext = ReadString(Record, I);
3615 OpenCLTypeExtMap[Type].insert(Ext);
3616 }
3617 }
3618 break;
3619
3620 case OPENCL_EXTENSION_DECLS:
3621 for (unsigned I = 0, E = Record.size(); I != E;) {
3622 auto DeclID = static_cast<::DeclID>(Record[I++]);
3623 auto *Decl = GetDecl(DeclID);
3624 auto NumExt = static_cast<unsigned>(Record[I++]);
3625 for (unsigned II = 0; II != NumExt; ++II) {
3626 auto Ext = ReadString(Record, I);
3627 OpenCLDeclExtMap[Decl].insert(Ext);
3628 }
3629 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 break;
3631
3632 case TENTATIVE_DEFINITIONS:
3633 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3634 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3635 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003636
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 case KNOWN_NAMESPACES:
3638 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3639 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3640 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003641
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003642 case UNDEFINED_BUT_USED:
3643 if (UndefinedButUsed.size() % 2 != 0) {
3644 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003645 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003646 }
3647
3648 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003649 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003650 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003651 }
3652 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003653 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3654 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003655 ReadSourceLocation(F, Record, I).getRawEncoding());
3656 }
3657 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003658
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003659 case DELETE_EXPRS_TO_ANALYZE:
3660 for (unsigned I = 0, N = Record.size(); I != N;) {
3661 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3662 const uint64_t Count = Record[I++];
3663 DelayedDeleteExprs.push_back(Count);
3664 for (uint64_t C = 0; C < Count; ++C) {
3665 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3666 bool IsArrayForm = Record[I++] == 1;
3667 DelayedDeleteExprs.push_back(IsArrayForm);
3668 }
3669 }
3670 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003671
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003672 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003673 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 // If we aren't loading a module (which has its own exports), make
3675 // all of the imported modules visible.
3676 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003677 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3678 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3679 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003680 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003681 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003682 if (DeserializationListener)
3683 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3684 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003685 }
3686 }
3687 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003688
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 case MACRO_OFFSET: {
3690 if (F.LocalNumMacros != 0) {
3691 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003692 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003694 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 F.LocalNumMacros = Record[0];
3696 unsigned LocalBaseMacroID = Record[1];
3697 F.BaseMacroID = getTotalNumMacros();
3698
3699 if (F.LocalNumMacros > 0) {
3700 // Introduce the global -> local mapping for macros within this module.
3701 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3702
3703 // Introduce the local -> global mapping for macros within this module.
3704 F.MacroRemap.insertOrReplace(
3705 std::make_pair(LocalBaseMacroID,
3706 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003707
3708 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 }
3710 break;
3711 }
3712
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003713 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003714 LateParsedTemplates.append(Record.begin(), Record.end());
3715 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003716
3717 case OPTIMIZE_PRAGMA_OPTIONS:
3718 if (Record.size() != 1) {
3719 Error("invalid pragma optimize record");
3720 return Failure;
3721 }
3722 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3723 break;
Nico Weber72889432014-09-06 01:25:55 +00003724
Nico Weber779355f2016-03-02 23:22:00 +00003725 case MSSTRUCT_PRAGMA_OPTIONS:
3726 if (Record.size() != 1) {
3727 Error("invalid pragma ms_struct record");
3728 return Failure;
3729 }
3730 PragmaMSStructState = Record[0];
3731 break;
3732
Nico Weber42932312016-03-03 00:17:35 +00003733 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3734 if (Record.size() != 2) {
3735 Error("invalid pragma ms_struct record");
3736 return Failure;
3737 }
3738 PragmaMSPointersToMembersState = Record[0];
3739 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3740 break;
3741
Nico Weber72889432014-09-06 01:25:55 +00003742 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3743 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3744 UnusedLocalTypedefNameCandidates.push_back(
3745 getGlobalDeclID(F, Record[I]));
3746 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003747
3748 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3749 if (Record.size() != 1) {
3750 Error("invalid cuda pragma options record");
3751 return Failure;
3752 }
3753 ForceCUDAHostDeviceDepth = Record[0];
3754 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003755
3756 case PACK_PRAGMA_OPTIONS: {
3757 if (Record.size() < 3) {
3758 Error("invalid pragma pack record");
3759 return Failure;
3760 }
3761 PragmaPackCurrentValue = Record[0];
3762 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3763 unsigned NumStackEntries = Record[2];
3764 unsigned Idx = 3;
3765 // Reset the stack when importing a new module.
3766 PragmaPackStack.clear();
3767 for (unsigned I = 0; I < NumStackEntries; ++I) {
3768 PragmaPackStackEntry Entry;
3769 Entry.Value = Record[Idx++];
3770 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003771 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003772 PragmaPackStrings.push_back(ReadString(Record, Idx));
3773 Entry.SlotLabel = PragmaPackStrings.back();
3774 PragmaPackStack.push_back(Entry);
3775 }
3776 break;
3777 }
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05003778
3779 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3780 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3781 DeclsToCheckForDeferredDiags.push_back(getGlobalDeclID(F, Record[I]));
3782 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003783 }
3784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003785}
3786
Richard Smith37a93df2017-02-18 00:32:02 +00003787void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3788 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3789
3790 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003791 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003792 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3793 F.ModuleOffsetMap = StringRef();
3794
3795 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3796 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3797 F.SLocRemap.insert(std::make_pair(0U, 0));
3798 F.SLocRemap.insert(std::make_pair(2U, 1));
3799 }
3800
3801 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003802 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003803 RemapBuilder SLocRemap(F.SLocRemap);
3804 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3805 RemapBuilder MacroRemap(F.MacroRemap);
3806 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3807 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3808 RemapBuilder SelectorRemap(F.SelectorRemap);
3809 RemapBuilder DeclRemap(F.DeclRemap);
3810 RemapBuilder TypeRemap(F.TypeRemap);
3811
3812 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003813 // FIXME: Looking up dependency modules by filename is horrible. Let's
3814 // start fixing this with prebuilt and explicit modules and see how it
3815 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003816 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003817 ModuleKind Kind = static_cast<ModuleKind>(
3818 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003819 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3820 StringRef Name = StringRef((const char*)Data, Len);
3821 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003822 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3823 ? ModuleMgr.lookupByModuleName(Name)
3824 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003825 if (!OM) {
3826 std::string Msg =
3827 "SourceLocation remap refers to unknown module, cannot find ";
Benjamin Krameradcd0262020-01-28 20:23:46 +01003828 Msg.append(std::string(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003829 Error(Msg);
3830 return;
3831 }
3832
3833 uint32_t SLocOffset =
3834 endian::readNext<uint32_t, little, unaligned>(Data);
3835 uint32_t IdentifierIDOffset =
3836 endian::readNext<uint32_t, little, unaligned>(Data);
3837 uint32_t MacroIDOffset =
3838 endian::readNext<uint32_t, little, unaligned>(Data);
3839 uint32_t PreprocessedEntityIDOffset =
3840 endian::readNext<uint32_t, little, unaligned>(Data);
3841 uint32_t SubmoduleIDOffset =
3842 endian::readNext<uint32_t, little, unaligned>(Data);
3843 uint32_t SelectorIDOffset =
3844 endian::readNext<uint32_t, little, unaligned>(Data);
3845 uint32_t DeclIDOffset =
3846 endian::readNext<uint32_t, little, unaligned>(Data);
3847 uint32_t TypeIndexOffset =
3848 endian::readNext<uint32_t, little, unaligned>(Data);
3849
3850 uint32_t None = std::numeric_limits<uint32_t>::max();
3851
3852 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3853 RemapBuilder &Remap) {
3854 if (Offset != None)
3855 Remap.insert(std::make_pair(Offset,
3856 static_cast<int>(BaseOffset - Offset)));
3857 };
3858 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3859 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3860 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3861 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3862 PreprocessedEntityRemap);
3863 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3864 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3865 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3866 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3867
3868 // Global -> local mappings.
3869 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3870 }
3871}
3872
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003873ASTReader::ASTReadResult
3874ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3875 const ModuleFile *ImportedBy,
3876 unsigned ClientLoadCapabilities) {
3877 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003878 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003879
3880 // Try to resolve ModuleName in the current header search context and
3881 // verify that it is found in the same module map file as we saved. If the
3882 // top-level AST file is a main file, skip this check because there is no
3883 // usable header search context.
3884 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003885 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003886 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003887 // An implicitly-loaded module file should have its module listed in some
3888 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003889 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003890 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3891 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003892 // Don't emit module relocation error if we have -fno-validate-pch
3893 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003894 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003895 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003896 // This module was defined by an imported (explicit) module.
3897 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3898 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003899 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003900 // This module was built with a different module map.
3901 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003902 << F.ModuleName << F.FileName
3903 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3904 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003905 // In case it was imported by a PCH, there's a chance the user is
3906 // just missing to include the search path to the directory containing
3907 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003908 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003909 Diag(diag::note_imported_by_pch_module_not_found)
3910 << llvm::sys::path::parent_path(F.ModuleMapPath);
3911 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003912 }
3913 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003914 }
3915
Richard Smithe842a472014-10-22 02:05:46 +00003916 assert(M->Name == F.ModuleName && "found module with different name");
3917
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003918 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003919 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3920 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003921 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003922 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3923 "top-level import should be verified");
3924 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003925 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3926 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003927 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3928 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003929 return OutOfDate;
3930 }
3931
3932 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3933 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3934 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003935 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003936 auto F = FileMgr.getFile(Filename, false, false);
3937 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003938 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3939 Error("could not find file '" + Filename +"' referenced by AST file");
3940 return OutOfDate;
3941 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003942 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003943 }
3944
3945 // Check any additional module map files (e.g. module.private.modulemap)
3946 // that are not in the pcm.
3947 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003948 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003949 // Remove files that match
3950 // Note: SmallPtrSet::erase is really remove
3951 if (!AdditionalStoredMaps.erase(ModMap)) {
3952 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3953 Diag(diag::err_module_different_modmap)
3954 << F.ModuleName << /*new*/0 << ModMap->getName();
3955 return OutOfDate;
3956 }
3957 }
3958 }
3959
3960 // Check any additional module map files that are in the pcm, but not
3961 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003962 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003963 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3964 Diag(diag::err_module_different_modmap)
3965 << F.ModuleName << /*not new*/1 << ModMap->getName();
3966 return OutOfDate;
3967 }
3968 }
3969
3970 if (Listener)
3971 Listener->ReadModuleMapFile(F.ModuleMapPath);
3972 return Success;
3973}
3974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003975/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003976static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3977 // Find the entry for this selector in the method pool.
3978 Sema::GlobalMethodPool::iterator Known
3979 = S.MethodPool.find(Method->getSelector());
3980 if (Known == S.MethodPool.end())
3981 return;
3982
3983 // Retrieve the appropriate method list.
3984 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3985 : Known->second.second;
3986 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003987 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003988 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003989 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003990 Found = true;
3991 } else {
3992 // Keep searching.
3993 continue;
3994 }
3995 }
3996
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003997 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003998 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003999 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00004000 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00004001 }
4002}
4003
Richard Smithde711422015-04-23 21:20:19 +00004004void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00004005 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00004006 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00004007 bool wasHidden = D->isHidden();
4008 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00004009
Vedant Kumar48b4f762018-04-14 01:40:48 +00004010 if (wasHidden && SemaObj) {
4011 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004012 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004013 }
4014 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 }
4016}
4017
Richard Smith49f906a2014-03-01 00:08:04 +00004018void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004019 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004020 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004022 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004023 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004025 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004026
4027 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004028 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 // there is nothing more to do.
4030 continue;
4031 }
Richard Smith49f906a2014-03-01 00:08:04 +00004032
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 if (!Mod->isAvailable()) {
4034 // Modules that aren't available cannot be made visible.
4035 continue;
4036 }
4037
4038 // Update the module's name visibility.
4039 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004040
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 // If we've already deserialized any names from this module,
4042 // mark them as visible.
4043 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4044 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004045 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004047 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004048 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4049 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004051
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004053 SmallVector<Module *, 16> Exports;
4054 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004055 for (SmallVectorImpl<Module *>::iterator
4056 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4057 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004058 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004059 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 }
4062}
4063
Richard Smith6561f922016-09-12 21:06:40 +00004064/// We've merged the definition \p MergedDef into the existing definition
4065/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4066/// visible.
4067void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4068 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004069 if (Def->isHidden()) {
4070 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004071 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004072 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004073 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004074 getContext().mergeDefinitionIntoModule(
4075 Def, MergedDef->getImportedOwningModule(),
4076 /*NotifyListeners*/ false);
4077 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004078 }
Richard Smith6561f922016-09-12 21:06:40 +00004079 }
4080}
4081
Douglas Gregore060e572013-01-25 01:03:03 +00004082bool ASTReader::loadGlobalIndex() {
4083 if (GlobalIndex)
4084 return false;
4085
4086 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004087 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004088 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004089
Douglas Gregore060e572013-01-25 01:03:03 +00004090 // Try to load the global index.
4091 TriedLoadingGlobalIndex = true;
4092 StringRef ModuleCachePath
4093 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004094 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4095 GlobalModuleIndex::readIndex(ModuleCachePath);
4096 if (llvm::Error Err = std::move(Result.second)) {
4097 assert(!Result.first);
4098 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004099 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004100 }
Douglas Gregore060e572013-01-25 01:03:03 +00004101
4102 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004103 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004104 return false;
4105}
4106
4107bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004108 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004109 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4110}
4111
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004112static void updateModuleTimestamp(ModuleFile &MF) {
4113 // Overwrite the timestamp file contents so that file's mtime changes.
4114 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004115 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004116 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004117 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004118 return;
4119 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004120 OS.close();
4121 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004122}
4123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004124/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004125/// cursor into the start of the given block ID, returning false on success and
4126/// true on failure.
4127static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004128 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004129 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4130 if (!MaybeEntry) {
4131 // FIXME this drops errors on the floor.
4132 consumeError(MaybeEntry.takeError());
4133 return true;
4134 }
4135 llvm::BitstreamEntry Entry = MaybeEntry.get();
4136
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004137 switch (Entry.Kind) {
4138 case llvm::BitstreamEntry::Error:
4139 case llvm::BitstreamEntry::EndBlock:
4140 return true;
4141
4142 case llvm::BitstreamEntry::Record:
4143 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004144 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4145 break;
4146 else {
4147 // FIXME this drops errors on the floor.
4148 consumeError(Skipped.takeError());
4149 return true;
4150 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004151
4152 case llvm::BitstreamEntry::SubBlock:
4153 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004154 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4155 // FIXME this drops the error on the floor.
4156 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004157 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004158 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004159 // Found it!
4160 return false;
4161 }
4162
JF Bastien0e828952019-06-26 19:50:12 +00004163 if (llvm::Error Err = Cursor.SkipBlock()) {
4164 // FIXME this drops the error on the floor.
4165 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004166 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004167 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004168 }
4169 }
4170}
4171
Benjamin Kramer0772c422016-02-13 13:42:54 +00004172ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 ModuleKind Type,
4174 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004175 unsigned ClientLoadCapabilities,
4176 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004177 llvm::SaveAndRestore<SourceLocation>
4178 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4179
Richard Smithd1c46742014-04-30 02:24:17 +00004180 // Defer any pending actions until we get to the end of reading the AST file.
4181 Deserializing AnASTFile(this);
4182
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004184 unsigned PreviousGeneration = 0;
4185 if (ContextObj)
4186 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004187
4188 unsigned NumModules = ModuleMgr.size();
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004189 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4190 assert(ReadResult && "expected to return error");
Duncan P. N. Exon Smith8e9e4332019-11-10 10:31:03 -08004191 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004192 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004193 ? &PP.getHeaderSearchInfo().getModuleMap()
4194 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004195
4196 // If we find that any modules are unusable, the global index is going
4197 // to be out-of-date. Just remove it.
4198 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004199 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 return ReadResult;
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004201 };
4202
4203 SmallVector<ImportedModule, 4> Loaded;
4204 switch (ASTReadResult ReadResult =
4205 ReadASTCore(FileName, Type, ImportLoc,
4206 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4207 ASTFileSignature(), ClientLoadCapabilities)) {
4208 case Failure:
4209 case Missing:
4210 case OutOfDate:
4211 case VersionMismatch:
4212 case ConfigurationMismatch:
4213 case HadErrors:
4214 return removeModulesAndReturn(ReadResult);
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 case Success:
4216 break;
4217 }
4218
4219 // Here comes stuff that we only do once the entire chain is loaded.
4220
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004221 // Load the AST blocks of all of the modules that we loaded. We can still
4222 // hit errors parsing the ASTs at this point.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004223 for (ImportedModule &M : Loaded) {
4224 ModuleFile &F = *M.Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004225
4226 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004227 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004228 return removeModulesAndReturn(Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00004229
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08004230 // The AST block should always have a definition for the main module.
4231 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4232 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4233 return removeModulesAndReturn(Failure);
4234 }
4235
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004236 // Read the extension blocks.
4237 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4238 if (ASTReadResult Result = ReadExtensionBlock(F))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004239 return removeModulesAndReturn(Result);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004240 }
4241
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004242 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 // bits of all files we've seen.
4244 F.GlobalBitOffset = TotalModulesSizeInBits;
4245 TotalModulesSizeInBits += F.SizeInBits;
4246 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004247 }
4248
4249 // Preload source locations and interesting indentifiers.
4250 for (ImportedModule &M : Loaded) {
4251 ModuleFile &F = *M.Mod;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004252
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004254 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4255 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 // Load it through the SourceManager and don't call ReadSLocEntry()
4257 // directly because the entry may have already been loaded in which case
4258 // calling ReadSLocEntry() directly would trigger an assertion in
4259 // SourceManager.
4260 SourceMgr.getLoadedSLocEntryByID(Index);
4261 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004262
Richard Smithea741482017-05-01 22:10:47 +00004263 // Map the original source file ID into the ID space of the current
4264 // compilation.
4265 if (F.OriginalSourceFileID.isValid()) {
4266 F.OriginalSourceFileID = FileID::get(
4267 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4268 }
4269
Richard Smith33e0f7e2015-07-22 02:08:40 +00004270 // Preload all the pending interesting identifiers by marking them out of
4271 // date.
4272 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004273 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004274 F.IdentifierTableData + Offset);
4275
4276 ASTIdentifierLookupTrait Trait(*this, F);
4277 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4278 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004279 auto &II = PP.getIdentifierTable().getOwn(Key);
4280 II.setOutOfDate(true);
4281
4282 // Mark this identifier as being from an AST file so that we can track
4283 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004284 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004285
4286 // Associate the ID with the identifier so that the writer can reuse it.
4287 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4288 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004289 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 }
4291
Douglas Gregor603cd862013-03-22 18:50:14 +00004292 // Setup the import locations and notify the module manager that we've
4293 // committed to these module files.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004294 for (ImportedModule &M : Loaded) {
4295 ModuleFile &F = *M.Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004296
4297 ModuleMgr.moduleFileAccepted(&F);
4298
4299 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004300 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004301 // FIXME: We assume that locations from PCH / preamble do not need
4302 // any translation.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004303 if (!M.ImportedBy)
4304 F.ImportLoc = M.ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 else
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004306 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308
Richard Smithdbafb6c2017-06-29 23:23:46 +00004309 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004310 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4311 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004312 // Mark all of the identifiers in the identifier table as being out of date,
4313 // so that various accessors know to check the loaded modules when the
4314 // identifier is used.
4315 //
4316 // For C++ modules, we don't need information on many identifiers (just
4317 // those that provide macros or are poisoned), so we mark all of
4318 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004319 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4320 IdEnd = PP.getIdentifierTable().end();
4321 Id != IdEnd; ++Id)
4322 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004323 }
Manman Rena0f31a02016-04-29 19:04:05 +00004324 // Mark selectors as out of date.
4325 for (auto Sel : SelectorGeneration)
4326 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004327
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004329 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4330 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4332 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004333
4334 switch (Unresolved.Kind) {
4335 case UnresolvedModuleRef::Conflict:
4336 if (ResolvedMod) {
4337 Module::Conflict Conflict;
4338 Conflict.Other = ResolvedMod;
4339 Conflict.Message = Unresolved.String.str();
4340 Unresolved.Mod->Conflicts.push_back(Conflict);
4341 }
4342 continue;
4343
4344 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004346 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348
Douglas Gregorfb912652013-03-20 21:10:35 +00004349 case UnresolvedModuleRef::Export:
4350 if (ResolvedMod || Unresolved.IsWildcard)
4351 Unresolved.Mod->Exports.push_back(
4352 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4353 continue;
4354 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004356 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004357
Graydon Hoaree7196af2016-12-09 21:45:49 +00004358 if (Imported)
4359 Imported->append(ImportedModules.begin(),
4360 ImportedModules.end());
4361
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004362 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4363 // Might be unnecessary as use declarations are only used to build the
4364 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004365
Richard Smithdbafb6c2017-06-29 23:23:46 +00004366 if (ContextObj)
4367 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004368
Richard Smith3d8e97e2013-10-18 06:54:39 +00004369 if (SemaObj)
4370 UpdateSema();
4371
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 if (DeserializationListener)
4373 DeserializationListener->ReaderInitialized(this);
4374
4375 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004376 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 // If this AST file is a precompiled preamble, then set the
4378 // preamble file ID of the source manager to the file source file
4379 // from which the preamble was built.
4380 if (Type == MK_Preamble) {
4381 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4382 } else if (Type == MK_MainFile) {
4383 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4384 }
4385 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004386
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 // For any Objective-C class definitions we have already loaded, make sure
4388 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004389 if (ContextObj) {
4390 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4391 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4392 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004393 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004394 }
4395 }
Douglas Gregore060e572013-01-25 01:03:03 +00004396
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004397 if (PP.getHeaderSearchInfo()
4398 .getHeaderSearchOpts()
4399 .ModulesValidateOncePerBuildSession) {
4400 // Now we are certain that the module and all modules it depends on are
4401 // up to date. Create or update timestamp files for modules that are
4402 // located in the module cache (not for PCH files that could be anywhere
4403 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004404 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4405 ImportedModule &M = Loaded[I];
4406 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004407 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004408 }
4409 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004410 }
4411
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 return Success;
4413}
4414
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004415static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004416
JF Bastien0e828952019-06-26 19:50:12 +00004417/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4418static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4419 // FIXME checking magic headers is done in other places such as
4420 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4421 // always done the same. Unify it all with a helper.
4422 if (!Stream.canSkipToPos(4))
4423 return llvm::createStringError(std::errc::illegal_byte_sequence,
4424 "file too small to contain AST file magic");
4425 for (unsigned C : {'C', 'P', 'C', 'H'})
4426 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4427 if (Res.get() != C)
4428 return llvm::createStringError(
4429 std::errc::illegal_byte_sequence,
4430 "file doesn't start with AST file magic");
4431 } else
4432 return Res.takeError();
4433 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004434}
4435
Richard Smith0f99d6a2015-08-09 08:48:41 +00004436static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4437 switch (Kind) {
4438 case MK_PCH:
4439 return 0; // PCH
4440 case MK_ImplicitModule:
4441 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004442 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004443 return 1; // module
4444 case MK_MainFile:
4445 case MK_Preamble:
4446 return 2; // main source file
4447 }
4448 llvm_unreachable("unknown module kind");
4449}
4450
Guy Benyei11169dd2012-12-18 14:30:41 +00004451ASTReader::ASTReadResult
4452ASTReader::ReadASTCore(StringRef FileName,
4453 ModuleKind Type,
4454 SourceLocation ImportLoc,
4455 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004456 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004457 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004458 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 unsigned ClientLoadCapabilities) {
4460 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004462 ModuleManager::AddModuleResult AddResult
4463 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004464 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004465 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004466 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004467
Douglas Gregor7029ce12013-03-19 00:28:20 +00004468 switch (AddResult) {
4469 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004470 Diag(diag::remark_module_import)
4471 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4472 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004473 return Success;
4474
4475 case ModuleManager::NewlyLoaded:
4476 // Load module file below.
4477 break;
4478
4479 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004480 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004481 // it.
4482 if (ClientLoadCapabilities & ARR_Missing)
4483 return Missing;
4484
4485 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004486 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004487 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004488 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004489 return Failure;
4490
4491 case ModuleManager::OutOfDate:
4492 // We couldn't load the module file because it is out-of-date. If the
4493 // client can handle out-of-date, return it.
4494 if (ClientLoadCapabilities & ARR_OutOfDate)
4495 return OutOfDate;
4496
4497 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004498 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004499 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004500 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 return Failure;
4502 }
4503
Douglas Gregor7029ce12013-03-19 00:28:20 +00004504 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004505
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004506 bool ShouldFinalizePCM = false;
4507 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4508 auto &MC = getModuleManager().getModuleCache();
4509 if (ShouldFinalizePCM)
4510 MC.finalizePCM(FileName);
4511 else
Rumeet Dhindsa57a2eaf2020-03-10 10:59:26 -07004512 MC.tryToDropPCM(FileName);
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004513 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004515 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004516 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004517 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004518
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004520 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4521 Diag(diag::err_module_file_invalid)
4522 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 return Failure;
4524 }
4525
4526 // This is used for compatibility with older PCH formats.
4527 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004528 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004529 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4530 if (!MaybeEntry) {
4531 Error(MaybeEntry.takeError());
4532 return Failure;
4533 }
4534 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004535
Chris Lattnerefa77172013-01-20 00:00:22 +00004536 switch (Entry.Kind) {
4537 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004538 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004539 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 Error("invalid record at top-level of AST file");
4541 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004542
Chris Lattnerefa77172013-01-20 00:00:22 +00004543 case llvm::BitstreamEntry::SubBlock:
4544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
Chris Lattnerefa77172013-01-20 00:00:22 +00004547 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 case CONTROL_BLOCK_ID:
4549 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004550 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004552 // Check that we didn't try to load a non-module AST file as a module.
4553 //
4554 // FIXME: Should we also perform the converse check? Loading a module as
4555 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004556 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4557 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004558 F.ModuleName.empty()) {
4559 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4560 if (Result != OutOfDate ||
4561 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4562 Diag(diag::err_module_file_not_module) << FileName;
4563 return Result;
4564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 break;
4566
4567 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004568 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 case OutOfDate: return OutOfDate;
4570 case VersionMismatch: return VersionMismatch;
4571 case ConfigurationMismatch: return ConfigurationMismatch;
4572 case HadErrors: return HadErrors;
4573 }
4574 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004575
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 case AST_BLOCK_ID:
4577 if (!HaveReadControlBlock) {
4578 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004579 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 return VersionMismatch;
4581 }
4582
4583 // Record that we've loaded this module.
4584 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004585 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 return Success;
4587
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004588 case UNHASHED_CONTROL_BLOCK_ID:
4589 // This block is handled using look-ahead during ReadControlBlock. We
4590 // shouldn't get here!
4591 Error("malformed block record in AST file");
4592 return Failure;
4593
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 default:
JF Bastien0e828952019-06-26 19:50:12 +00004595 if (llvm::Error Err = Stream.SkipBlock()) {
4596 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 return Failure;
4598 }
4599 break;
4600 }
4601 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004602
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004603 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004604}
4605
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004606ASTReader::ASTReadResult
4607ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4608 unsigned ClientLoadCapabilities) {
4609 const HeaderSearchOptions &HSOpts =
4610 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4611 bool AllowCompatibleConfigurationMismatch =
4612 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4613
4614 ASTReadResult Result = readUnhashedControlBlockImpl(
4615 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4616 Listener.get(),
4617 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4618
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004619 // If F was directly imported by another module, it's implicitly validated by
4620 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004621 if (DisableValidation || WasImportedBy ||
4622 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4623 return Success;
4624
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004625 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004626 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004627 return Failure;
4628 }
4629
4630 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004631 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004632 // with it; we can only load a single version of each module.
4633 //
4634 // This can happen when a module is imported in two contexts: in one, as a
4635 // user module; in another, as a system module (due to an import from
4636 // another module marked with the [system] flag). It usually indicates a
4637 // bug in the module map: this module should also be marked with [system].
4638 //
4639 // If -Wno-system-headers (the default), and the first import is as a
4640 // system module, then validation will fail during the as-user import,
4641 // since -Werror flags won't have been validated. However, it's reasonable
4642 // to treat this consistently as a system module.
4643 //
4644 // If -Wsystem-headers, the PCM on disk was built with
4645 // -Wno-system-headers, and the first import is as a user module, then
4646 // validation will fail during the as-system import since the PCM on disk
4647 // doesn't guarantee that -Werror was respected. However, the -Werror
4648 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004649 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004650 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4651 return Success;
4652 }
4653 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004654
4655 return Result;
4656}
4657
4658ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4659 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4660 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4661 bool ValidateDiagnosticOptions) {
4662 // Initialize a stream.
4663 BitstreamCursor Stream(StreamData);
4664
4665 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004666 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4667 // FIXME this drops the error on the floor.
4668 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004669 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004670 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004671
4672 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4673 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4674 return Failure;
4675
4676 // Read all of the records in the options block.
4677 RecordData Record;
4678 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004679 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004680 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4681 if (!MaybeEntry) {
4682 // FIXME this drops the error on the floor.
4683 consumeError(MaybeEntry.takeError());
4684 return Failure;
4685 }
4686 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004687
4688 switch (Entry.Kind) {
4689 case llvm::BitstreamEntry::Error:
4690 case llvm::BitstreamEntry::SubBlock:
4691 return Failure;
4692
4693 case llvm::BitstreamEntry::EndBlock:
4694 return Result;
4695
4696 case llvm::BitstreamEntry::Record:
4697 // The interesting case.
4698 break;
4699 }
4700
4701 // Read and process a record.
4702 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004703 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4704 if (!MaybeRecordType) {
4705 // FIXME this drops the error.
4706 return Failure;
4707 }
4708 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004709 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004710 if (F)
4711 std::copy(Record.begin(), Record.end(), F->Signature.data());
4712 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004713 case DIAGNOSTIC_OPTIONS: {
4714 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4715 if (Listener && ValidateDiagnosticOptions &&
4716 !AllowCompatibleConfigurationMismatch &&
4717 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004718 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004719 break;
4720 }
4721 case DIAG_PRAGMA_MAPPINGS:
4722 if (!F)
4723 break;
4724 if (F->PragmaDiagMappings.empty())
4725 F->PragmaDiagMappings.swap(Record);
4726 else
4727 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4728 Record.begin(), Record.end());
4729 break;
4730 }
4731 }
4732}
4733
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004734/// Parse a record and blob containing module file extension metadata.
4735static bool parseModuleFileExtensionMetadata(
4736 const SmallVectorImpl<uint64_t> &Record,
4737 StringRef Blob,
4738 ModuleFileExtensionMetadata &Metadata) {
4739 if (Record.size() < 4) return true;
4740
4741 Metadata.MajorVersion = Record[0];
4742 Metadata.MinorVersion = Record[1];
4743
4744 unsigned BlockNameLen = Record[2];
4745 unsigned UserInfoLen = Record[3];
4746
4747 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4748
4749 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4750 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4751 Blob.data() + BlockNameLen + UserInfoLen);
4752 return false;
4753}
4754
4755ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4756 BitstreamCursor &Stream = F.Stream;
4757
4758 RecordData Record;
4759 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004760 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4761 if (!MaybeEntry) {
4762 Error(MaybeEntry.takeError());
4763 return Failure;
4764 }
4765 llvm::BitstreamEntry Entry = MaybeEntry.get();
4766
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004767 switch (Entry.Kind) {
4768 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004769 if (llvm::Error Err = Stream.SkipBlock()) {
4770 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004771 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004772 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004773 continue;
4774
4775 case llvm::BitstreamEntry::EndBlock:
4776 return Success;
4777
4778 case llvm::BitstreamEntry::Error:
4779 return HadErrors;
4780
4781 case llvm::BitstreamEntry::Record:
4782 break;
4783 }
4784
4785 Record.clear();
4786 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004787 Expected<unsigned> MaybeRecCode =
4788 Stream.readRecord(Entry.ID, Record, &Blob);
4789 if (!MaybeRecCode) {
4790 Error(MaybeRecCode.takeError());
4791 return Failure;
4792 }
4793 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004794 case EXTENSION_METADATA: {
4795 ModuleFileExtensionMetadata Metadata;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004796 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4797 Error("malformed EXTENSION_METADATA in AST file");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004798 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004799 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004800
4801 // Find a module file extension with this block name.
4802 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4803 if (Known == ModuleFileExtensions.end()) break;
4804
4805 // Form a reader.
4806 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4807 F, Stream)) {
4808 F.ExtensionReaders.push_back(std::move(Reader));
4809 }
4810
4811 break;
4812 }
4813 }
4814 }
4815
4816 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004817}
4818
Richard Smitha7e2cc62015-05-01 01:53:09 +00004819void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004820 assert(ContextObj && "no context to initialize");
4821 ASTContext &Context = *ContextObj;
4822
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 // If there's a listener, notify them that we "read" the translation unit.
4824 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004825 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 Context.getTranslationUnitDecl());
4827
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 // FIXME: Find a better way to deal with collisions between these
4829 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004830
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 // Load the special types.
4832 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4833 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4834 if (!Context.CFConstantStringTypeDecl)
4835 Context.setCFConstantStringType(GetType(String));
4836 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004837
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4839 QualType FileType = GetType(File);
4840 if (FileType.isNull()) {
4841 Error("FILE type is NULL");
4842 return;
4843 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004844
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004846 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 Context.setFILEDecl(Typedef->getDecl());
4848 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004849 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 if (!Tag) {
4851 Error("Invalid FILE type in AST file");
4852 return;
4853 }
4854 Context.setFILEDecl(Tag->getDecl());
4855 }
4856 }
4857 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004858
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4860 QualType Jmp_bufType = GetType(Jmp_buf);
4861 if (Jmp_bufType.isNull()) {
4862 Error("jmp_buf type is NULL");
4863 return;
4864 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004865
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004867 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 Context.setjmp_bufDecl(Typedef->getDecl());
4869 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004870 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 if (!Tag) {
4872 Error("Invalid jmp_buf type in AST file");
4873 return;
4874 }
4875 Context.setjmp_bufDecl(Tag->getDecl());
4876 }
4877 }
4878 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004879
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4881 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4882 if (Sigjmp_bufType.isNull()) {
4883 Error("sigjmp_buf type is NULL");
4884 return;
4885 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004886
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004888 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 Context.setsigjmp_bufDecl(Typedef->getDecl());
4890 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004891 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 assert(Tag && "Invalid sigjmp_buf type in AST file");
4893 Context.setsigjmp_bufDecl(Tag->getDecl());
4894 }
4895 }
4896 }
4897
4898 if (unsigned ObjCIdRedef
4899 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4900 if (Context.ObjCIdRedefinitionType.isNull())
4901 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4902 }
4903
4904 if (unsigned ObjCClassRedef
4905 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4906 if (Context.ObjCClassRedefinitionType.isNull())
4907 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4908 }
4909
4910 if (unsigned ObjCSelRedef
4911 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4912 if (Context.ObjCSelRedefinitionType.isNull())
4913 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4914 }
4915
4916 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4917 QualType Ucontext_tType = GetType(Ucontext_t);
4918 if (Ucontext_tType.isNull()) {
4919 Error("ucontext_t type is NULL");
4920 return;
4921 }
4922
4923 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004924 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 Context.setucontext_tDecl(Typedef->getDecl());
4926 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004927 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 assert(Tag && "Invalid ucontext_t type in AST file");
4929 Context.setucontext_tDecl(Tag->getDecl());
4930 }
4931 }
4932 }
4933 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004934
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4936
4937 // If there were any CUDA special declarations, deserialize them.
4938 if (!CUDASpecialDeclRefs.empty()) {
4939 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4940 Context.setcudaConfigureCallDecl(
4941 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4942 }
Richard Smith56be7542014-03-21 00:33:59 +00004943
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004945 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004946 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004947 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004948 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004949 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004950 if (Import.ImportLoc.isValid())
4951 PP.makeModuleVisible(Imported, Import.ImportLoc);
4952 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 }
4955 ImportedModules.clear();
4956}
4957
4958void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004959 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004960}
4961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004962/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004963/// else returns 0.
4964static ASTFileSignature readASTFileSignature(StringRef PCH) {
4965 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004966 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4967 // FIXME this drops the error on the floor.
4968 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004969 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004970 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004971
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004972 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4973 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004974 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004975
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004976 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004977 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004978 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004979 Expected<llvm::BitstreamEntry> MaybeEntry =
4980 Stream.advanceSkippingSubblocks();
4981 if (!MaybeEntry) {
4982 // FIXME this drops the error on the floor.
4983 consumeError(MaybeEntry.takeError());
4984 return ASTFileSignature();
4985 }
4986 llvm::BitstreamEntry Entry = MaybeEntry.get();
4987
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004988 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004989 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004990
4991 Record.clear();
4992 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004993 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4994 if (!MaybeRecord) {
4995 // FIXME this drops the error on the floor.
4996 consumeError(MaybeRecord.takeError());
4997 return ASTFileSignature();
4998 }
4999 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005000 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
5001 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00005002 }
5003}
5004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005005/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00005006/// directly from the AST file, without actually loading the AST
5007/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005008std::string ASTReader::getOriginalSourceFile(
5009 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005010 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00005012 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00005014 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5015 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00005016 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 }
5018
5019 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00005020 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00005021
5022 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005023 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5024 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005025 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005027
Chris Lattnere7b154b2013-01-19 21:39:22 +00005028 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005029 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005030 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005031 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005032 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005033
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005034 // Scan for ORIGINAL_FILE inside the control block.
5035 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005036 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005037 Expected<llvm::BitstreamEntry> MaybeEntry =
5038 Stream.advanceSkippingSubblocks();
5039 if (!MaybeEntry) {
5040 // FIXME this drops errors on the floor.
5041 consumeError(MaybeEntry.takeError());
5042 return std::string();
5043 }
5044 llvm::BitstreamEntry Entry = MaybeEntry.get();
5045
Chris Lattnere7b154b2013-01-19 21:39:22 +00005046 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005047 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005048
Chris Lattnere7b154b2013-01-19 21:39:22 +00005049 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5050 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005051 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005053
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005055 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005056 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5057 if (!MaybeRecord) {
5058 // FIXME this drops the errors on the floor.
5059 consumeError(MaybeRecord.takeError());
5060 return std::string();
5061 }
5062 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005063 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005065}
5066
5067namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005068
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 class SimplePCHValidator : public ASTReaderListener {
5070 const LangOptions &ExistingLangOpts;
5071 const TargetOptions &ExistingTargetOpts;
5072 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005073 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005075
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 public:
5077 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5078 const TargetOptions &ExistingTargetOpts,
5079 const PreprocessorOptions &ExistingPPOpts,
Benjamin Krameradcd0262020-01-28 20:23:46 +01005080 StringRef ExistingModuleCachePath, FileManager &FileMgr)
5081 : ExistingLangOpts(ExistingLangOpts),
5082 ExistingTargetOpts(ExistingTargetOpts),
5083 ExistingPPOpts(ExistingPPOpts),
5084 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005085
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005086 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5087 bool AllowCompatibleDifferences) override {
5088 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5089 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005091
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005092 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5093 bool AllowCompatibleDifferences) override {
5094 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5095 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005097
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005098 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5099 StringRef SpecificModuleCachePath,
5100 bool Complain) override {
5101 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5102 ExistingModuleCachePath,
5103 nullptr, ExistingLangOpts);
5104 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005105
Craig Topper3e89dfe2014-03-13 02:13:41 +00005106 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5107 bool Complain,
5108 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005109 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005110 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 }
5112 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005113
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005114} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005115
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005116bool ASTReader::readASTFileControlBlock(
5117 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005118 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005119 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005120 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005122 // FIXME: This allows use of the VFS; we do not allow use of the
5123 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005124 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 if (!Buffer) {
5126 return true;
5127 }
5128
5129 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005130 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5131 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005132
5133 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005134 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5135 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005138
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005139 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005140 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005141 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005142
5143 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005144 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005145 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005146 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005147
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005149 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005150 bool DoneWithControlBlock = false;
5151 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005152 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5153 if (!MaybeEntry) {
5154 // FIXME this drops the error on the floor.
5155 consumeError(MaybeEntry.takeError());
5156 return true;
5157 }
5158 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005159
5160 switch (Entry.Kind) {
5161 case llvm::BitstreamEntry::SubBlock: {
5162 switch (Entry.ID) {
5163 case OPTIONS_BLOCK_ID: {
5164 std::string IgnoredSuggestedPredefines;
5165 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5166 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005167 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005168 return true;
5169 break;
5170 }
5171
5172 case INPUT_FILES_BLOCK_ID:
5173 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005174 if (llvm::Error Err = Stream.SkipBlock()) {
5175 // FIXME this drops the error on the floor.
5176 consumeError(std::move(Err));
5177 return true;
5178 }
5179 if (NeedsInputFiles &&
5180 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005181 return true;
5182 break;
5183
5184 default:
JF Bastien0e828952019-06-26 19:50:12 +00005185 if (llvm::Error Err = Stream.SkipBlock()) {
5186 // FIXME this drops the error on the floor.
5187 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005188 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005189 }
Richard Smith0516b182015-09-08 19:40:14 +00005190 break;
5191 }
5192
5193 continue;
5194 }
5195
5196 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005197 DoneWithControlBlock = true;
5198 break;
Richard Smith0516b182015-09-08 19:40:14 +00005199
5200 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005201 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005202
5203 case llvm::BitstreamEntry::Record:
5204 break;
5205 }
5206
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005207 if (DoneWithControlBlock) break;
5208
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005210 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005211 Expected<unsigned> MaybeRecCode =
5212 Stream.readRecord(Entry.ID, Record, &Blob);
5213 if (!MaybeRecCode) {
5214 // FIXME this drops the error.
5215 return Failure;
5216 }
5217 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005218 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005219 if (Record[0] != VERSION_MAJOR)
5220 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005221 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005222 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005223 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005224 case MODULE_NAME:
5225 Listener.ReadModuleName(Blob);
5226 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005227 case MODULE_DIRECTORY:
Benjamin Krameradcd0262020-01-28 20:23:46 +01005228 ModuleDir = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005229 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005230 case MODULE_MAP_FILE: {
5231 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005232 auto Path = ReadString(Record, Idx);
5233 ResolveImportedPath(Path, ModuleDir);
5234 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005235 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005236 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005237 case INPUT_FILE_OFFSETS: {
5238 if (!NeedsInputFiles)
5239 break;
5240
5241 unsigned NumInputFiles = Record[0];
5242 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005243 const llvm::support::unaligned_uint64_t *InputFileOffs =
5244 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005245 for (unsigned I = 0; I != NumInputFiles; ++I) {
5246 // Go find this input file.
5247 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005248
5249 if (isSystemFile && !NeedsSystemInputFiles)
5250 break; // the rest are system input files
5251
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005252 BitstreamCursor &Cursor = InputFilesCursor;
5253 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005254 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5255 // FIXME this drops errors on the floor.
5256 consumeError(std::move(Err));
5257 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005258
JF Bastien0e828952019-06-26 19:50:12 +00005259 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5260 if (!MaybeCode) {
5261 // FIXME this drops errors on the floor.
5262 consumeError(MaybeCode.takeError());
5263 }
5264 unsigned Code = MaybeCode.get();
5265
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005266 RecordData Record;
5267 StringRef Blob;
5268 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005269 Expected<unsigned> MaybeRecordType =
5270 Cursor.readRecord(Code, Record, &Blob);
5271 if (!MaybeRecordType) {
5272 // FIXME this drops errors on the floor.
5273 consumeError(MaybeRecordType.takeError());
5274 }
5275 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005276 case INPUT_FILE_HASH:
5277 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005278 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005279 bool Overridden = static_cast<bool>(Record[3]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01005280 std::string Filename = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005281 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005282 shouldContinue = Listener.visitInputFile(
5283 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005284 break;
5285 }
5286 if (!shouldContinue)
5287 break;
5288 }
5289 break;
5290 }
5291
Richard Smithd4b230b2014-10-27 23:01:16 +00005292 case IMPORTS: {
5293 if (!NeedsImports)
5294 break;
5295
5296 unsigned Idx = 0, N = Record.size();
5297 while (Idx < N) {
5298 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005299 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5300 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005301 std::string Filename = ReadString(Record, Idx);
5302 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005303 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005304 }
5305 break;
5306 }
5307
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005308 default:
5309 // No other validation to perform.
5310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 }
5312 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005313
5314 // Look for module file extension blocks, if requested.
5315 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005316 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005317 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5318 bool DoneWithExtensionBlock = false;
5319 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005320 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5321 if (!MaybeEntry) {
5322 // FIXME this drops the error.
5323 return true;
5324 }
5325 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005326
JF Bastien0e828952019-06-26 19:50:12 +00005327 switch (Entry.Kind) {
5328 case llvm::BitstreamEntry::SubBlock:
5329 if (llvm::Error Err = Stream.SkipBlock()) {
5330 // FIXME this drops the error on the floor.
5331 consumeError(std::move(Err));
5332 return true;
5333 }
5334 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005335
JF Bastien0e828952019-06-26 19:50:12 +00005336 case llvm::BitstreamEntry::EndBlock:
5337 DoneWithExtensionBlock = true;
5338 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005339
JF Bastien0e828952019-06-26 19:50:12 +00005340 case llvm::BitstreamEntry::Error:
5341 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005342
JF Bastien0e828952019-06-26 19:50:12 +00005343 case llvm::BitstreamEntry::Record:
5344 break;
5345 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005346
5347 Record.clear();
5348 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005349 Expected<unsigned> MaybeRecCode =
5350 Stream.readRecord(Entry.ID, Record, &Blob);
5351 if (!MaybeRecCode) {
5352 // FIXME this drops the error.
5353 return true;
5354 }
5355 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005356 case EXTENSION_METADATA: {
5357 ModuleFileExtensionMetadata Metadata;
5358 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5359 return true;
5360
5361 Listener.readModuleFileExtension(Metadata);
5362 break;
5363 }
5364 }
5365 }
5366 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005367 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005368 }
5369
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005370 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5371 if (readUnhashedControlBlockImpl(
5372 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5373 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5374 ValidateDiagnosticOptions) != Success)
5375 return true;
5376
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005377 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005378}
5379
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005380bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5381 const PCHContainerReader &PCHContainerRdr,
5382 const LangOptions &LangOpts,
5383 const TargetOptions &TargetOpts,
5384 const PreprocessorOptions &PPOpts,
5385 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005386 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5387 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005388 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005389 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005390 validator,
5391 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005392}
5393
Ben Langmuir2c9af442014-04-10 17:57:43 +00005394ASTReader::ASTReadResult
5395ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005397 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5398 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005399 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 }
5401
5402 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5403 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005404 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 RecordData Record;
5406 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005407 Expected<llvm::BitstreamEntry> MaybeEntry =
5408 F.Stream.advanceSkippingSubblocks();
5409 if (!MaybeEntry) {
5410 Error(MaybeEntry.takeError());
5411 return Failure;
5412 }
5413 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005414
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005415 switch (Entry.Kind) {
5416 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5417 case llvm::BitstreamEntry::Error:
5418 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005419 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005420 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005421 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005422 case llvm::BitstreamEntry::Record:
5423 // The interesting case.
5424 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005426
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005428 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005430 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5431 if (!MaybeKind) {
5432 Error(MaybeKind.takeError());
5433 return Failure;
5434 }
5435 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005436
5437 if ((Kind == SUBMODULE_METADATA) != First) {
5438 Error("submodule metadata record should be at beginning of block");
5439 return Failure;
5440 }
5441 First = false;
5442
5443 // Submodule information is only valid if we have a current module.
5444 // FIXME: Should we error on these cases?
5445 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5446 Kind != SUBMODULE_DEFINITION)
5447 continue;
5448
5449 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 default: // Default behavior: ignore.
5451 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005452
Richard Smith03478d92014-10-23 22:12:14 +00005453 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005454 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005456 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 }
Richard Smith03478d92014-10-23 22:12:14 +00005458
Chris Lattner0e6c9402013-01-20 02:38:54 +00005459 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005460 unsigned Idx = 0;
5461 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5462 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005463 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005464 bool IsFramework = Record[Idx++];
5465 bool IsExplicit = Record[Idx++];
5466 bool IsSystem = Record[Idx++];
5467 bool IsExternC = Record[Idx++];
5468 bool InferSubmodules = Record[Idx++];
5469 bool InferExplicitSubmodules = Record[Idx++];
5470 bool InferExportWildcard = Record[Idx++];
5471 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005472 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005473
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005474 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005475 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005477
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 // Retrieve this (sub)module from the module map, creating it if
5479 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005480 CurrentModule =
5481 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5482 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005483
5484 // FIXME: set the definition loc for CurrentModule, or call
5485 // ModMap.setInferredModuleAllowedBy()
5486
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5488 if (GlobalIndex >= SubmodulesLoaded.size() ||
5489 SubmodulesLoaded[GlobalIndex]) {
5490 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005491 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005493
Douglas Gregor7029ce12013-03-19 00:28:20 +00005494 if (!ParentModule) {
5495 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005496 // Don't emit module relocation error if we have -fno-validate-pch
5497 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5498 CurFile != F.File) {
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08005499 Error(diag::err_module_file_conflict,
5500 CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5501 F.File->getName());
Ben Langmuir2c9af442014-04-10 17:57:43 +00005502 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005503 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005504 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005505
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08005506 F.DidReadTopLevelSubmodule = true;
Douglas Gregor7029ce12013-03-19 00:28:20 +00005507 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005508 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005509 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005510
Richard Smithdd8b5332017-09-04 05:37:53 +00005511 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005512 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 CurrentModule->IsFromModuleFile = true;
5514 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005515 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005516 CurrentModule->InferSubmodules = InferSubmodules;
5517 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5518 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005519 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005520 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005521 if (DeserializationListener)
5522 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005523
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005525
Richard Smith8a3e39a2016-03-28 21:31:09 +00005526 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005527 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005528 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005529 CurrentModule->UnresolvedConflicts.clear();
5530 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005531
5532 // The module is available unless it's missing a requirement; relevant
5533 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5534 // Missing headers that were present when the module was built do not
5535 // make it unavailable -- if we got this far, this must be an explicitly
5536 // imported module file.
5537 CurrentModule->Requirements.clear();
5538 CurrentModule->MissingHeaders.clear();
5539 CurrentModule->IsMissingRequirement =
5540 ParentModule && ParentModule->IsMissingRequirement;
5541 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 break;
5543 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005544
Guy Benyei11169dd2012-12-18 14:30:41 +00005545 case SUBMODULE_UMBRELLA_HEADER: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005546 std::string Filename = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005547 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005548 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005550 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5551 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005552 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5553 Error("mismatched umbrella headers in submodule");
5554 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 }
5556 }
5557 break;
5558 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005559
Richard Smith202210b2014-10-24 20:23:01 +00005560 case SUBMODULE_HEADER:
5561 case SUBMODULE_EXCLUDED_HEADER:
5562 case SUBMODULE_PRIVATE_HEADER:
5563 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005564 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5565 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005566 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005567
Richard Smith202210b2014-10-24 20:23:01 +00005568 case SUBMODULE_TEXTUAL_HEADER:
5569 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5570 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5571 // them here.
5572 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005573
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005574 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005575 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005577
5578 case SUBMODULE_UMBRELLA_DIR: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005579 std::string Dirname = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005580 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005581 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005583 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5584 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005585 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5586 Error("mismatched umbrella directories in submodule");
5587 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 }
5589 }
5590 break;
5591 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005592
Guy Benyei11169dd2012-12-18 14:30:41 +00005593 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005594 F.BaseSubmoduleID = getTotalNumSubmodules();
5595 F.LocalNumSubmodules = Record[0];
5596 unsigned LocalBaseSubmoduleID = Record[1];
5597 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005598 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 // module.
5600 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005601
5602 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005603 // module.
5604 F.SubmoduleRemap.insertOrReplace(
5605 std::make_pair(LocalBaseSubmoduleID,
5606 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005607
Ben Langmuir52ca6782014-10-20 16:27:32 +00005608 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5609 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 break;
5611 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005612
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005613 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005615 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 Unresolved.File = &F;
5617 Unresolved.Mod = CurrentModule;
5618 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005619 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005621 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 }
5623 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005624
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005625 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005627 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 Unresolved.File = &F;
5629 Unresolved.Mod = CurrentModule;
5630 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005631 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005632 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005633 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005634 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005635
5636 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 // the parsed, unresolved exports around.
5638 CurrentModule->UnresolvedExports.clear();
5639 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005640
5641 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005642 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5643 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005644 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005645
5646 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005647 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005648 CurrentModule->LinkLibraries.push_back(
Benjamin Krameradcd0262020-01-28 20:23:46 +01005649 Module::LinkLibrary(std::string(Blob), Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005650 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005651
5652 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005653 CurrentModule->ConfigMacros.push_back(Blob.str());
5654 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005655
5656 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005657 UnresolvedModuleRef Unresolved;
5658 Unresolved.File = &F;
5659 Unresolved.Mod = CurrentModule;
5660 Unresolved.ID = Record[0];
5661 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5662 Unresolved.IsWildcard = false;
5663 Unresolved.String = Blob;
5664 UnresolvedModuleRefs.push_back(Unresolved);
5665 break;
5666 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005667
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005668 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005669 if (!ContextObj)
5670 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005671 SmallVector<uint32_t, 16> Inits;
5672 for (auto &ID : Record)
5673 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005674 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005675 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005677
5678 case SUBMODULE_EXPORT_AS:
5679 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005680 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005681 break;
5682 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005683 }
5684}
5685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005686/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005687/// structure.
5688///
5689/// This routine parses the language options from the AST file and then gives
5690/// them to the AST listener if one is set.
5691///
5692/// \returns true if the listener deems the file unacceptable, false otherwise.
5693bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5694 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005695 ASTReaderListener &Listener,
5696 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005697 LangOptions LangOpts;
5698 unsigned Idx = 0;
5699#define LANGOPT(Name, Bits, Default, Description) \
5700 LangOpts.Name = Record[Idx++];
5701#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5702 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5703#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005704#define SANITIZER(NAME, ID) \
5705 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005706#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005707
Ben Langmuircd98cb72015-06-23 18:20:18 +00005708 for (unsigned N = Record[Idx++]; N; --N)
5709 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5710
Vedant Kumar48b4f762018-04-14 01:40:48 +00005711 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5713 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005714
Ben Langmuird4a667a2015-06-23 18:20:23 +00005715 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005716
5717 // Comment options.
5718 for (unsigned N = Record[Idx++]; N; --N) {
5719 LangOpts.CommentOpts.BlockCommandNames.push_back(
5720 ReadString(Record, Idx));
5721 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005722 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005723
Samuel Antaoee8fb302016-01-06 13:42:12 +00005724 // OpenMP offloading options.
5725 for (unsigned N = Record[Idx++]; N; --N) {
5726 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5727 }
5728
5729 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5730
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005731 return Listener.ReadLanguageOptions(LangOpts, Complain,
5732 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005733}
5734
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005735bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5736 ASTReaderListener &Listener,
5737 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 unsigned Idx = 0;
5739 TargetOptions TargetOpts;
5740 TargetOpts.Triple = ReadString(Record, Idx);
5741 TargetOpts.CPU = ReadString(Record, Idx);
5742 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 for (unsigned N = Record[Idx++]; N; --N) {
5744 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5745 }
5746 for (unsigned N = Record[Idx++]; N; --N) {
5747 TargetOpts.Features.push_back(ReadString(Record, Idx));
5748 }
5749
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005750 return Listener.ReadTargetOptions(TargetOpts, Complain,
5751 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005752}
5753
5754bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5755 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005756 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005757 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005758#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005759#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005760 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005761#include "clang/Basic/DiagnosticOptions.def"
5762
Richard Smith3be1cb22014-08-07 00:24:21 +00005763 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005764 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005765 for (unsigned N = Record[Idx++]; N; --N)
5766 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005767
5768 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5769}
5770
5771bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5772 ASTReaderListener &Listener) {
5773 FileSystemOptions FSOpts;
5774 unsigned Idx = 0;
5775 FSOpts.WorkingDir = ReadString(Record, Idx);
5776 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5777}
5778
5779bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5780 bool Complain,
5781 ASTReaderListener &Listener) {
5782 HeaderSearchOptions HSOpts;
5783 unsigned Idx = 0;
5784 HSOpts.Sysroot = ReadString(Record, Idx);
5785
5786 // Include entries.
5787 for (unsigned N = Record[Idx++]; N; --N) {
5788 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005789 frontend::IncludeDirGroup Group
5790 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 bool IsFramework = Record[Idx++];
5792 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005793 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5794 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 }
5796
5797 // System header prefixes.
5798 for (unsigned N = Record[Idx++]; N; --N) {
5799 std::string Prefix = ReadString(Record, Idx);
5800 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005801 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 }
5803
5804 HSOpts.ResourceDir = ReadString(Record, Idx);
5805 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005806 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005807 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005808 HSOpts.ImplicitModuleMaps = Record[Idx++];
5809 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005810 HSOpts.UseBuiltinIncludes = Record[Idx++];
5811 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5812 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5813 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005814 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005816 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5817 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818}
5819
5820bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5821 bool Complain,
5822 ASTReaderListener &Listener,
5823 std::string &SuggestedPredefines) {
5824 PreprocessorOptions PPOpts;
5825 unsigned Idx = 0;
5826
5827 // Macro definitions/undefs
5828 for (unsigned N = Record[Idx++]; N; --N) {
5829 std::string Macro = ReadString(Record, Idx);
5830 bool IsUndef = Record[Idx++];
5831 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5832 }
5833
5834 // Includes
5835 for (unsigned N = Record[Idx++]; N; --N) {
5836 PPOpts.Includes.push_back(ReadString(Record, Idx));
5837 }
5838
5839 // Macro Includes
5840 for (unsigned N = Record[Idx++]; N; --N) {
5841 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5842 }
5843
5844 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005845 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005847 PPOpts.ObjCXXARCStandardLibrary =
5848 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5849 SuggestedPredefines.clear();
5850 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5851 SuggestedPredefines);
5852}
5853
5854std::pair<ModuleFile *, unsigned>
5855ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5856 GlobalPreprocessedEntityMapType::iterator
5857 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005858 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005859 "Corrupted global preprocessed entity map");
5860 ModuleFile *M = I->second;
5861 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5862 return std::make_pair(M, LocalIndex);
5863}
5864
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005865llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005866ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5867 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5868 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5869 Mod.NumPreprocessedEntities);
5870
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005871 return llvm::make_range(PreprocessingRecord::iterator(),
5872 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005873}
5874
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005875llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005876ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005877 return llvm::make_range(
5878 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5879 ModuleDeclIterator(this, &Mod,
5880 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005881}
5882
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005883SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5884 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5885 assert(I != GlobalSkippedRangeMap.end() &&
5886 "Corrupted global skipped range map");
5887 ModuleFile *M = I->second;
5888 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5889 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5890 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5891 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5892 TranslateSourceLocation(*M, RawRange.getEnd()));
5893 assert(Range.isValid());
5894 return Range;
5895}
5896
Guy Benyei11169dd2012-12-18 14:30:41 +00005897PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5898 PreprocessedEntityID PPID = Index+1;
5899 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5900 ModuleFile &M = *PPInfo.first;
5901 unsigned LocalIndex = PPInfo.second;
5902 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5903
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 if (!PP.getPreprocessingRecord()) {
5905 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005906 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005908
5909 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005910 if (llvm::Error Err =
5911 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5912 Error(std::move(Err));
5913 return nullptr;
5914 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005915
JF Bastien0e828952019-06-26 19:50:12 +00005916 Expected<llvm::BitstreamEntry> MaybeEntry =
5917 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5918 if (!MaybeEntry) {
5919 Error(MaybeEntry.takeError());
5920 return nullptr;
5921 }
5922 llvm::BitstreamEntry Entry = MaybeEntry.get();
5923
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005924 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005925 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005926
Guy Benyei11169dd2012-12-18 14:30:41 +00005927 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005928 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5929 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005930 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005931 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005933 Expected<unsigned> MaybeRecType =
5934 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5935 if (!MaybeRecType) {
5936 Error(MaybeRecType.takeError());
5937 return nullptr;
5938 }
5939 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005940 case PPD_MACRO_EXPANSION: {
5941 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005942 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005943 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 if (isBuiltin)
5945 Name = getLocalIdentifier(M, Record[1]);
5946 else {
Richard Smith66a81862015-05-04 02:25:31 +00005947 PreprocessedEntityID GlobalID =
5948 getGlobalPreprocessedEntityID(M, Record[1]);
5949 Def = cast<MacroDefinitionRecord>(
5950 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 }
5952
5953 MacroExpansion *ME;
5954 if (isBuiltin)
5955 ME = new (PPRec) MacroExpansion(Name, Range);
5956 else
5957 ME = new (PPRec) MacroExpansion(Def, Range);
5958
5959 return ME;
5960 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005961
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 case PPD_MACRO_DEFINITION: {
5963 // Decode the identifier info and then check again; if the macro is
5964 // still defined and associated with the identifier,
5965 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005966 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005967
5968 if (DeserializationListener)
5969 DeserializationListener->MacroDefinitionRead(PPID, MD);
5970
5971 return MD;
5972 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005973
Guy Benyei11169dd2012-12-18 14:30:41 +00005974 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005975 const char *FullFileNameStart = Blob.data() + Record[0];
5976 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005977 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005979 if (auto FE = PP.getFileManager().getFile(FullFileName))
5980 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005981
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005983 InclusionDirective::InclusionKind Kind
5984 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5985 InclusionDirective *ID
5986 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005987 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 Record[1], Record[3],
5989 File,
5990 Range);
5991 return ID;
5992 }
5993 }
5994
5995 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5996}
5997
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005998/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005999/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00006000///
6001/// \param SLocMapI points at a chunk of a module that contains no
6002/// preprocessed entities or the entities it contains are not the ones we are
6003/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00006004PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6005 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6006 ++SLocMapI;
6007 for (GlobalSLocOffsetMapType::const_iterator
6008 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6009 ModuleFile &M = *SLocMapI->second;
6010 if (M.NumPreprocessedEntities)
6011 return M.BasePreprocessedEntityID;
6012 }
6013
6014 return getTotalNumPreprocessedEntities();
6015}
6016
6017namespace {
6018
Guy Benyei11169dd2012-12-18 14:30:41 +00006019struct PPEntityComp {
6020 const ASTReader &Reader;
6021 ModuleFile &M;
6022
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006023 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006024
6025 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6026 SourceLocation LHS = getLoc(L);
6027 SourceLocation RHS = getLoc(R);
6028 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6029 }
6030
6031 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6032 SourceLocation LHS = getLoc(L);
6033 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6034 }
6035
6036 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6037 SourceLocation RHS = getLoc(R);
6038 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6039 }
6040
6041 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006042 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006043 }
6044};
6045
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006046} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006047
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006048PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6049 bool EndsAfter) const {
6050 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 return getTotalNumPreprocessedEntities();
6052
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006053 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6054 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6056 "Corrupted global sloc offset map");
6057
6058 if (SLocMapI->second->NumPreprocessedEntities == 0)
6059 return findNextPreprocessedEntity(SLocMapI);
6060
6061 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006062
6063 using pp_iterator = const PPEntityOffset *;
6064
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6066 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6067
6068 size_t Count = M.NumPreprocessedEntities;
6069 size_t Half;
6070 pp_iterator First = pp_begin;
6071 pp_iterator PPI;
6072
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006073 if (EndsAfter) {
6074 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006075 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006076 } else {
6077 // Do a binary search manually instead of using std::lower_bound because
6078 // The end locations of entities may be unordered (when a macro expansion
6079 // is inside another macro argument), but for this case it is not important
6080 // whether we get the first macro expansion or its containing macro.
6081 while (Count > 0) {
6082 Half = Count / 2;
6083 PPI = First;
6084 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006085 if (SourceMgr.isBeforeInTranslationUnit(
6086 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006087 First = PPI;
6088 ++First;
6089 Count = Count - Half - 1;
6090 } else
6091 Count = Half;
6092 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 }
6094
6095 if (PPI == pp_end)
6096 return findNextPreprocessedEntity(SLocMapI);
6097
6098 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6099}
6100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006101/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006102/// preprocessed entities that \arg Range encompasses.
6103std::pair<unsigned, unsigned>
6104 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6105 if (Range.isInvalid())
6106 return std::make_pair(0,0);
6107 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6108
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006109 PreprocessedEntityID BeginID =
6110 findPreprocessedEntity(Range.getBegin(), false);
6111 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 return std::make_pair(BeginID, EndID);
6113}
6114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006115/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006116/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006117Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 FileID FID) {
6119 if (FID.isInvalid())
6120 return false;
6121
6122 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6123 ModuleFile &M = *PPInfo.first;
6124 unsigned LocalIndex = PPInfo.second;
6125 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006126
Richard Smithcb34bd32016-03-27 07:28:06 +00006127 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 if (Loc.isInvalid())
6129 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006130
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6132 return true;
6133 else
6134 return false;
6135}
6136
6137namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006138
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006139 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006142 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006145 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006146
6147 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006148 HeaderFileInfoLookupTable *Table
6149 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 if (!Table)
6151 return false;
6152
6153 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006154 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 if (Pos == Table->end())
6156 return false;
6157
Richard Smithbdf2d932015-07-30 03:37:16 +00006158 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 return true;
6160 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006161
David Blaikie05785d12013-02-20 22:23:23 +00006162 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006164
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006165} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006166
6167HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006168 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006169 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006170 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006172
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 return HeaderFileInfo();
6174}
6175
6176void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006177 using DiagState = DiagnosticsEngine::DiagState;
6178 SmallVector<DiagState *, 32> DiagStates;
6179
Vedant Kumar48b4f762018-04-14 01:40:48 +00006180 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006182 auto &Record = F.PragmaDiagMappings;
6183 if (Record.empty())
6184 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006185
Richard Smithd230de22017-01-26 01:01:01 +00006186 DiagStates.clear();
6187
6188 auto ReadDiagState =
6189 [&](const DiagState &BasedOn, SourceLocation Loc,
6190 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6191 unsigned BackrefID = Record[Idx++];
6192 if (BackrefID != 0)
6193 return DiagStates[BackrefID - 1];
6194
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006196 Diag.DiagStates.push_back(BasedOn);
6197 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006199 unsigned Size = Record[Idx++];
6200 assert(Idx + Size * 2 <= Record.size() &&
6201 "Invalid data, not enough diag/map pairs");
6202 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006203 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006204 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006205 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006206 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6207 continue;
6208
6209 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6210
6211 // If this mapping was specified as a warning but the severity was
6212 // upgraded due to diagnostic settings, simulate the current diagnostic
6213 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006214 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6215 NewMapping.setSeverity(diag::Severity::Warning);
6216 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006217 }
6218
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006219 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006220 }
Richard Smithd230de22017-01-26 01:01:01 +00006221 return NewState;
6222 };
6223
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006224 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006225 DiagState *FirstState;
6226 if (F.Kind == MK_ImplicitModule) {
6227 // Implicitly-built modules are reused with different diagnostic
6228 // settings. Use the initial diagnostic state from Diag to simulate this
6229 // compilation's diagnostic settings.
6230 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6231 DiagStates.push_back(FirstState);
6232
6233 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006234 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006235 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006236 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006237 assert(Idx < Record.size() &&
6238 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006239 } else if (F.isModule()) {
6240 // For an explicit module, preserve the flags from the module build
6241 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6242 // -Wblah flags.
6243 unsigned Flags = Record[Idx++];
6244 DiagState Initial;
6245 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6246 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6247 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6248 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6249 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6250 Initial.ExtBehavior = (diag::Severity)Flags;
6251 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006252
Richard Smith6c2b5a82018-02-09 01:15:13 +00006253 assert(F.OriginalSourceFileID.isValid());
6254
Richard Smithe37391c2017-05-03 00:28:49 +00006255 // Set up the root buffer of the module to start with the initial
6256 // diagnostic state of the module itself, to cover files that contain no
6257 // explicit transitions (for which we did not serialize anything).
6258 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6259 .StateTransitions.push_back({FirstState, 0});
6260 } else {
6261 // For prefix ASTs, start with whatever the user configured on the
6262 // command line.
6263 Idx++; // Skip flags.
6264 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6265 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006266 }
Richard Smithd230de22017-01-26 01:01:01 +00006267
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006268 // Read the state transitions.
6269 unsigned NumLocations = Record[Idx++];
6270 while (NumLocations--) {
6271 assert(Idx < Record.size() &&
6272 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006273 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6274 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006275 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006276 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6277 unsigned Transitions = Record[Idx++];
6278
6279 // Note that we don't need to set up Parent/ParentOffset here, because
6280 // we won't be changing the diagnostic state within imported FileIDs
6281 // (other than perhaps appending to the main source file, which has no
6282 // parent).
6283 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6284 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6285 for (unsigned I = 0; I != Transitions; ++I) {
6286 unsigned Offset = Record[Idx++];
6287 auto *State =
6288 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6289 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 }
6291 }
Richard Smithd230de22017-01-26 01:01:01 +00006292
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006293 // Read the final state.
6294 assert(Idx < Record.size() &&
6295 "Invalid data, missing final pragma diagnostic state");
6296 SourceLocation CurStateLoc =
6297 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6298 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6299
6300 if (!F.isModule()) {
6301 Diag.DiagStatesByLoc.CurDiagState = CurState;
6302 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6303
6304 // Preserve the property that the imaginary root file describes the
6305 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006306 FileID NullFile;
6307 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006308 if (T.empty())
6309 T.push_back({CurState, 0});
6310 else
6311 T[0].State = CurState;
6312 }
6313
Richard Smithd230de22017-01-26 01:01:01 +00006314 // Don't try to read these mappings again.
6315 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 }
6317}
6318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006319/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006320ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6321 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6322 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6323 ModuleFile *M = I->second;
6324 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6325}
6326
John McCalld505e572019-12-13 21:54:44 -05006327static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6328 switch (code) {
6329#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6330 case TYPE_##CODE_ID: return Type::CLASS_ID;
6331#include "clang/Serialization/TypeBitCodes.def"
6332 default: return llvm::None;
6333 }
John McCall3ce3d232019-12-13 03:37:23 -05006334}
6335
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006336/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006337///
6338/// The index is the type ID, shifted and minus the number of predefs. This
6339/// routine actually reads the record corresponding to the type at the given
6340/// location. It is a helper routine for GetType, which deals with reading type
6341/// IDs.
6342QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006343 assert(ContextObj && "reading type with no AST context");
6344 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006346 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006347
6348 // Keep track of where we are in the stream, then jump back there
6349 // after reading this type.
6350 SavedStreamPosition SavedPosition(DeclsCursor);
6351
6352 ReadingKindTracker ReadingKind(Read_Type, *this);
6353
6354 // Note that we are loading a type record.
6355 Deserializing AType(this);
6356
JF Bastien0e828952019-06-26 19:50:12 +00006357 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6358 Error(std::move(Err));
6359 return QualType();
6360 }
John McCall3ce3d232019-12-13 03:37:23 -05006361 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6362 if (!RawCode) {
6363 Error(RawCode.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006364 return QualType();
6365 }
JF Bastien0e828952019-06-26 19:50:12 +00006366
John McCall3ce3d232019-12-13 03:37:23 -05006367 ASTRecordReader Record(*this, *Loc.F);
6368 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6369 if (!Code) {
6370 Error(Code.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006371 return QualType();
6372 }
John McCalld505e572019-12-13 21:54:44 -05006373 if (Code.get() == TYPE_EXT_QUAL) {
6374 QualType baseType = Record.readQualType();
6375 Qualifiers quals = Record.readQualifiers();
6376 return Context.getQualifiedType(baseType, quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 }
6378
John McCalld505e572019-12-13 21:54:44 -05006379 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6380 if (!maybeClass) {
6381 Error("Unexpected code for type");
6382 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 }
6384
John McCalld505e572019-12-13 21:54:44 -05006385 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6386 return TypeReader.read(*maybeClass);
Richard Smith564417a2014-03-20 21:47:22 +00006387}
6388
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006389namespace clang {
6390
6391class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
John McCall3ce3d232019-12-13 03:37:23 -05006392 ASTRecordReader &Reader;
Guy Benyei11169dd2012-12-18 14:30:41 +00006393
John McCall3ce3d232019-12-13 03:37:23 -05006394 SourceLocation readSourceLocation() {
6395 return Reader.readSourceLocation();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006396 }
6397
6398 TypeSourceInfo *GetTypeSourceInfo() {
John McCall3ce3d232019-12-13 03:37:23 -05006399 return Reader.readTypeSourceInfo();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006400 }
6401
6402 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
John McCall3ce3d232019-12-13 03:37:23 -05006403 return Reader.readNestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 }
6405
Richard Smithe43e2b32018-08-20 21:47:29 +00006406 Attr *ReadAttr() {
John McCall3ce3d232019-12-13 03:37:23 -05006407 return Reader.readAttr();
Richard Smithe43e2b32018-08-20 21:47:29 +00006408 }
6409
Guy Benyei11169dd2012-12-18 14:30:41 +00006410public:
John McCall3ce3d232019-12-13 03:37:23 -05006411 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006412
6413 // We want compile-time assurance that we've enumerated all of
6414 // these, so unfortunately we have to declare them first, then
6415 // define them out-of-line.
6416#define ABSTRACT_TYPELOC(CLASS, PARENT)
6417#define TYPELOC(CLASS, PARENT) \
6418 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6419#include "clang/AST/TypeLocNodes.def"
6420
6421 void VisitFunctionTypeLoc(FunctionTypeLoc);
6422 void VisitArrayTypeLoc(ArrayTypeLoc);
6423};
6424
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006425} // namespace clang
6426
Guy Benyei11169dd2012-12-18 14:30:41 +00006427void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6428 // nothing to do
6429}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006430
Guy Benyei11169dd2012-12-18 14:30:41 +00006431void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006432 TL.setBuiltinLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 if (TL.needsExtraLocalData()) {
John McCall3ce3d232019-12-13 03:37:23 -05006434 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6435 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6436 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6437 TL.setModeAttr(Reader.readInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 }
6439}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006440
Guy Benyei11169dd2012-12-18 14:30:41 +00006441void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006442 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006443}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006446 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006447}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006448
Reid Kleckner8a365022013-06-24 17:51:48 +00006449void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6450 // nothing to do
6451}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006452
Reid Kleckner0503a872013-12-05 01:23:43 +00006453void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6454 // nothing to do
6455}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006456
Leonard Chanc72aaf62019-05-07 03:20:17 +00006457void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006458 TL.setExpansionLoc(readSourceLocation());
Leonard Chanc72aaf62019-05-07 03:20:17 +00006459}
6460
Guy Benyei11169dd2012-12-18 14:30:41 +00006461void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006462 TL.setCaretLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006463}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006464
Guy Benyei11169dd2012-12-18 14:30:41 +00006465void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006466 TL.setAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006467}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006468
Guy Benyei11169dd2012-12-18 14:30:41 +00006469void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006470 TL.setAmpAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006471}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006472
Guy Benyei11169dd2012-12-18 14:30:41 +00006473void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006474 TL.setStarLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006475 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006476}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006477
Guy Benyei11169dd2012-12-18 14:30:41 +00006478void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006479 TL.setLBracketLoc(readSourceLocation());
6480 TL.setRBracketLoc(readSourceLocation());
6481 if (Reader.readBool())
6482 TL.setSizeExpr(Reader.readExpr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 else
Craig Toppera13603a2014-05-22 05:54:18 +00006484 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006485}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006486
Guy Benyei11169dd2012-12-18 14:30:41 +00006487void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6488 VisitArrayTypeLoc(TL);
6489}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006490
Guy Benyei11169dd2012-12-18 14:30:41 +00006491void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6492 VisitArrayTypeLoc(TL);
6493}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006494
Guy Benyei11169dd2012-12-18 14:30:41 +00006495void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6496 VisitArrayTypeLoc(TL);
6497}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006498
Guy Benyei11169dd2012-12-18 14:30:41 +00006499void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6500 DependentSizedArrayTypeLoc TL) {
6501 VisitArrayTypeLoc(TL);
6502}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006503
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006504void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6505 DependentAddressSpaceTypeLoc TL) {
6506
John McCall3ce3d232019-12-13 03:37:23 -05006507 TL.setAttrNameLoc(readSourceLocation());
6508 TL.setAttrOperandParensRange(Reader.readSourceRange());
6509 TL.setAttrExprOperand(Reader.readExpr());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006510}
6511
Guy Benyei11169dd2012-12-18 14:30:41 +00006512void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6513 DependentSizedExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006514 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006515}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006516
Guy Benyei11169dd2012-12-18 14:30:41 +00006517void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006518 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006519}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006520
Erich Keanef702b022018-07-13 19:46:04 +00006521void TypeLocReader::VisitDependentVectorTypeLoc(
6522 DependentVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006523 TL.setNameLoc(readSourceLocation());
Erich Keanef702b022018-07-13 19:46:04 +00006524}
6525
Guy Benyei11169dd2012-12-18 14:30:41 +00006526void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006527 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006528}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006529
Guy Benyei11169dd2012-12-18 14:30:41 +00006530void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006531 TL.setLocalRangeBegin(readSourceLocation());
6532 TL.setLParenLoc(readSourceLocation());
6533 TL.setRParenLoc(readSourceLocation());
6534 TL.setExceptionSpecRange(Reader.readSourceRange());
6535 TL.setLocalRangeEnd(readSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006536 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
John McCall3ce3d232019-12-13 03:37:23 -05006537 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 }
6539}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006540
Guy Benyei11169dd2012-12-18 14:30:41 +00006541void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6542 VisitFunctionTypeLoc(TL);
6543}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006544
Guy Benyei11169dd2012-12-18 14:30:41 +00006545void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6546 VisitFunctionTypeLoc(TL);
6547}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006548
Guy Benyei11169dd2012-12-18 14:30:41 +00006549void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006550 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006551}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006552
Guy Benyei11169dd2012-12-18 14:30:41 +00006553void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006554 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006558 TL.setTypeofLoc(readSourceLocation());
6559 TL.setLParenLoc(readSourceLocation());
6560 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006561}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006562
Guy Benyei11169dd2012-12-18 14:30:41 +00006563void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006564 TL.setTypeofLoc(readSourceLocation());
6565 TL.setLParenLoc(readSourceLocation());
6566 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006567 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006568}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006569
Guy Benyei11169dd2012-12-18 14:30:41 +00006570void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006571 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006572}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006573
Guy Benyei11169dd2012-12-18 14:30:41 +00006574void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006575 TL.setKWLoc(readSourceLocation());
6576 TL.setLParenLoc(readSourceLocation());
6577 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006578 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006579}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006580
Guy Benyei11169dd2012-12-18 14:30:41 +00006581void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006582 TL.setNameLoc(readSourceLocation());
Saar Razb481f022020-01-22 02:03:05 +02006583 if (Reader.readBool()) {
6584 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6585 TL.setTemplateKWLoc(readSourceLocation());
6586 TL.setConceptNameLoc(readSourceLocation());
6587 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6588 TL.setLAngleLoc(readSourceLocation());
6589 TL.setRAngleLoc(readSourceLocation());
6590 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6591 TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6592 TL.getTypePtr()->getArg(i).getKind()));
6593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006594}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006595
Richard Smith600b5262017-01-26 20:40:47 +00006596void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6597 DeducedTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006598 TL.setTemplateNameLoc(readSourceLocation());
Richard Smith600b5262017-01-26 20:40:47 +00006599}
6600
Guy Benyei11169dd2012-12-18 14:30:41 +00006601void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006602 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006603}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006604
Guy Benyei11169dd2012-12-18 14:30:41 +00006605void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006606 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006607}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006608
Guy Benyei11169dd2012-12-18 14:30:41 +00006609void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006610 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006611}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006612
Guy Benyei11169dd2012-12-18 14:30:41 +00006613void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006614 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006615}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6618 SubstTemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006619 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006620}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006621
Guy Benyei11169dd2012-12-18 14:30:41 +00006622void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6623 SubstTemplateTypeParmPackTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006624 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006625}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006626
Guy Benyei11169dd2012-12-18 14:30:41 +00006627void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6628 TemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006629 TL.setTemplateKeywordLoc(readSourceLocation());
6630 TL.setTemplateNameLoc(readSourceLocation());
6631 TL.setLAngleLoc(readSourceLocation());
6632 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006634 TL.setArgLocInfo(
6635 i,
John McCall3ce3d232019-12-13 03:37:23 -05006636 Reader.readTemplateArgumentLocInfo(
6637 TL.getTypePtr()->getArg(i).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006638}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006639
Guy Benyei11169dd2012-12-18 14:30:41 +00006640void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006641 TL.setLParenLoc(readSourceLocation());
6642 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006644
Guy Benyei11169dd2012-12-18 14:30:41 +00006645void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006646 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006647 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006648}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006649
Guy Benyei11169dd2012-12-18 14:30:41 +00006650void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006651 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006652}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006653
Guy Benyei11169dd2012-12-18 14:30:41 +00006654void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006655 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006656 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006657 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006658}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006659
Guy Benyei11169dd2012-12-18 14:30:41 +00006660void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6661 DependentTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006662 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006663 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006664 TL.setTemplateKeywordLoc(readSourceLocation());
6665 TL.setTemplateNameLoc(readSourceLocation());
6666 TL.setLAngleLoc(readSourceLocation());
6667 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006669 TL.setArgLocInfo(
6670 I,
John McCall3ce3d232019-12-13 03:37:23 -05006671 Reader.readTemplateArgumentLocInfo(
6672 TL.getTypePtr()->getArg(I).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006673}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006674
Guy Benyei11169dd2012-12-18 14:30:41 +00006675void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006676 TL.setEllipsisLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006677}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006678
Guy Benyei11169dd2012-12-18 14:30:41 +00006679void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006680 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006681}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006682
Manman Rene6be26c2016-09-13 17:25:08 +00006683void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6684 if (TL.getNumProtocols()) {
John McCall3ce3d232019-12-13 03:37:23 -05006685 TL.setProtocolLAngleLoc(readSourceLocation());
6686 TL.setProtocolRAngleLoc(readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006687 }
6688 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006689 TL.setProtocolLoc(i, readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006690}
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006693 TL.setHasBaseTypeAsWritten(Reader.readBool());
6694 TL.setTypeArgsLAngleLoc(readSourceLocation());
6695 TL.setTypeArgsRAngleLoc(readSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006696 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006697 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
John McCall3ce3d232019-12-13 03:37:23 -05006698 TL.setProtocolLAngleLoc(readSourceLocation());
6699 TL.setProtocolRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006701 TL.setProtocolLoc(i, readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006702}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006703
Guy Benyei11169dd2012-12-18 14:30:41 +00006704void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006705 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006706}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006709 TL.setKWLoc(readSourceLocation());
6710 TL.setLParenLoc(readSourceLocation());
6711 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006712}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006713
Xiuli Pan9c14e282016-01-09 12:53:17 +00006714void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006715 TL.setKWLoc(readSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006716}
Guy Benyei11169dd2012-12-18 14:30:41 +00006717
John McCall3ce3d232019-12-13 03:37:23 -05006718void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6719 TypeLocReader TLR(*this);
Richard Smithc23d7342018-06-29 20:46:25 +00006720 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6721 TLR.Visit(TL);
6722}
6723
John McCall3ce3d232019-12-13 03:37:23 -05006724TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6725 QualType InfoTy = readType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006727 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006728
6729 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
John McCall3ce3d232019-12-13 03:37:23 -05006730 readTypeLoc(TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 return TInfo;
6732}
6733
6734QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006735 assert(ContextObj && "reading type with no AST context");
6736 ASTContext &Context = *ContextObj;
6737
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 unsigned FastQuals = ID & Qualifiers::FastMask;
6739 unsigned Index = ID >> Qualifiers::FastWidth;
6740
6741 if (Index < NUM_PREDEF_TYPE_IDS) {
6742 QualType T;
6743 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006744 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006745 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006746 case PREDEF_TYPE_VOID_ID:
6747 T = Context.VoidTy;
6748 break;
6749 case PREDEF_TYPE_BOOL_ID:
6750 T = Context.BoolTy;
6751 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 case PREDEF_TYPE_CHAR_U_ID:
6753 case PREDEF_TYPE_CHAR_S_ID:
6754 // FIXME: Check that the signedness of CharTy is correct!
6755 T = Context.CharTy;
6756 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006757 case PREDEF_TYPE_UCHAR_ID:
6758 T = Context.UnsignedCharTy;
6759 break;
6760 case PREDEF_TYPE_USHORT_ID:
6761 T = Context.UnsignedShortTy;
6762 break;
6763 case PREDEF_TYPE_UINT_ID:
6764 T = Context.UnsignedIntTy;
6765 break;
6766 case PREDEF_TYPE_ULONG_ID:
6767 T = Context.UnsignedLongTy;
6768 break;
6769 case PREDEF_TYPE_ULONGLONG_ID:
6770 T = Context.UnsignedLongLongTy;
6771 break;
6772 case PREDEF_TYPE_UINT128_ID:
6773 T = Context.UnsignedInt128Ty;
6774 break;
6775 case PREDEF_TYPE_SCHAR_ID:
6776 T = Context.SignedCharTy;
6777 break;
6778 case PREDEF_TYPE_WCHAR_ID:
6779 T = Context.WCharTy;
6780 break;
6781 case PREDEF_TYPE_SHORT_ID:
6782 T = Context.ShortTy;
6783 break;
6784 case PREDEF_TYPE_INT_ID:
6785 T = Context.IntTy;
6786 break;
6787 case PREDEF_TYPE_LONG_ID:
6788 T = Context.LongTy;
6789 break;
6790 case PREDEF_TYPE_LONGLONG_ID:
6791 T = Context.LongLongTy;
6792 break;
6793 case PREDEF_TYPE_INT128_ID:
6794 T = Context.Int128Ty;
6795 break;
6796 case PREDEF_TYPE_HALF_ID:
6797 T = Context.HalfTy;
6798 break;
6799 case PREDEF_TYPE_FLOAT_ID:
6800 T = Context.FloatTy;
6801 break;
6802 case PREDEF_TYPE_DOUBLE_ID:
6803 T = Context.DoubleTy;
6804 break;
6805 case PREDEF_TYPE_LONGDOUBLE_ID:
6806 T = Context.LongDoubleTy;
6807 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006808 case PREDEF_TYPE_SHORT_ACCUM_ID:
6809 T = Context.ShortAccumTy;
6810 break;
6811 case PREDEF_TYPE_ACCUM_ID:
6812 T = Context.AccumTy;
6813 break;
6814 case PREDEF_TYPE_LONG_ACCUM_ID:
6815 T = Context.LongAccumTy;
6816 break;
6817 case PREDEF_TYPE_USHORT_ACCUM_ID:
6818 T = Context.UnsignedShortAccumTy;
6819 break;
6820 case PREDEF_TYPE_UACCUM_ID:
6821 T = Context.UnsignedAccumTy;
6822 break;
6823 case PREDEF_TYPE_ULONG_ACCUM_ID:
6824 T = Context.UnsignedLongAccumTy;
6825 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006826 case PREDEF_TYPE_SHORT_FRACT_ID:
6827 T = Context.ShortFractTy;
6828 break;
6829 case PREDEF_TYPE_FRACT_ID:
6830 T = Context.FractTy;
6831 break;
6832 case PREDEF_TYPE_LONG_FRACT_ID:
6833 T = Context.LongFractTy;
6834 break;
6835 case PREDEF_TYPE_USHORT_FRACT_ID:
6836 T = Context.UnsignedShortFractTy;
6837 break;
6838 case PREDEF_TYPE_UFRACT_ID:
6839 T = Context.UnsignedFractTy;
6840 break;
6841 case PREDEF_TYPE_ULONG_FRACT_ID:
6842 T = Context.UnsignedLongFractTy;
6843 break;
6844 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6845 T = Context.SatShortAccumTy;
6846 break;
6847 case PREDEF_TYPE_SAT_ACCUM_ID:
6848 T = Context.SatAccumTy;
6849 break;
6850 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6851 T = Context.SatLongAccumTy;
6852 break;
6853 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6854 T = Context.SatUnsignedShortAccumTy;
6855 break;
6856 case PREDEF_TYPE_SAT_UACCUM_ID:
6857 T = Context.SatUnsignedAccumTy;
6858 break;
6859 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6860 T = Context.SatUnsignedLongAccumTy;
6861 break;
6862 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6863 T = Context.SatShortFractTy;
6864 break;
6865 case PREDEF_TYPE_SAT_FRACT_ID:
6866 T = Context.SatFractTy;
6867 break;
6868 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6869 T = Context.SatLongFractTy;
6870 break;
6871 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6872 T = Context.SatUnsignedShortFractTy;
6873 break;
6874 case PREDEF_TYPE_SAT_UFRACT_ID:
6875 T = Context.SatUnsignedFractTy;
6876 break;
6877 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6878 T = Context.SatUnsignedLongFractTy;
6879 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006880 case PREDEF_TYPE_FLOAT16_ID:
6881 T = Context.Float16Ty;
6882 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006883 case PREDEF_TYPE_FLOAT128_ID:
6884 T = Context.Float128Ty;
6885 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006886 case PREDEF_TYPE_OVERLOAD_ID:
6887 T = Context.OverloadTy;
6888 break;
6889 case PREDEF_TYPE_BOUND_MEMBER:
6890 T = Context.BoundMemberTy;
6891 break;
6892 case PREDEF_TYPE_PSEUDO_OBJECT:
6893 T = Context.PseudoObjectTy;
6894 break;
6895 case PREDEF_TYPE_DEPENDENT_ID:
6896 T = Context.DependentTy;
6897 break;
6898 case PREDEF_TYPE_UNKNOWN_ANY:
6899 T = Context.UnknownAnyTy;
6900 break;
6901 case PREDEF_TYPE_NULLPTR_ID:
6902 T = Context.NullPtrTy;
6903 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006904 case PREDEF_TYPE_CHAR8_ID:
6905 T = Context.Char8Ty;
6906 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006907 case PREDEF_TYPE_CHAR16_ID:
6908 T = Context.Char16Ty;
6909 break;
6910 case PREDEF_TYPE_CHAR32_ID:
6911 T = Context.Char32Ty;
6912 break;
6913 case PREDEF_TYPE_OBJC_ID:
6914 T = Context.ObjCBuiltinIdTy;
6915 break;
6916 case PREDEF_TYPE_OBJC_CLASS:
6917 T = Context.ObjCBuiltinClassTy;
6918 break;
6919 case PREDEF_TYPE_OBJC_SEL:
6920 T = Context.ObjCBuiltinSelTy;
6921 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006922#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6923 case PREDEF_TYPE_##Id##_ID: \
6924 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006925 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006926#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006927#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6928 case PREDEF_TYPE_##Id##_ID: \
6929 T = Context.Id##Ty; \
6930 break;
6931#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006932 case PREDEF_TYPE_SAMPLER_ID:
6933 T = Context.OCLSamplerTy;
6934 break;
6935 case PREDEF_TYPE_EVENT_ID:
6936 T = Context.OCLEventTy;
6937 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006938 case PREDEF_TYPE_CLK_EVENT_ID:
6939 T = Context.OCLClkEventTy;
6940 break;
6941 case PREDEF_TYPE_QUEUE_ID:
6942 T = Context.OCLQueueTy;
6943 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006944 case PREDEF_TYPE_RESERVE_ID_ID:
6945 T = Context.OCLReserveIDTy;
6946 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006947 case PREDEF_TYPE_AUTO_DEDUCT:
6948 T = Context.getAutoDeductType();
6949 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006950 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6951 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6954 T = Context.ARCUnbridgedCastTy;
6955 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 case PREDEF_TYPE_BUILTIN_FN:
6957 T = Context.BuiltinFnTy;
6958 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006959 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6960 T = Context.OMPArraySectionTy;
6961 break;
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05006962 case PREDEF_TYPE_OMP_ARRAY_SHAPING:
6963 T = Context.OMPArraySectionTy;
6964 break;
Alexey Bataev13a15042020-04-01 15:06:38 -04006965 case PREDEF_TYPE_OMP_ITERATOR:
6966 T = Context.OMPIteratorTy;
6967 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006968#define SVE_TYPE(Name, Id, SingletonId) \
6969 case PREDEF_TYPE_##Id##_ID: \
6970 T = Context.SingletonId; \
6971 break;
6972#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 }
6974
6975 assert(!T.isNull() && "Unknown predefined type");
6976 return T.withFastQualifiers(FastQuals);
6977 }
6978
6979 Index -= NUM_PREDEF_TYPE_IDS;
6980 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6981 if (TypesLoaded[Index].isNull()) {
6982 TypesLoaded[Index] = readTypeRecord(Index);
6983 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006984 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006985
6986 TypesLoaded[Index]->setFromAST();
6987 if (DeserializationListener)
6988 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6989 TypesLoaded[Index]);
6990 }
6991
6992 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6993}
6994
6995QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6996 return GetType(getGlobalTypeID(F, LocalID));
6997}
6998
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006999serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007000ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7001 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7002 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007003
Guy Benyei11169dd2012-12-18 14:30:41 +00007004 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7005 return LocalID;
7006
Richard Smith37a93df2017-02-18 00:32:02 +00007007 if (!F.ModuleOffsetMap.empty())
7008 ReadModuleOffsetMap(F);
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7011 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7012 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007013
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 unsigned GlobalIndex = LocalIndex + I->second;
7015 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7016}
7017
7018TemplateArgumentLocInfo
John McCall3ce3d232019-12-13 03:37:23 -05007019ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 switch (Kind) {
7021 case TemplateArgument::Expression:
John McCall3ce3d232019-12-13 03:37:23 -05007022 return readExpr();
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 case TemplateArgument::Type:
John McCall3ce3d232019-12-13 03:37:23 -05007024 return readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007025 case TemplateArgument::Template: {
John McCall3ce3d232019-12-13 03:37:23 -05007026 NestedNameSpecifierLoc QualifierLoc =
7027 readNestedNameSpecifierLoc();
7028 SourceLocation TemplateNameLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007029 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7030 SourceLocation());
7031 }
7032 case TemplateArgument::TemplateExpansion: {
John McCall3ce3d232019-12-13 03:37:23 -05007033 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7034 SourceLocation TemplateNameLoc = readSourceLocation();
7035 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007036 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007037 EllipsisLoc);
7038 }
7039 case TemplateArgument::Null:
7040 case TemplateArgument::Integral:
7041 case TemplateArgument::Declaration:
7042 case TemplateArgument::NullPtr:
7043 case TemplateArgument::Pack:
7044 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007045 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007046 }
7047 llvm_unreachable("unexpected template argument loc");
7048}
7049
John McCall3ce3d232019-12-13 03:37:23 -05007050TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7051 TemplateArgument Arg = readTemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00007052
7053 if (Arg.getKind() == TemplateArgument::Expression) {
John McCall3ce3d232019-12-13 03:37:23 -05007054 if (readBool()) // bool InfoHasSameExpr.
Guy Benyei11169dd2012-12-18 14:30:41 +00007055 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7056 }
John McCall3ce3d232019-12-13 03:37:23 -05007057 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00007058}
7059
John McCall3ce3d232019-12-13 03:37:23 -05007060const ASTTemplateArgumentListInfo *
7061ASTRecordReader::readASTTemplateArgumentListInfo() {
7062 SourceLocation LAngleLoc = readSourceLocation();
7063 SourceLocation RAngleLoc = readSourceLocation();
7064 unsigned NumArgsAsWritten = readInt();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007065 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7066 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05007067 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007068 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7069}
7070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7072 return GetDecl(ID);
7073}
7074
Richard Smith053f6c62014-05-16 23:01:30 +00007075void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007076 if (NumCurrentElementsDeserializing) {
7077 // We arrange to not care about the complete redeclaration chain while we're
7078 // deserializing. Just remember that the AST has marked this one as complete
7079 // but that it's not actually complete yet, so we know we still need to
7080 // complete it later.
7081 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7082 return;
7083 }
7084
Richard Smith053f6c62014-05-16 23:01:30 +00007085 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7086
Richard Smith053f6c62014-05-16 23:01:30 +00007087 // If this is a named declaration, complete it by looking it up
7088 // within its context.
7089 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007090 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007091 // all mergeable entities within it.
7092 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7093 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7094 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007095 if (!getContext().getLangOpts().CPlusPlus &&
7096 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007097 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007098 // the identifier instead. (For C++ modules, we don't store decls
7099 // in the serialized identifier table, so we do the lookup in the TU.)
7100 auto *II = Name.getAsIdentifierInfo();
7101 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007102 if (II->isOutOfDate())
7103 updateOutOfDateIdentifier(*II);
7104 } else
7105 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007106 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007107 // Find all declarations of this kind from the relevant context.
7108 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7109 auto *DC = cast<DeclContext>(DCDecl);
7110 SmallVector<Decl*, 8> Decls;
7111 FindExternalLexicalDecls(
7112 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7113 }
Richard Smith053f6c62014-05-16 23:01:30 +00007114 }
7115 }
Richard Smith50895422015-01-31 03:04:55 +00007116
7117 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7118 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7119 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7120 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7121 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7122 if (auto *Template = FD->getPrimaryTemplate())
7123 Template->LoadLazySpecializations();
7124 }
Richard Smith053f6c62014-05-16 23:01:30 +00007125}
7126
Richard Smithc2bb8182015-03-24 06:36:48 +00007127CXXCtorInitializer **
7128ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7129 RecordLocation Loc = getLocalBitOffset(Offset);
7130 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7131 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007132 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7133 Error(std::move(Err));
7134 return nullptr;
7135 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007136 ReadingKindTracker ReadingKind(Read_Decl, *this);
7137
JF Bastien0e828952019-06-26 19:50:12 +00007138 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7139 if (!MaybeCode) {
7140 Error(MaybeCode.takeError());
7141 return nullptr;
7142 }
7143 unsigned Code = MaybeCode.get();
7144
John McCall3ce3d232019-12-13 03:37:23 -05007145 ASTRecordReader Record(*this, *Loc.F);
7146 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007147 if (!MaybeRecCode) {
7148 Error(MaybeRecCode.takeError());
7149 return nullptr;
7150 }
7151 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007152 Error("malformed AST file: missing C++ ctor initializers");
7153 return nullptr;
7154 }
7155
John McCall3ce3d232019-12-13 03:37:23 -05007156 return Record.readCXXCtorInitializers();
Richard Smithc2bb8182015-03-24 06:36:48 +00007157}
7158
Guy Benyei11169dd2012-12-18 14:30:41 +00007159CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007160 assert(ContextObj && "reading base specifiers with no AST context");
7161 ASTContext &Context = *ContextObj;
7162
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007164 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007166 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7167 Error(std::move(Err));
7168 return nullptr;
7169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 ReadingKindTracker ReadingKind(Read_Decl, *this);
JF Bastien0e828952019-06-26 19:50:12 +00007171
7172 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7173 if (!MaybeCode) {
7174 Error(MaybeCode.takeError());
7175 return nullptr;
7176 }
7177 unsigned Code = MaybeCode.get();
7178
John McCall3ce3d232019-12-13 03:37:23 -05007179 ASTRecordReader Record(*this, *Loc.F);
7180 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007181 if (!MaybeRecCode) {
7182 Error(MaybeCode.takeError());
7183 return nullptr;
7184 }
7185 unsigned RecCode = MaybeRecCode.get();
7186
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007188 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007189 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 }
7191
John McCall3ce3d232019-12-13 03:37:23 -05007192 unsigned NumBases = Record.readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00007193 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007194 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 for (unsigned I = 0; I != NumBases; ++I)
John McCall3ce3d232019-12-13 03:37:23 -05007196 Bases[I] = Record.readCXXBaseSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 return Bases;
7198}
7199
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007200serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007201ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7202 if (LocalID < NUM_PREDEF_DECL_IDS)
7203 return LocalID;
7204
Richard Smith37a93df2017-02-18 00:32:02 +00007205 if (!F.ModuleOffsetMap.empty())
7206 ReadModuleOffsetMap(F);
7207
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7209 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7210 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007211
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 return LocalID + I->second;
7213}
7214
7215bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7216 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007217 // Predefined decls aren't from any module.
7218 if (ID < NUM_PREDEF_DECL_IDS)
7219 return false;
7220
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007221 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007222 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007223}
7224
Douglas Gregor9f782892013-01-21 15:25:38 +00007225ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007227 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7229 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7230 return I->second;
7231}
7232
7233SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7234 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007235 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007236
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7238
7239 if (Index > DeclsLoaded.size()) {
7240 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007241 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007243
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 if (Decl *D = DeclsLoaded[Index])
7245 return D->getLocation();
7246
Richard Smithcb34bd32016-03-27 07:28:06 +00007247 SourceLocation Loc;
7248 DeclCursorForID(ID, Loc);
7249 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007250}
7251
Richard Smithfe620d22015-03-05 23:24:12 +00007252static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7253 switch (ID) {
7254 case PREDEF_DECL_NULL_ID:
7255 return nullptr;
7256
7257 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7258 return Context.getTranslationUnitDecl();
7259
7260 case PREDEF_DECL_OBJC_ID_ID:
7261 return Context.getObjCIdDecl();
7262
7263 case PREDEF_DECL_OBJC_SEL_ID:
7264 return Context.getObjCSelDecl();
7265
7266 case PREDEF_DECL_OBJC_CLASS_ID:
7267 return Context.getObjCClassDecl();
7268
7269 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7270 return Context.getObjCProtocolDecl();
7271
7272 case PREDEF_DECL_INT_128_ID:
7273 return Context.getInt128Decl();
7274
7275 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7276 return Context.getUInt128Decl();
7277
7278 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7279 return Context.getObjCInstanceTypeDecl();
7280
7281 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7282 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007283
Richard Smith9b88a4c2015-07-27 05:40:23 +00007284 case PREDEF_DECL_VA_LIST_TAG:
7285 return Context.getVaListTagDecl();
7286
Charles Davisc7d5c942015-09-17 20:55:33 +00007287 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7288 return Context.getBuiltinMSVaListDecl();
7289
Richard Smithf19e1272015-03-07 00:04:49 +00007290 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7291 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007292
7293 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7294 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007295
7296 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7297 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007298
7299 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7300 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007301
7302 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7303 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007304 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007305 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007306}
7307
Richard Smithcd45dbc2014-04-19 03:48:30 +00007308Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007309 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007310 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007311 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007312 if (D) {
7313 // Track that we have merged the declaration with ID \p ID into the
7314 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007315 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007316 if (Merged.empty())
7317 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007318 }
Richard Smithfe620d22015-03-05 23:24:12 +00007319 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007320 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007321
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7323
7324 if (Index >= DeclsLoaded.size()) {
7325 assert(0 && "declaration ID out-of-range for AST file");
7326 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007327 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007329
7330 return DeclsLoaded[Index];
7331}
7332
7333Decl *ASTReader::GetDecl(DeclID ID) {
7334 if (ID < NUM_PREDEF_DECL_IDS)
7335 return GetExistingDecl(ID);
7336
7337 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7338
7339 if (Index >= DeclsLoaded.size()) {
7340 assert(0 && "declaration ID out-of-range for AST file");
7341 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007342 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007343 }
7344
Guy Benyei11169dd2012-12-18 14:30:41 +00007345 if (!DeclsLoaded[Index]) {
7346 ReadDeclRecord(ID);
7347 if (DeserializationListener)
7348 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7349 }
7350
7351 return DeclsLoaded[Index];
7352}
7353
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007354DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 DeclID GlobalID) {
7356 if (GlobalID < NUM_PREDEF_DECL_IDS)
7357 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007358
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7360 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7361 ModuleFile *Owner = I->second;
7362
7363 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7364 = M.GlobalToLocalDeclIDs.find(Owner);
7365 if (Pos == M.GlobalToLocalDeclIDs.end())
7366 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007367
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 return GlobalID - Owner->BaseDeclID + Pos->second;
7369}
7370
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007371serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007372 const RecordData &Record,
7373 unsigned &Idx) {
7374 if (Idx >= Record.size()) {
7375 Error("Corrupted AST file");
7376 return 0;
7377 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007378
Guy Benyei11169dd2012-12-18 14:30:41 +00007379 return getGlobalDeclID(F, Record[Idx++]);
7380}
7381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007382/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007383///
7384/// This operation will read a new statement from the external
7385/// source each time it is called, and is meant to be used via a
7386/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7387Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7388 // Switch case IDs are per Decl.
7389 ClearSwitchCaseIDs();
7390
7391 // Offset here is a global offset across the entire chain.
7392 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007393 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7394 Error(std::move(Err));
7395 return nullptr;
7396 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007397 assert(NumCurrentElementsDeserializing == 0 &&
7398 "should not be called while already deserializing");
7399 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 return ReadStmtFromStream(*Loc.F);
7401}
7402
Richard Smith3cb15722015-08-05 22:41:45 +00007403void ASTReader::FindExternalLexicalDecls(
7404 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7405 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007406 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7407
Richard Smith9ccdd932015-08-06 22:14:12 +00007408 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007409 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7410 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7411 auto K = (Decl::Kind)+LexicalDecls[I];
7412 if (!IsKindWeWant(K))
7413 continue;
7414
7415 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7416
7417 // Don't add predefined declarations to the lexical context more
7418 // than once.
7419 if (ID < NUM_PREDEF_DECL_IDS) {
7420 if (PredefsVisited[ID])
7421 continue;
7422
7423 PredefsVisited[ID] = true;
7424 }
7425
7426 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007427 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007428 if (!DC->isDeclInLexicalTraversal(D))
7429 Decls.push_back(D);
7430 }
7431 }
7432 };
7433
7434 if (isa<TranslationUnitDecl>(DC)) {
7435 for (auto Lexical : TULexicalDecls)
7436 Visit(Lexical.first, Lexical.second);
7437 } else {
7438 auto I = LexicalDecls.find(DC);
7439 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007440 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007441 }
7442
Guy Benyei11169dd2012-12-18 14:30:41 +00007443 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007444}
7445
7446namespace {
7447
7448class DeclIDComp {
7449 ASTReader &Reader;
7450 ModuleFile &Mod;
7451
7452public:
7453 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7454
7455 bool operator()(LocalDeclID L, LocalDeclID R) const {
7456 SourceLocation LHS = getLocation(L);
7457 SourceLocation RHS = getLocation(R);
7458 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7459 }
7460
7461 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7462 SourceLocation RHS = getLocation(R);
7463 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7464 }
7465
7466 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7467 SourceLocation LHS = getLocation(L);
7468 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7469 }
7470
7471 SourceLocation getLocation(LocalDeclID ID) const {
7472 return Reader.getSourceManager().getFileLoc(
7473 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7474 }
7475};
7476
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007477} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007478
7479void ASTReader::FindFileRegionDecls(FileID File,
7480 unsigned Offset, unsigned Length,
7481 SmallVectorImpl<Decl *> &Decls) {
7482 SourceManager &SM = getSourceManager();
7483
7484 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7485 if (I == FileDeclIDs.end())
7486 return;
7487
7488 FileDeclsInfo &DInfo = I->second;
7489 if (DInfo.Decls.empty())
7490 return;
7491
7492 SourceLocation
7493 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7494 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7495
7496 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007497 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7498 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 if (BeginIt != DInfo.Decls.begin())
7500 --BeginIt;
7501
7502 // If we are pointing at a top-level decl inside an objc container, we need
7503 // to backtrack until we find it otherwise we will fail to report that the
7504 // region overlaps with an objc container.
7505 while (BeginIt != DInfo.Decls.begin() &&
7506 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7507 ->isTopLevelDeclInObjCContainer())
7508 --BeginIt;
7509
Fangrui Song7264a472019-07-03 08:13:17 +00007510 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7511 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 if (EndIt != DInfo.Decls.end())
7513 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007514
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 for (ArrayRef<serialization::LocalDeclID>::iterator
7516 DIt = BeginIt; DIt != EndIt; ++DIt)
7517 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7518}
7519
Richard Smith9ce12e32013-02-07 03:30:24 +00007520bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007521ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7522 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007523 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007524 "DeclContext has no visible decls in storage");
7525 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007526 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007527
Richard Smithd88a7f12015-09-01 20:35:42 +00007528 auto It = Lookups.find(DC);
7529 if (It == Lookups.end())
7530 return false;
7531
Richard Smith8c913ec2014-08-14 02:21:01 +00007532 Deserializing LookupResults(this);
7533
Richard Smithd88a7f12015-09-01 20:35:42 +00007534 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007536 for (DeclID ID : It->second.Table.find(Name)) {
7537 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007538 if (ND->getDeclName() == Name)
7539 Decls.push_back(ND);
7540 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007541
Guy Benyei11169dd2012-12-18 14:30:41 +00007542 ++NumVisibleDeclContextsRead;
7543 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007544 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007545}
7546
Guy Benyei11169dd2012-12-18 14:30:41 +00007547void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7548 if (!DC->hasExternalVisibleStorage())
7549 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007550
7551 auto It = Lookups.find(DC);
7552 assert(It != Lookups.end() &&
7553 "have external visible storage but no lookup tables");
7554
Craig Topper79be4cd2013-07-05 04:33:53 +00007555 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007556
Vedant Kumar48b4f762018-04-14 01:40:48 +00007557 for (DeclID ID : It->second.Table.findAll()) {
7558 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007559 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007560 }
7561
Guy Benyei11169dd2012-12-18 14:30:41 +00007562 ++NumVisibleDeclContextsRead;
7563
Vedant Kumar48b4f762018-04-14 01:40:48 +00007564 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7565 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7566 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007567 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7568}
7569
Richard Smithd88a7f12015-09-01 20:35:42 +00007570const serialization::reader::DeclContextLookupTable *
7571ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7572 auto I = Lookups.find(Primary);
7573 return I == Lookups.end() ? nullptr : &I->second;
7574}
7575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007576/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007577/// before receiving the implementation, and codegen depends on this.
7578/// We simulate this by deserializing and passing to consumer the methods of the
7579/// implementation before passing the deserialized implementation decl.
7580static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7581 ASTConsumer *Consumer) {
7582 assert(ImplD && Consumer);
7583
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007584 for (auto *I : ImplD->methods())
7585 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007586
7587 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7588}
7589
Guy Benyei11169dd2012-12-18 14:30:41 +00007590void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007591 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007592 PassObjCImplDeclToConsumer(ImplD, Consumer);
7593 else
7594 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7595}
7596
7597void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7598 this->Consumer = Consumer;
7599
Richard Smith9e2341d2015-03-23 03:25:59 +00007600 if (Consumer)
7601 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007602
7603 if (DeserializationListener)
7604 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007605}
7606
7607void ASTReader::PrintStats() {
7608 std::fprintf(stderr, "*** AST File Statistics:\n");
7609
7610 unsigned NumTypesLoaded
7611 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7612 QualType());
7613 unsigned NumDeclsLoaded
7614 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007615 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 unsigned NumIdentifiersLoaded
7617 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7618 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007619 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 unsigned NumMacrosLoaded
7621 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7622 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007623 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 unsigned NumSelectorsLoaded
7625 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7626 SelectorsLoaded.end(),
7627 Selector());
7628
7629 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7630 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7631 NumSLocEntriesRead, TotalNumSLocEntries,
7632 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7633 if (!TypesLoaded.empty())
7634 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7635 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7636 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7637 if (!DeclsLoaded.empty())
7638 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7639 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7640 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7641 if (!IdentifiersLoaded.empty())
7642 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7643 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7644 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7645 if (!MacrosLoaded.empty())
7646 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7647 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7648 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7649 if (!SelectorsLoaded.empty())
7650 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7651 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7652 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7653 if (TotalNumStatements)
7654 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7655 NumStatementsRead, TotalNumStatements,
7656 ((float)NumStatementsRead/TotalNumStatements * 100));
7657 if (TotalNumMacros)
7658 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7659 NumMacrosRead, TotalNumMacros,
7660 ((float)NumMacrosRead/TotalNumMacros * 100));
7661 if (TotalLexicalDeclContexts)
7662 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7663 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7664 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7665 * 100));
7666 if (TotalVisibleDeclContexts)
7667 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7668 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7669 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7670 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007671 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7673 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7674 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7675 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007676 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007677 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7678 NumMethodPoolHits, NumMethodPoolLookups,
7679 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007680 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007681 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7682 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7683 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7684 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007685 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007686 std::fprintf(stderr,
7687 " %u / %u identifier table lookups succeeded (%f%%)\n",
7688 NumIdentifierLookupHits, NumIdentifierLookups,
7689 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007690
Douglas Gregore060e572013-01-25 01:03:03 +00007691 if (GlobalIndex) {
7692 std::fprintf(stderr, "\n");
7693 GlobalIndex->printStats();
7694 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007695
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 std::fprintf(stderr, "\n");
7697 dump();
7698 std::fprintf(stderr, "\n");
7699}
7700
7701template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007702LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007703dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007704 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 InitialCapacity> &Map) {
7706 if (Map.begin() == Map.end())
7707 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007708
Vedant Kumar48b4f762018-04-14 01:40:48 +00007709 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7710
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007712 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7713 I != IEnd; ++I) {
7714 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7715 << "\n";
7716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007717}
7718
Yaron Kerencdae9412016-01-29 19:38:18 +00007719LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7721 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7722 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7723 dumpModuleIDMap("Global type map", GlobalTypeMap);
7724 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7725 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7726 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7727 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7728 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007729 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007731
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007733 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007734 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007735}
7736
7737/// Return the amount of memory used by memory buffers, breaking down
7738/// by heap-backed versus mmap'ed memory.
7739void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007740 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007741 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007742 size_t bytes = buf->getBufferSize();
7743 switch (buf->getBufferKind()) {
7744 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7745 sizes.malloc_bytes += bytes;
7746 break;
7747 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7748 sizes.mmap_bytes += bytes;
7749 break;
7750 }
7751 }
7752 }
7753}
7754
7755void ASTReader::InitializeSema(Sema &S) {
7756 SemaObj = &S;
7757 S.addExternalSource(this);
7758
7759 // Makes sure any declarations that were deserialized "too early"
7760 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007761 for (uint64_t ID : PreloadedDeclIDs) {
7762 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007763 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007765 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007766
Richard Smith3d8e97e2013-10-18 06:54:39 +00007767 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 if (!FPPragmaOptions.empty()) {
7769 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007770 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 }
7772
Yaxun Liu5b746652016-12-18 05:18:55 +00007773 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7774 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7775 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007776
7777 UpdateSema();
7778}
7779
7780void ASTReader::UpdateSema() {
7781 assert(SemaObj && "no Sema to update");
7782
7783 // Load the offsets of the declarations that Sema references.
7784 // They will be lazily deserialized when needed.
7785 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007786 assert(SemaDeclRefs.size() % 3 == 0);
7787 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007788 if (!SemaObj->StdNamespace)
7789 SemaObj->StdNamespace = SemaDeclRefs[I];
7790 if (!SemaObj->StdBadAlloc)
7791 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007792 if (!SemaObj->StdAlignValT)
7793 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007794 }
7795 SemaDeclRefs.clear();
7796 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007797
Nico Weber779355f2016-03-02 23:22:00 +00007798 // Update the state of pragmas. Use the same API as if we had encountered the
7799 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007800 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007801 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007802 if (PragmaMSStructState != -1)
7803 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007804 if (PointersToMembersPragmaLocation.isValid()) {
7805 SemaObj->ActOnPragmaMSPointersToMembers(
7806 (LangOptions::PragmaMSPointersToMembersKind)
7807 PragmaMSPointersToMembersState,
7808 PointersToMembersPragmaLocation);
7809 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007810 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007811
7812 if (PragmaPackCurrentValue) {
7813 // The bottom of the stack might have a default value. It must be adjusted
7814 // to the current value to ensure that the packing state is preserved after
7815 // popping entries that were included/imported from a PCH/module.
7816 bool DropFirst = false;
7817 if (!PragmaPackStack.empty() &&
7818 PragmaPackStack.front().Location.isInvalid()) {
7819 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7820 "Expected a default alignment value");
7821 SemaObj->PackStack.Stack.emplace_back(
7822 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007823 SemaObj->PackStack.CurrentPragmaLocation,
7824 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007825 DropFirst = true;
7826 }
7827 for (const auto &Entry :
7828 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7829 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007830 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007831 if (PragmaPackCurrentLocation.isInvalid()) {
7832 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7833 "Expected a default alignment value");
7834 // Keep the current values.
7835 } else {
7836 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7837 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7838 }
7839 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007840}
7841
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007842IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007843 // Note that we are loading an identifier.
7844 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007845
Douglas Gregor7211ac12013-01-25 23:32:03 +00007846 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007847 NumIdentifierLookups,
7848 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007849
7850 // We don't need to do identifier table lookups in C++ modules (we preload
7851 // all interesting declarations, and don't need to use the scope for name
7852 // lookups). Perform the lookup in PCH files, though, since we don't build
7853 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007854 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007855 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007856 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007857 break;
7858 } else {
7859 // If there is a global index, look there first to determine which modules
7860 // provably do not have any results for this identifier.
7861 GlobalModuleIndex::HitSet Hits;
7862 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7863 if (!loadGlobalIndex()) {
7864 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7865 HitsPtr = &Hits;
7866 }
7867 }
7868
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007869 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007870 }
7871
Guy Benyei11169dd2012-12-18 14:30:41 +00007872 IdentifierInfo *II = Visitor.getIdentifierInfo();
7873 markIdentifierUpToDate(II);
7874 return II;
7875}
7876
7877namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007879 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007880 /// identifiers stored within a set of AST files.
7881 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007882 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 const ASTReader &Reader;
7884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007885 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 /// the AST reader.
7887 unsigned Index;
7888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007889 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 /// of the current AST file.
7891 ASTIdentifierLookupTable::key_iterator Current;
7892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007893 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 /// the current AST file.
7895 ASTIdentifierLookupTable::key_iterator End;
7896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007897 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007898 bool SkipModules;
7899
Guy Benyei11169dd2012-12-18 14:30:41 +00007900 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007901 explicit ASTIdentifierIterator(const ASTReader &Reader,
7902 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007903
Craig Topper3e89dfe2014-03-13 02:13:41 +00007904 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007905 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007906
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007907} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007908
Ben Langmuir537c5b52016-05-04 00:53:13 +00007909ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7910 bool SkipModules)
7911 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007912}
7913
7914StringRef ASTIdentifierIterator::Next() {
7915 while (Current == End) {
7916 // If we have exhausted all of our AST files, we're done.
7917 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007918 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007919
7920 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007921 ModuleFile &F = Reader.ModuleMgr[Index];
7922 if (SkipModules && F.isModule())
7923 continue;
7924
Vedant Kumar48b4f762018-04-14 01:40:48 +00007925 ASTIdentifierLookupTable *IdTable =
7926 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 Current = IdTable->key_begin();
7928 End = IdTable->key_end();
7929 }
7930
7931 // We have any identifiers remaining in the current AST file; return
7932 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007933 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007935 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007936}
7937
Ben Langmuir537c5b52016-05-04 00:53:13 +00007938namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007939
Ben Langmuir537c5b52016-05-04 00:53:13 +00007940/// A utility for appending two IdentifierIterators.
7941class ChainedIdentifierIterator : public IdentifierIterator {
7942 std::unique_ptr<IdentifierIterator> Current;
7943 std::unique_ptr<IdentifierIterator> Queued;
7944
7945public:
7946 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7947 std::unique_ptr<IdentifierIterator> Second)
7948 : Current(std::move(First)), Queued(std::move(Second)) {}
7949
7950 StringRef Next() override {
7951 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007952 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007953
7954 StringRef result = Current->Next();
7955 if (!result.empty())
7956 return result;
7957
7958 // Try the queued iterator, which may itself be empty.
7959 Current.reset();
7960 std::swap(Current, Queued);
7961 return Next();
7962 }
7963};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007964
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007965} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007966
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007967IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007968 if (!loadGlobalIndex()) {
7969 std::unique_ptr<IdentifierIterator> ReaderIter(
7970 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7971 std::unique_ptr<IdentifierIterator> ModulesIter(
7972 GlobalIndex->createIdentifierIterator());
7973 return new ChainedIdentifierIterator(std::move(ReaderIter),
7974 std::move(ModulesIter));
7975 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007976
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 return new ASTIdentifierIterator(*this);
7978}
7979
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007980namespace clang {
7981namespace serialization {
7982
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 class ReadMethodPoolVisitor {
7984 ASTReader &Reader;
7985 Selector Sel;
7986 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007987 unsigned InstanceBits = 0;
7988 unsigned FactoryBits = 0;
7989 bool InstanceHasMoreThanOneDecl = false;
7990 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007991 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7992 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993
7994 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007995 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007997 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007998
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007999 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 if (!M.SelectorLookupTable)
8001 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008002
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008004 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 return true;
8006
Richard Smithbdf2d932015-07-30 03:37:16 +00008007 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008008 ASTSelectorLookupTable *PoolTable
8009 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008010 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 if (Pos == PoolTable->end())
8012 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008013
Richard Smithbdf2d932015-07-30 03:37:16 +00008014 ++Reader.NumMethodPoolTableHits;
8015 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 // FIXME: Not quite happy with the statistics here. We probably should
8017 // disable this tracking when called via LoadSelector.
8018 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008019 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008021 if (Reader.DeserializationListener)
8022 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008023
Richard Smithbdf2d932015-07-30 03:37:16 +00008024 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8025 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8026 InstanceBits = Data.InstanceBits;
8027 FactoryBits = Data.FactoryBits;
8028 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8029 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 return true;
8031 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008033 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008034 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8035 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008036 }
8037
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008038 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008039 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 return FactoryMethods;
8041 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008042
8043 unsigned getInstanceBits() const { return InstanceBits; }
8044 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008045
Nico Weberff4b35e2014-12-27 22:14:15 +00008046 bool instanceHasMoreThanOneDecl() const {
8047 return InstanceHasMoreThanOneDecl;
8048 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008049
Nico Weberff4b35e2014-12-27 22:14:15 +00008050 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008052
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008053} // namespace serialization
8054} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008056/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008057static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8058 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008059 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8060 S.addMethodToGlobalList(&List, Methods[I]);
8061 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008062}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008063
Guy Benyei11169dd2012-12-18 14:30:41 +00008064void ASTReader::ReadMethodPool(Selector Sel) {
8065 // Get the selector generation and update it to the current generation.
8066 unsigned &Generation = SelectorGeneration[Sel];
8067 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008068 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008069 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008070
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008072 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008074 ModuleMgr.visit(Visitor);
8075
Guy Benyei11169dd2012-12-18 14:30:41 +00008076 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008077 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008079
8080 ++NumMethodPoolHits;
8081
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 if (!getSema())
8083 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008084
Guy Benyei11169dd2012-12-18 14:30:41 +00008085 Sema &S = *getSema();
8086 Sema::GlobalMethodPool::iterator Pos
8087 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008088
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008089 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008090 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008091 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008092 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008093
8094 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8095 // when building a module we keep every method individually and may need to
8096 // update hasMoreThanOneDecl as we add the methods.
8097 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8098 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008099}
8100
Manman Rena0f31a02016-04-29 19:04:05 +00008101void ASTReader::updateOutOfDateSelector(Selector Sel) {
8102 if (SelectorOutOfDate[Sel])
8103 ReadMethodPool(Sel);
8104}
8105
Guy Benyei11169dd2012-12-18 14:30:41 +00008106void ASTReader::ReadKnownNamespaces(
8107 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8108 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008109
Vedant Kumar48b4f762018-04-14 01:40:48 +00008110 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8111 if (NamespaceDecl *Namespace
8112 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008114 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008115}
8116
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008117void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008118 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008119 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008120 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008121 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008122 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008123 Undefined.insert(std::make_pair(D, Loc));
8124 }
8125}
Nick Lewycky8334af82013-01-26 00:35:08 +00008126
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008127void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8128 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8129 Exprs) {
8130 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008131 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008132 uint64_t Count = DelayedDeleteExprs[Idx++];
8133 for (uint64_t C = 0; C < Count; ++C) {
8134 SourceLocation DeleteLoc =
8135 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8136 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8137 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8138 }
8139 }
8140}
8141
Guy Benyei11169dd2012-12-18 14:30:41 +00008142void ASTReader::ReadTentativeDefinitions(
8143 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008144 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8145 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 if (Var)
8147 TentativeDefs.push_back(Var);
8148 }
8149 TentativeDefinitions.clear();
8150}
8151
8152void ASTReader::ReadUnusedFileScopedDecls(
8153 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008154 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8155 DeclaratorDecl *D
8156 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 if (D)
8158 Decls.push_back(D);
8159 }
8160 UnusedFileScopedDecls.clear();
8161}
8162
8163void ASTReader::ReadDelegatingConstructors(
8164 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008165 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8166 CXXConstructorDecl *D
8167 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 if (D)
8169 Decls.push_back(D);
8170 }
8171 DelegatingCtorDecls.clear();
8172}
8173
8174void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008175 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8176 TypedefNameDecl *D
8177 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 if (D)
8179 Decls.push_back(D);
8180 }
8181 ExtVectorDecls.clear();
8182}
8183
Nico Weber72889432014-09-06 01:25:55 +00008184void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8185 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008186 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8187 ++I) {
8188 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8189 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008190 if (D)
8191 Decls.insert(D);
8192 }
8193 UnusedLocalTypedefNameCandidates.clear();
8194}
8195
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05008196void ASTReader::ReadDeclsToCheckForDeferredDiags(
8197 llvm::SmallVector<Decl *, 4> &Decls) {
8198 for (unsigned I = 0, N = DeclsToCheckForDeferredDiags.size(); I != N;
8199 ++I) {
8200 auto *D = dyn_cast_or_null<Decl>(
8201 GetDecl(DeclsToCheckForDeferredDiags[I]));
8202 if (D)
8203 Decls.push_back(D);
8204 }
8205 DeclsToCheckForDeferredDiags.clear();
8206}
8207
8208
Guy Benyei11169dd2012-12-18 14:30:41 +00008209void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008210 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 if (ReferencedSelectorsData.empty())
8212 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008213
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 // If there are @selector references added them to its pool. This is for
8215 // implementation of -Wselector.
8216 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8217 unsigned I = 0;
8218 while (I < DataSize) {
8219 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8220 SourceLocation SelLoc
8221 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8222 Sels.push_back(std::make_pair(Sel, SelLoc));
8223 }
8224 ReferencedSelectorsData.clear();
8225}
8226
8227void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008228 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 if (WeakUndeclaredIdentifiers.empty())
8230 return;
8231
8232 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008233 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008235 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8237 SourceLocation Loc
8238 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8239 bool Used = WeakUndeclaredIdentifiers[I++];
8240 WeakInfo WI(AliasId, Loc);
8241 WI.setUsed(Used);
8242 WeakIDs.push_back(std::make_pair(WeakId, WI));
8243 }
8244 WeakUndeclaredIdentifiers.clear();
8245}
8246
8247void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8248 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8249 ExternalVTableUse VT;
8250 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8251 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8252 VT.DefinitionRequired = VTableUses[Idx++];
8253 VTables.push_back(VT);
8254 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008255
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 VTableUses.clear();
8257}
8258
8259void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008260 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008262 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 SourceLocation Loc
8264 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8265
8266 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008267 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 PendingInstantiations.clear();
8269}
8270
Richard Smithe40f2ba2013-08-07 21:41:30 +00008271void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008272 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8273 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008274 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8275 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008276 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008277
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008278 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008279 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8280
8281 ModuleFile *F = getOwningModuleFile(LT->D);
8282 assert(F && "No module");
8283
8284 unsigned TokN = LateParsedTemplates[Idx++];
8285 LT->Toks.reserve(TokN);
8286 for (unsigned T = 0; T < TokN; ++T)
8287 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8288
Justin Lebar28f09c52016-10-10 16:26:08 +00008289 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008290 }
8291
8292 LateParsedTemplates.clear();
8293}
8294
Guy Benyei11169dd2012-12-18 14:30:41 +00008295void ASTReader::LoadSelector(Selector Sel) {
8296 // It would be complicated to avoid reading the methods anyway. So don't.
8297 ReadMethodPool(Sel);
8298}
8299
8300void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8301 assert(ID && "Non-zero identifier ID required");
8302 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8303 IdentifiersLoaded[ID - 1] = II;
8304 if (DeserializationListener)
8305 DeserializationListener->IdentifierRead(ID, II);
8306}
8307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008308/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008309/// identifier.
8310///
8311/// If the AST reader is currently in a state where the given declaration IDs
8312/// cannot safely be resolved, they are queued until it is safe to resolve
8313/// them.
8314///
8315/// \param II an IdentifierInfo that refers to one or more globally-visible
8316/// declarations.
8317///
8318/// \param DeclIDs the set of declaration IDs with the name @p II that are
8319/// visible at global scope.
8320///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008321/// \param Decls if non-null, this vector will be populated with the set of
8322/// deserialized declarations. These declarations will not be pushed into
8323/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008324void
8325ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8326 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008327 SmallVectorImpl<Decl *> *Decls) {
8328 if (NumCurrentElementsDeserializing && !Decls) {
8329 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 return;
8331 }
8332
Vedant Kumar48b4f762018-04-14 01:40:48 +00008333 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008334 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008335 // Queue this declaration so that it will be added to the
8336 // translation unit scope and identifier's declaration chain
8337 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008338 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008339 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008340 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008341
Vedant Kumar48b4f762018-04-14 01:40:48 +00008342 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008343
8344 // If we're simply supposed to record the declarations, do so now.
8345 if (Decls) {
8346 Decls->push_back(D);
8347 continue;
8348 }
8349
8350 // Introduce this declaration into the translation-unit scope
8351 // and add it to the declaration chain for this identifier, so
8352 // that (unqualified) name lookup will find it.
8353 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
8355}
8356
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008357IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008359 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008360
8361 if (IdentifiersLoaded.empty()) {
8362 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008363 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 }
8365
8366 ID -= 1;
8367 if (!IdentifiersLoaded[ID]) {
8368 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8369 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8370 ModuleFile *M = I->second;
8371 unsigned Index = ID - M->BaseIdentifierID;
8372 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8373
8374 // All of the strings in the AST file are preceded by a 16-bit length.
8375 // Extract that 16-bit length to avoid having to execute strlen().
8376 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8377 // unsigned integers. This is important to avoid integer overflow when
8378 // we cast them to 'unsigned'.
8379 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8380 unsigned StrLen = (((unsigned) StrLenPtr[0])
8381 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008382 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8383 IdentifiersLoaded[ID] = &II;
8384 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008386 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008387 }
8388
8389 return IdentifiersLoaded[ID];
8390}
8391
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008392IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8393 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008394}
8395
8396IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8397 if (LocalID < NUM_PREDEF_IDENT_IDS)
8398 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008399
Richard Smith37a93df2017-02-18 00:32:02 +00008400 if (!M.ModuleOffsetMap.empty())
8401 ReadModuleOffsetMap(M);
8402
Guy Benyei11169dd2012-12-18 14:30:41 +00008403 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8404 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008405 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008406 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 return LocalID + I->second;
8409}
8410
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008411MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008413 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008414
8415 if (MacrosLoaded.empty()) {
8416 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008417 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 }
8419
8420 ID -= NUM_PREDEF_MACRO_IDS;
8421 if (!MacrosLoaded[ID]) {
8422 GlobalMacroMapType::iterator I
8423 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8424 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8425 ModuleFile *M = I->second;
8426 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008427 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008428
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008429 if (DeserializationListener)
8430 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8431 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 }
8433
8434 return MacrosLoaded[ID];
8435}
8436
8437MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8438 if (LocalID < NUM_PREDEF_MACRO_IDS)
8439 return LocalID;
8440
Richard Smith37a93df2017-02-18 00:32:02 +00008441 if (!M.ModuleOffsetMap.empty())
8442 ReadModuleOffsetMap(M);
8443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8445 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8446 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8447
8448 return LocalID + I->second;
8449}
8450
8451serialization::SubmoduleID
8452ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8453 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8454 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008455
Richard Smith37a93df2017-02-18 00:32:02 +00008456 if (!M.ModuleOffsetMap.empty())
8457 ReadModuleOffsetMap(M);
8458
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8460 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008461 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464 return LocalID + I->second;
8465}
8466
8467Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8468 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8469 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008470 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008471 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008472
Guy Benyei11169dd2012-12-18 14:30:41 +00008473 if (GlobalID > SubmodulesLoaded.size()) {
8474 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008475 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008477
Guy Benyei11169dd2012-12-18 14:30:41 +00008478 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8479}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008480
8481Module *ASTReader::getModule(unsigned ID) {
8482 return getSubmodule(ID);
8483}
8484
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008485bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8486 ModuleFile *MF = getOwningModuleFile(D);
8487 return MF && MF->PCHHasObjectFile;
8488}
8489
Richard Smithd88a7f12015-09-01 20:35:42 +00008490ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8491 if (ID & 1) {
8492 // It's a module, look it up by submodule ID.
8493 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8494 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8495 } else {
8496 // It's a prefix (preamble, PCH, ...). Look it up by index.
8497 unsigned IndexFromEnd = ID >> 1;
8498 assert(IndexFromEnd && "got reference to unknown module file");
8499 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8500 }
8501}
8502
8503unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8504 if (!F)
8505 return 1;
8506
8507 // For a file representing a module, use the submodule ID of the top-level
8508 // module as the file ID. For any other kind of file, the number of such
8509 // files loaded beforehand will be the same on reload.
8510 // FIXME: Is this true even if we have an explicit module file and a PCH?
8511 if (F->isModule())
8512 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8513
8514 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008515 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008516 assert(I != PCHModules.end() && "emitting reference to unknown file");
8517 return (I - PCHModules.end()) << 1;
8518}
8519
Reid Klecknerc915cb92020-02-27 18:13:54 -08008520llvm::Optional<ASTSourceDescriptor>
Adrian Prantl15bcf702015-06-30 17:39:43 +00008521ASTReader::getSourceDescriptor(unsigned ID) {
Adrian Prantlf4754ea2020-03-17 12:51:58 -07008522 if (Module *M = getSubmodule(ID))
Reid Klecknerc915cb92020-02-27 18:13:54 -08008523 return ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008524
8525 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008526 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008527 const auto &PCHChain = ModuleMgr.pch_modules();
8528 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008529 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008530 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008531 StringRef FileName = llvm::sys::path::filename(MF.FileName);
Reid Klecknerc915cb92020-02-27 18:13:54 -08008532 return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8533 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008534 }
8535 return None;
8536}
8537
David Blaikie1ac9c982017-04-11 21:13:37 +00008538ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008539 auto I = DefinitionSource.find(FD);
8540 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008541 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008542 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008543}
8544
Guy Benyei11169dd2012-12-18 14:30:41 +00008545Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8546 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8547}
8548
8549Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8550 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008551 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008552
8553 if (ID > SelectorsLoaded.size()) {
8554 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008555 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008556 }
8557
Craig Toppera13603a2014-05-22 05:54:18 +00008558 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008559 // Load this selector from the selector table.
8560 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8561 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8562 ModuleFile &M = *I->second;
8563 ASTSelectorLookupTrait Trait(*this, M);
8564 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8565 SelectorsLoaded[ID - 1] =
8566 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8567 if (DeserializationListener)
8568 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8569 }
8570
8571 return SelectorsLoaded[ID - 1];
8572}
8573
8574Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8575 return DecodeSelector(ID);
8576}
8577
8578uint32_t ASTReader::GetNumExternalSelectors() {
8579 // ID 0 (the null selector) is considered an external selector.
8580 return getTotalNumSelectors() + 1;
8581}
8582
8583serialization::SelectorID
8584ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8585 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8586 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008587
Richard Smith37a93df2017-02-18 00:32:02 +00008588 if (!M.ModuleOffsetMap.empty())
8589 ReadModuleOffsetMap(M);
8590
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8592 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008593 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008594 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596 return LocalID + I->second;
8597}
8598
John McCall3ce3d232019-12-13 03:37:23 -05008599DeclarationNameLoc
8600ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8601 DeclarationNameLoc DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008602 switch (Name.getNameKind()) {
8603 case DeclarationName::CXXConstructorName:
8604 case DeclarationName::CXXDestructorName:
8605 case DeclarationName::CXXConversionFunctionName:
John McCall3ce3d232019-12-13 03:37:23 -05008606 DNLoc.NamedType.TInfo = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 break;
8608
8609 case DeclarationName::CXXOperatorName:
8610 DNLoc.CXXOperatorName.BeginOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008611 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 DNLoc.CXXOperatorName.EndOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008613 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008614 break;
8615
8616 case DeclarationName::CXXLiteralOperatorName:
8617 DNLoc.CXXLiteralOperatorName.OpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008618 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 break;
8620
8621 case DeclarationName::Identifier:
8622 case DeclarationName::ObjCZeroArgSelector:
8623 case DeclarationName::ObjCOneArgSelector:
8624 case DeclarationName::ObjCMultiArgSelector:
8625 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008626 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 break;
8628 }
John McCall3ce3d232019-12-13 03:37:23 -05008629 return DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008630}
8631
John McCall3ce3d232019-12-13 03:37:23 -05008632DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8633 DeclarationNameInfo NameInfo;
8634 NameInfo.setName(readDeclarationName());
8635 NameInfo.setLoc(readSourceLocation());
8636 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8637 return NameInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +00008638}
8639
John McCall3ce3d232019-12-13 03:37:23 -05008640void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8641 Info.QualifierLoc = readNestedNameSpecifierLoc();
8642 unsigned NumTPLists = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 Info.NumTemplParamLists = NumTPLists;
8644 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008645 Info.TemplParamLists =
8646 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008647 for (unsigned i = 0; i != NumTPLists; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05008648 Info.TemplParamLists[i] = readTemplateParameterList();
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 }
8650}
8651
Guy Benyei11169dd2012-12-18 14:30:41 +00008652TemplateParameterList *
John McCall3ce3d232019-12-13 03:37:23 -05008653ASTRecordReader::readTemplateParameterList() {
8654 SourceLocation TemplateLoc = readSourceLocation();
8655 SourceLocation LAngleLoc = readSourceLocation();
8656 SourceLocation RAngleLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008657
John McCall3ce3d232019-12-13 03:37:23 -05008658 unsigned NumParams = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008659 SmallVector<NamedDecl *, 16> Params;
8660 Params.reserve(NumParams);
8661 while (NumParams--)
John McCall3ce3d232019-12-13 03:37:23 -05008662 Params.push_back(readDeclAs<NamedDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00008663
John McCall3ce3d232019-12-13 03:37:23 -05008664 bool HasRequiresClause = readBool();
8665 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
Saar Raz0330fba2019-10-15 18:44:06 +00008666
Richard Smithdbafb6c2017-06-29 23:23:46 +00008667 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00008668 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00008669 return TemplateParams;
8670}
8671
John McCall3ce3d232019-12-13 03:37:23 -05008672void ASTRecordReader::readTemplateArgumentList(
8673 SmallVectorImpl<TemplateArgument> &TemplArgs,
8674 bool Canonicalize) {
8675 unsigned NumTemplateArgs = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008676 TemplArgs.reserve(NumTemplateArgs);
8677 while (NumTemplateArgs--)
John McCall3ce3d232019-12-13 03:37:23 -05008678 TemplArgs.push_back(readTemplateArgument(Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008679}
8680
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008681/// Read a UnresolvedSet structure.
John McCall3ce3d232019-12-13 03:37:23 -05008682void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8683 unsigned NumDecls = readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008684 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008685 while (NumDecls--) {
John McCall3ce3d232019-12-13 03:37:23 -05008686 DeclID ID = readDeclID();
8687 AccessSpecifier AS = (AccessSpecifier) readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008688 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008689 }
8690}
8691
8692CXXBaseSpecifier
John McCall3ce3d232019-12-13 03:37:23 -05008693ASTRecordReader::readCXXBaseSpecifier() {
8694 bool isVirtual = readBool();
8695 bool isBaseOfClass = readBool();
8696 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8697 bool inheritConstructors = readBool();
8698 TypeSourceInfo *TInfo = readTypeSourceInfo();
8699 SourceRange Range = readSourceRange();
8700 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008701 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008702 EllipsisLoc);
8703 Result.setInheritConstructors(inheritConstructors);
8704 return Result;
8705}
8706
Richard Smithc2bb8182015-03-24 06:36:48 +00008707CXXCtorInitializer **
John McCall3ce3d232019-12-13 03:37:23 -05008708ASTRecordReader::readCXXCtorInitializers() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008709 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008710 unsigned NumInitializers = readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008711 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008712 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008713 for (unsigned i = 0; i != NumInitializers; ++i) {
8714 TypeSourceInfo *TInfo = nullptr;
8715 bool IsBaseVirtual = false;
8716 FieldDecl *Member = nullptr;
8717 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008718
John McCall3ce3d232019-12-13 03:37:23 -05008719 CtorInitializerType Type = (CtorInitializerType) readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008720 switch (Type) {
8721 case CTOR_INITIALIZER_BASE:
John McCall3ce3d232019-12-13 03:37:23 -05008722 TInfo = readTypeSourceInfo();
8723 IsBaseVirtual = readBool();
Richard Smithc2bb8182015-03-24 06:36:48 +00008724 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008725
Richard Smithc2bb8182015-03-24 06:36:48 +00008726 case CTOR_INITIALIZER_DELEGATING:
John McCall3ce3d232019-12-13 03:37:23 -05008727 TInfo = readTypeSourceInfo();
Richard Smithc2bb8182015-03-24 06:36:48 +00008728 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008729
Richard Smithc2bb8182015-03-24 06:36:48 +00008730 case CTOR_INITIALIZER_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008731 Member = readDeclAs<FieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008732 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008733
Richard Smithc2bb8182015-03-24 06:36:48 +00008734 case CTOR_INITIALIZER_INDIRECT_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008735 IndirectMember = readDeclAs<IndirectFieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008736 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008738
John McCall3ce3d232019-12-13 03:37:23 -05008739 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8740 Expr *Init = readExpr();
8741 SourceLocation LParenLoc = readSourceLocation();
8742 SourceLocation RParenLoc = readSourceLocation();
Richard Smithc2bb8182015-03-24 06:36:48 +00008743
8744 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008745 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008746 BOMInit = new (Context)
8747 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8748 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008749 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008750 BOMInit = new (Context)
8751 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008752 else if (Member)
8753 BOMInit = new (Context)
8754 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8755 Init, RParenLoc);
8756 else
8757 BOMInit = new (Context)
8758 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8759 LParenLoc, Init, RParenLoc);
8760
John McCall3ce3d232019-12-13 03:37:23 -05008761 if (/*IsWritten*/readBool()) {
8762 unsigned SourceOrder = readInt();
Richard Smith30e304e2016-12-14 00:03:17 +00008763 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008764 }
8765
Richard Smithc2bb8182015-03-24 06:36:48 +00008766 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008767 }
8768
Richard Smithc2bb8182015-03-24 06:36:48 +00008769 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008770}
8771
Guy Benyei11169dd2012-12-18 14:30:41 +00008772NestedNameSpecifierLoc
John McCall3ce3d232019-12-13 03:37:23 -05008773ASTRecordReader::readNestedNameSpecifierLoc() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008774 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008775 unsigned N = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008776 NestedNameSpecifierLocBuilder Builder;
8777 for (unsigned I = 0; I != N; ++I) {
John McCalld505e572019-12-13 21:54:44 -05008778 auto Kind = readNestedNameSpecifierKind();
Guy Benyei11169dd2012-12-18 14:30:41 +00008779 switch (Kind) {
8780 case NestedNameSpecifier::Identifier: {
John McCall3ce3d232019-12-13 03:37:23 -05008781 IdentifierInfo *II = readIdentifier();
8782 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8784 break;
8785 }
8786
8787 case NestedNameSpecifier::Namespace: {
John McCall3ce3d232019-12-13 03:37:23 -05008788 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8789 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008790 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8791 break;
8792 }
8793
8794 case NestedNameSpecifier::NamespaceAlias: {
John McCall3ce3d232019-12-13 03:37:23 -05008795 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8796 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008797 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8798 break;
8799 }
8800
8801 case NestedNameSpecifier::TypeSpec:
8802 case NestedNameSpecifier::TypeSpecWithTemplate: {
John McCall3ce3d232019-12-13 03:37:23 -05008803 bool Template = readBool();
8804 TypeSourceInfo *T = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008805 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008806 return NestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -05008807 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008808
8809 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008810 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8812 T->getTypeLoc(), ColonColonLoc);
8813 break;
8814 }
8815
8816 case NestedNameSpecifier::Global: {
John McCall3ce3d232019-12-13 03:37:23 -05008817 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008818 Builder.MakeGlobal(Context, ColonColonLoc);
8819 break;
8820 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008821
8822 case NestedNameSpecifier::Super: {
John McCall3ce3d232019-12-13 03:37:23 -05008823 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8824 SourceRange Range = readSourceRange();
Nikola Smiljanic67860242014-09-26 00:28:20 +00008825 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8826 break;
8827 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008828 }
8829 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008830
Guy Benyei11169dd2012-12-18 14:30:41 +00008831 return Builder.getWithLocInContext(Context);
8832}
8833
8834SourceRange
8835ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8836 unsigned &Idx) {
8837 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8838 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8839 return SourceRange(beg, end);
8840}
8841
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008842static FixedPointSemantics
8843ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8844 unsigned &Idx) {
8845 unsigned Width = Record[Idx++];
8846 unsigned Scale = Record[Idx++];
8847 uint64_t Tmp = Record[Idx++];
8848 bool IsSigned = Tmp & 0x1;
8849 bool IsSaturated = Tmp & 0x2;
8850 bool HasUnsignedPadding = Tmp & 0x4;
8851 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8852 HasUnsignedPadding);
8853}
8854
John McCall3ce3d232019-12-13 03:37:23 -05008855static const llvm::fltSemantics &
8856readAPFloatSemantics(ASTRecordReader &reader) {
8857 return llvm::APFloatBase::EnumToSemantics(
8858 static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8859}
8860
8861APValue ASTRecordReader::readAPValue() {
8862 unsigned Kind = readInt();
John McCalld505e572019-12-13 21:54:44 -05008863 switch ((APValue::ValueKind) Kind) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008864 case APValue::None:
8865 return APValue();
8866 case APValue::Indeterminate:
8867 return APValue::IndeterminateValue();
8868 case APValue::Int:
John McCall3ce3d232019-12-13 03:37:23 -05008869 return APValue(readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008870 case APValue::Float: {
John McCall3ce3d232019-12-13 03:37:23 -05008871 const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8872 return APValue(readAPFloat(FloatSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008873 }
8874 case APValue::FixedPoint: {
8875 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
John McCall3ce3d232019-12-13 03:37:23 -05008876 return APValue(APFixedPoint(readAPInt(), FPSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008877 }
8878 case APValue::ComplexInt: {
John McCall3ce3d232019-12-13 03:37:23 -05008879 llvm::APSInt First = readAPSInt();
8880 return APValue(std::move(First), readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008881 }
8882 case APValue::ComplexFloat: {
John McCall3ce3d232019-12-13 03:37:23 -05008883 const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8884 llvm::APFloat First = readAPFloat(FloatSema1);
8885 const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8886 return APValue(std::move(First), readAPFloat(FloatSema2));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008887 }
8888 case APValue::LValue:
8889 case APValue::Vector:
8890 case APValue::Array:
8891 case APValue::Struct:
8892 case APValue::Union:
8893 case APValue::MemberPointer:
8894 case APValue::AddrLabelDiff:
8895 // TODO : Handle all these APValue::ValueKind.
8896 return APValue();
8897 }
8898 llvm_unreachable("Invalid APValue::ValueKind");
8899}
8900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008901/// Read a floating-point value
John McCall3ce3d232019-12-13 03:37:23 -05008902llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8903 return llvm::APFloat(Sem, readAPInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00008904}
8905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008906// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008907std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8908 unsigned Len = Record[Idx++];
8909 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8910 Idx += Len;
8911 return Result;
8912}
8913
Richard Smith7ed1bc92014-12-05 22:42:13 +00008914std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8915 unsigned &Idx) {
8916 std::string Filename = ReadString(Record, Idx);
8917 ResolveImportedPath(F, Filename);
8918 return Filename;
8919}
8920
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00008921std::string ASTReader::ReadPath(StringRef BaseDirectory,
8922 const RecordData &Record, unsigned &Idx) {
8923 std::string Filename = ReadString(Record, Idx);
8924 if (!BaseDirectory.empty())
8925 ResolveImportedPath(Filename, BaseDirectory);
8926 return Filename;
8927}
8928
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008929VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008930 unsigned &Idx) {
8931 unsigned Major = Record[Idx++];
8932 unsigned Minor = Record[Idx++];
8933 unsigned Subminor = Record[Idx++];
8934 if (Minor == 0)
8935 return VersionTuple(Major);
8936 if (Subminor == 0)
8937 return VersionTuple(Major, Minor - 1);
8938 return VersionTuple(Major, Minor - 1, Subminor - 1);
8939}
8940
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008941CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008942 const RecordData &Record,
8943 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008944 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008945 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008946}
8947
Richard Smith37a93df2017-02-18 00:32:02 +00008948DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008949 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008950}
8951
Richard Smith37a93df2017-02-18 00:32:02 +00008952DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008953 return Diags.Report(Loc, DiagID);
8954}
8955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008956/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00008957/// preprocessor.
8958IdentifierTable &ASTReader::getIdentifierTable() {
8959 return PP.getIdentifierTable();
8960}
8961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008962/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00008963/// statement.
8964void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008965 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008966 "Already have a SwitchCase with this ID");
8967 (*CurrSwitchCaseStmts)[ID] = SC;
8968}
8969
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008970/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00008971SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008972 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008973 return (*CurrSwitchCaseStmts)[ID];
8974}
8975
8976void ASTReader::ClearSwitchCaseIDs() {
8977 CurrSwitchCaseStmts->clear();
8978}
8979
8980void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008981 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008982 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008983 for (SmallVectorImpl<std::pair<BitstreamCursor,
8984 serialization::ModuleFile *>>::iterator
8985 I = CommentsCursors.begin(),
8986 E = CommentsCursors.end();
8987 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008988 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008989 BitstreamCursor &Cursor = I->first;
8990 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00008991 SavedStreamPosition SavedPosition(Cursor);
8992
8993 RecordData Record;
8994 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00008995 Expected<llvm::BitstreamEntry> MaybeEntry =
8996 Cursor.advanceSkippingSubblocks(
8997 BitstreamCursor::AF_DontPopBlockAtEnd);
8998 if (!MaybeEntry) {
8999 Error(MaybeEntry.takeError());
9000 return;
9001 }
9002 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009003
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009004 switch (Entry.Kind) {
9005 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9006 case llvm::BitstreamEntry::Error:
9007 Error("malformed block record in AST file");
9008 return;
9009 case llvm::BitstreamEntry::EndBlock:
9010 goto NextCursor;
9011 case llvm::BitstreamEntry::Record:
9012 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009013 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009014 }
9015
9016 // Read a record.
9017 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009018 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9019 if (!MaybeComment) {
9020 Error(MaybeComment.takeError());
9021 return;
9022 }
9023 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009024 case COMMENTS_RAW_COMMENT: {
9025 unsigned Idx = 0;
9026 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009027 RawComment::CommentKind Kind =
9028 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009029 bool IsTrailingComment = Record[Idx++];
9030 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009031 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009032 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009033 break;
9034 }
9035 }
9036 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009037 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009038 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9039 FileToOffsetToComment;
9040 for (RawComment *C : Comments) {
9041 SourceLocation CommentLoc = C->getBeginLoc();
9042 if (CommentLoc.isValid()) {
9043 std::pair<FileID, unsigned> Loc =
9044 SourceMgr.getDecomposedLoc(CommentLoc);
9045 if (Loc.first.isValid())
9046 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9047 }
9048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009049 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009050}
9051
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009052void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9053 bool IncludeSystem, bool Complain,
9054 llvm::function_ref<void(const serialization::InputFile &IF,
9055 bool isSystem)> Visitor) {
9056 unsigned NumUserInputs = MF.NumUserInputFiles;
9057 unsigned NumInputs = MF.InputFilesLoaded.size();
9058 assert(NumUserInputs <= NumInputs);
9059 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9060 for (unsigned I = 0; I < N; ++I) {
9061 bool IsSystem = I >= NumUserInputs;
9062 InputFile IF = getInputFile(MF, I+1, Complain);
9063 Visitor(IF, IsSystem);
9064 }
9065}
9066
Richard Smithf3f84612017-06-29 02:19:42 +00009067void ASTReader::visitTopLevelModuleMaps(
9068 serialization::ModuleFile &MF,
9069 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9070 unsigned NumInputs = MF.InputFilesLoaded.size();
9071 for (unsigned I = 0; I < NumInputs; ++I) {
9072 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9073 if (IFI.TopLevelModuleMap)
9074 // FIXME: This unnecessarily re-reads the InputFileInfo.
9075 if (auto *FE = getInputFile(MF, I + 1).getFile())
9076 Visitor(FE);
9077 }
9078}
9079
Richard Smithcd45dbc2014-04-19 03:48:30 +00009080std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9081 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009082 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009083 return M->getFullModuleName();
9084
9085 // Otherwise, use the name of the top-level module the decl is within.
9086 if (ModuleFile *M = getOwningModuleFile(D))
9087 return M->ModuleName;
9088
9089 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009090 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009091}
9092
Guy Benyei11169dd2012-12-18 14:30:41 +00009093void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009094 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009095 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009096 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009097 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009098 // If any identifiers with corresponding top-level declarations have
9099 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009100 using TopLevelDeclsMap =
9101 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009102 TopLevelDeclsMap TopLevelDecls;
9103
Guy Benyei11169dd2012-12-18 14:30:41 +00009104 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009105 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009106 SmallVector<uint32_t, 4> DeclIDs =
9107 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009108 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009109
9110 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009111 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009112
Richard Smitha62d1982018-08-03 01:00:01 +00009113 // Load each function type that we deferred loading because it was a
9114 // deduced type that might refer to a local type declared within itself.
9115 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9116 auto *FD = PendingFunctionTypes[I].first;
9117 FD->setType(GetType(PendingFunctionTypes[I].second));
9118
9119 // If we gave a function a deduced return type, remember that we need to
9120 // propagate that along the redeclaration chain.
9121 auto *DT = FD->getReturnType()->getContainedDeducedType();
9122 if (DT && DT->isDeduced())
9123 PendingDeducedTypeUpdates.insert(
9124 {FD->getCanonicalDecl(), FD->getReturnType()});
9125 }
9126 PendingFunctionTypes.clear();
9127
Richard Smith851072e2014-05-19 20:59:20 +00009128 // For each decl chain that we wanted to complete while deserializing, mark
9129 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009130 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9131 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9132 }
Richard Smith851072e2014-05-19 20:59:20 +00009133 PendingIncompleteDeclChains.clear();
9134
Guy Benyei11169dd2012-12-18 14:30:41 +00009135 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009136 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009137 loadPendingDeclChain(PendingDeclChains[I].first,
9138 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009139 PendingDeclChains.clear();
9140
Douglas Gregor6168bd22013-02-18 15:53:43 +00009141 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009142 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9143 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9144 IdentifierInfo *II = TLD->first;
9145 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9146 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009147 }
9148 }
9149
Guy Benyei11169dd2012-12-18 14:30:41 +00009150 // Load any pending macro definitions.
9151 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009152 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9153 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9154 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9155 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009156 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009157 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009158 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009159 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009160 resolvePendingMacro(II, Info);
9161 }
9162 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009163 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009164 ++IDIdx) {
9165 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009166 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009167 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009168 }
9169 }
9170 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009171
9172 // Wire up the DeclContexts for Decls that we delayed setting until
9173 // recursive loading is completed.
9174 while (!PendingDeclContextInfos.empty()) {
9175 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9176 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009177 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9178 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009179 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9180 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009181
Richard Smithd1c46742014-04-30 02:24:17 +00009182 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009183 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009184 auto Update = PendingUpdateRecords.pop_back_val();
9185 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009186 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009188 }
Richard Smith8a639892015-01-24 01:07:20 +00009189
9190 // At this point, all update records for loaded decls are in place, so any
9191 // fake class definitions should have become real.
9192 assert(PendingFakeDefinitionData.empty() &&
9193 "faked up a class definition but never saw the real one");
9194
Guy Benyei11169dd2012-12-18 14:30:41 +00009195 // If we deserialized any C++ or Objective-C class definitions, any
9196 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009197 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009198 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009199 for (Decl *D : PendingDefinitions) {
9200 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9201 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009202 // Make sure that the TagType points at the definition.
9203 const_cast<TagType*>(TagT)->decl = TD;
9204 }
Richard Smith8ce51082015-03-11 01:44:51 +00009205
Vedant Kumar48b4f762018-04-14 01:40:48 +00009206 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009207 for (auto *R = getMostRecentExistingDecl(RD); R;
9208 R = R->getPreviousDecl()) {
9209 assert((R == D) ==
9210 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009211 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009212 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009214 }
9215
9216 continue;
9217 }
Richard Smith8ce51082015-03-11 01:44:51 +00009218
Vedant Kumar48b4f762018-04-14 01:40:48 +00009219 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009220 // Make sure that the ObjCInterfaceType points at the definition.
9221 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9222 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009223
9224 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9225 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9226
Guy Benyei11169dd2012-12-18 14:30:41 +00009227 continue;
9228 }
Richard Smith8ce51082015-03-11 01:44:51 +00009229
Vedant Kumar48b4f762018-04-14 01:40:48 +00009230 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009231 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9232 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9233
Guy Benyei11169dd2012-12-18 14:30:41 +00009234 continue;
9235 }
Richard Smith8ce51082015-03-11 01:44:51 +00009236
Vedant Kumar48b4f762018-04-14 01:40:48 +00009237 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009238 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9239 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009240 }
9241 PendingDefinitions.clear();
9242
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009243 // Load the bodies of any functions or methods we've encountered. We do
9244 // this now (delayed) so that we can be sure that the declaration chains
9245 // have been fully wired up (hasBody relies on this).
9246 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009247 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9248 PBEnd = PendingBodies.end();
9249 PB != PBEnd; ++PB) {
9250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009251 // For a function defined inline within a class template, force the
9252 // canonical definition to be the one inside the canonical definition of
9253 // the template. This ensures that we instantiate from a correct view
9254 // of the template.
9255 //
9256 // Sadly we can't do this more generally: we can't be sure that all
9257 // copies of an arbitrary class definition will have the same members
9258 // defined (eg, some member functions may not be instantiated, and some
9259 // special members may or may not have been implicitly defined).
9260 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9261 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9262 continue;
9263
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009264 // FIXME: Check for =delete/=default?
9265 // FIXME: Complain about ODR violations here?
9266 const FunctionDecl *Defn = nullptr;
9267 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009268 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009269 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009270 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009271 mergeDefinitionVisibility(NonConstDefn, FD);
9272
9273 if (!FD->isLateTemplateParsed() &&
9274 !NonConstDefn->isLateTemplateParsed() &&
9275 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009276 if (!isa<CXXMethodDecl>(FD)) {
9277 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9278 } else if (FD->getLexicalParent()->isFileContext() &&
9279 NonConstDefn->getLexicalParent()->isFileContext()) {
9280 // Only diagnose out-of-line method definitions. If they are
9281 // in class definitions, then an error will be generated when
9282 // processing the class bodies.
9283 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9284 }
Richard Trieue6caa262017-12-23 00:41:01 +00009285 }
9286 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009287 continue;
9288 }
9289
Vedant Kumar48b4f762018-04-14 01:40:48 +00009290 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009291 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009292 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009293 }
9294 PendingBodies.clear();
9295
Richard Smith42413142015-05-15 20:05:43 +00009296 // Do some cleanup.
9297 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9298 getContext().deduplicateMergedDefinitonsFor(ND);
9299 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009300}
9301
9302void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009303 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009304 PendingFunctionOdrMergeFailures.empty() &&
9305 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009306 return;
9307
Richard Smitha0ce9c42014-07-29 23:23:27 +00009308 // Trigger the import of the full definition of each class that had any
9309 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009310 // These updates may in turn find and diagnose some ODR failures, so take
9311 // ownership of the set first.
9312 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9313 PendingOdrMergeFailures.clear();
9314 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009315 Merge.first->buildLookup();
9316 Merge.first->decls_begin();
9317 Merge.first->bases_begin();
9318 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009319 for (auto &RecordPair : Merge.second) {
9320 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009321 RD->decls_begin();
9322 RD->bases_begin();
9323 RD->vbases_begin();
9324 }
9325 }
9326
Richard Trieue6caa262017-12-23 00:41:01 +00009327 // Trigger the import of functions.
9328 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9329 PendingFunctionOdrMergeFailures.clear();
9330 for (auto &Merge : FunctionOdrMergeFailures) {
9331 Merge.first->buildLookup();
9332 Merge.first->decls_begin();
9333 Merge.first->getBody();
9334 for (auto &FD : Merge.second) {
9335 FD->buildLookup();
9336 FD->decls_begin();
9337 FD->getBody();
9338 }
9339 }
9340
Richard Trieuab4d7302018-07-25 22:52:05 +00009341 // Trigger the import of enums.
9342 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9343 PendingEnumOdrMergeFailures.clear();
9344 for (auto &Merge : EnumOdrMergeFailures) {
9345 Merge.first->decls_begin();
9346 for (auto &Enum : Merge.second) {
9347 Enum->decls_begin();
9348 }
9349 }
9350
Richard Smitha0ce9c42014-07-29 23:23:27 +00009351 // For each declaration from a merged context, check that the canonical
9352 // definition of that context also contains a declaration of the same
9353 // entity.
9354 //
9355 // Caution: this loop does things that might invalidate iterators into
9356 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9357 while (!PendingOdrMergeChecks.empty()) {
9358 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9359
9360 // FIXME: Skip over implicit declarations for now. This matters for things
9361 // like implicitly-declared special member functions. This isn't entirely
9362 // correct; we can end up with multiple unmerged declarations of the same
9363 // implicit entity.
9364 if (D->isImplicit())
9365 continue;
9366
9367 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009368
9369 bool Found = false;
9370 const Decl *DCanon = D->getCanonicalDecl();
9371
Richard Smith01bdb7a2014-08-28 05:44:07 +00009372 for (auto RI : D->redecls()) {
9373 if (RI->getLexicalDeclContext() == CanonDef) {
9374 Found = true;
9375 break;
9376 }
9377 }
9378 if (Found)
9379 continue;
9380
Richard Smith0f4e2c42015-08-06 04:23:48 +00009381 // Quick check failed, time to do the slow thing. Note, we can't just
9382 // look up the name of D in CanonDef here, because the member that is
9383 // in CanonDef might not be found by name lookup (it might have been
9384 // replaced by a more recent declaration in the lookup table), and we
9385 // can't necessarily find it in the redeclaration chain because it might
9386 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009387 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009388 for (auto *CanonMember : CanonDef->decls()) {
9389 if (CanonMember->getCanonicalDecl() == DCanon) {
9390 // This can happen if the declaration is merely mergeable and not
9391 // actually redeclarable (we looked for redeclarations earlier).
9392 //
9393 // FIXME: We should be able to detect this more efficiently, without
9394 // pulling in all of the members of CanonDef.
9395 Found = true;
9396 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009397 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009398 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9399 if (ND->getDeclName() == D->getDeclName())
9400 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009401 }
9402
9403 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009404 // The AST doesn't like TagDecls becoming invalid after they've been
9405 // completed. We only really need to mark FieldDecls as invalid here.
9406 if (!isa<TagDecl>(D))
9407 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009408
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009409 // Ensure we don't accidentally recursively enter deserialization while
9410 // we're producing our diagnostic.
9411 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009412
9413 std::string CanonDefModule =
9414 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9415 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9416 << D << getOwningModuleNameForDiagnostic(D)
9417 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9418
9419 if (Candidates.empty())
9420 Diag(cast<Decl>(CanonDef)->getLocation(),
9421 diag::note_module_odr_violation_no_possible_decls) << D;
9422 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009423 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9424 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009425 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009426 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009427 }
9428
9429 DiagnosedOdrMergeFailures.insert(CanonDef);
9430 }
9431 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009432
Richard Trieuab4d7302018-07-25 22:52:05 +00009433 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9434 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009435 return;
9436
9437 // Ensure we don't accidentally recursively enter deserialization while
9438 // we're producing our diagnostics.
9439 Deserializing RecursionGuard(this);
9440
Richard Trieue6caa262017-12-23 00:41:01 +00009441 // Common code for hashing helpers.
9442 ODRHash Hash;
9443 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9444 Hash.clear();
9445 Hash.AddQualType(Ty);
9446 return Hash.CalculateHash();
9447 };
9448
9449 auto ComputeODRHash = [&Hash](const Stmt *S) {
9450 assert(S);
9451 Hash.clear();
9452 Hash.AddStmt(S);
9453 return Hash.CalculateHash();
9454 };
9455
9456 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9457 assert(D);
9458 Hash.clear();
9459 Hash.AddSubDecl(D);
9460 return Hash.CalculateHash();
9461 };
9462
Richard Trieu7282d322018-04-25 00:31:15 +00009463 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9464 Hash.clear();
9465 Hash.AddTemplateArgument(TA);
9466 return Hash.CalculateHash();
9467 };
9468
Richard Trieu9359e8f2018-05-30 01:12:26 +00009469 auto ComputeTemplateParameterListODRHash =
9470 [&Hash](const TemplateParameterList *TPL) {
9471 assert(TPL);
9472 Hash.clear();
9473 Hash.AddTemplateParameterList(TPL);
9474 return Hash.CalculateHash();
9475 };
9476
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009477 // Used with err_module_odr_violation_mismatch_decl and
9478 // note_module_odr_violation_mismatch_decl
9479 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9480 enum ODRMismatchDecl {
9481 EndOfClass,
9482 PublicSpecifer,
9483 PrivateSpecifer,
9484 ProtectedSpecifer,
9485 StaticAssert,
9486 Field,
9487 CXXMethod,
9488 TypeAlias,
9489 TypeDef,
9490 Var,
9491 Friend,
9492 FunctionTemplate,
9493 Other
9494 };
9495
9496 // Used with err_module_odr_violation_mismatch_decl_diff and
9497 // note_module_odr_violation_mismatch_decl_diff
9498 enum ODRMismatchDeclDifference {
9499 StaticAssertCondition,
9500 StaticAssertMessage,
9501 StaticAssertOnlyMessage,
9502 FieldName,
9503 FieldTypeName,
9504 FieldSingleBitField,
9505 FieldDifferentWidthBitField,
9506 FieldSingleMutable,
9507 FieldSingleInitializer,
9508 FieldDifferentInitializers,
9509 MethodName,
9510 MethodDeleted,
9511 MethodDefaulted,
9512 MethodVirtual,
9513 MethodStatic,
9514 MethodVolatile,
9515 MethodConst,
9516 MethodInline,
9517 MethodNumberParameters,
9518 MethodParameterType,
9519 MethodParameterName,
9520 MethodParameterSingleDefaultArgument,
9521 MethodParameterDifferentDefaultArgument,
9522 MethodNoTemplateArguments,
9523 MethodDifferentNumberTemplateArguments,
9524 MethodDifferentTemplateArgument,
9525 MethodSingleBody,
9526 MethodDifferentBody,
9527 TypedefName,
9528 TypedefType,
9529 VarName,
9530 VarType,
9531 VarSingleInitializer,
9532 VarDifferentInitializer,
9533 VarConstexpr,
9534 FriendTypeFunction,
9535 FriendType,
9536 FriendFunction,
9537 FunctionTemplateDifferentNumberParameters,
9538 FunctionTemplateParameterDifferentKind,
9539 FunctionTemplateParameterName,
9540 FunctionTemplateParameterSingleDefaultArgument,
9541 FunctionTemplateParameterDifferentDefaultArgument,
9542 FunctionTemplateParameterDifferentType,
9543 FunctionTemplatePackParameter,
9544 };
9545
9546 // These lambdas have the common portions of the ODR diagnostics. This
9547 // has the same return as Diag(), so addition parameters can be passed
9548 // in with operator<<
9549 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule,
9550 SourceLocation Loc, SourceRange Range,
9551 ODRMismatchDeclDifference DiffType) {
9552 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9553 << FirstRecord << FirstModule.empty() << FirstModule << Range
9554 << DiffType;
9555 };
9556 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc,
9557 SourceRange Range, ODRMismatchDeclDifference DiffType) {
9558 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9559 << SecondModule << Range << DiffType;
9560 };
9561
9562 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote,
9563 &ComputeQualTypeODRHash, &ComputeODRHash](
9564 NamedDecl *FirstRecord, StringRef FirstModule,
9565 StringRef SecondModule, FieldDecl *FirstField,
9566 FieldDecl *SecondField) {
9567 IdentifierInfo *FirstII = FirstField->getIdentifier();
9568 IdentifierInfo *SecondII = SecondField->getIdentifier();
9569 if (FirstII->getName() != SecondII->getName()) {
9570 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9571 FirstField->getSourceRange(), FieldName)
9572 << FirstII;
9573 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9574 SecondField->getSourceRange(), FieldName)
9575 << SecondII;
9576
9577 return true;
9578 }
9579
9580 assert(getContext().hasSameType(FirstField->getType(),
9581 SecondField->getType()));
9582
9583 QualType FirstType = FirstField->getType();
9584 QualType SecondType = SecondField->getType();
9585 if (ComputeQualTypeODRHash(FirstType) !=
9586 ComputeQualTypeODRHash(SecondType)) {
9587 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9588 FirstField->getSourceRange(), FieldTypeName)
9589 << FirstII << FirstType;
9590 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9591 SecondField->getSourceRange(), FieldTypeName)
9592 << SecondII << SecondType;
9593
9594 return true;
9595 }
9596
9597 const bool IsFirstBitField = FirstField->isBitField();
9598 const bool IsSecondBitField = SecondField->isBitField();
9599 if (IsFirstBitField != IsSecondBitField) {
9600 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9601 FirstField->getSourceRange(), FieldSingleBitField)
9602 << FirstII << IsFirstBitField;
9603 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9604 SecondField->getSourceRange(), FieldSingleBitField)
9605 << SecondII << IsSecondBitField;
9606 return true;
9607 }
9608
9609 if (IsFirstBitField && IsSecondBitField) {
9610 unsigned FirstBitWidthHash =
9611 ComputeODRHash(FirstField->getBitWidth());
9612 unsigned SecondBitWidthHash =
9613 ComputeODRHash(SecondField->getBitWidth());
9614 if (FirstBitWidthHash != SecondBitWidthHash) {
9615 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9616 FirstField->getSourceRange(),
9617 FieldDifferentWidthBitField)
9618 << FirstII << FirstField->getBitWidth()->getSourceRange();
9619 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9620 SecondField->getSourceRange(),
9621 FieldDifferentWidthBitField)
9622 << SecondII << SecondField->getBitWidth()->getSourceRange();
9623 return true;
9624 }
9625 }
9626
9627 if (!PP.getLangOpts().CPlusPlus)
9628 return false;
9629
9630 const bool IsFirstMutable = FirstField->isMutable();
9631 const bool IsSecondMutable = SecondField->isMutable();
9632 if (IsFirstMutable != IsSecondMutable) {
9633 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9634 FirstField->getSourceRange(), FieldSingleMutable)
9635 << FirstII << IsFirstMutable;
9636 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9637 SecondField->getSourceRange(), FieldSingleMutable)
9638 << SecondII << IsSecondMutable;
9639 return true;
9640 }
9641
9642 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9643 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9644 if ((!FirstInitializer && SecondInitializer) ||
9645 (FirstInitializer && !SecondInitializer)) {
9646 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9647 FirstField->getSourceRange(), FieldSingleInitializer)
9648 << FirstII << (FirstInitializer != nullptr);
9649 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9650 SecondField->getSourceRange(), FieldSingleInitializer)
9651 << SecondII << (SecondInitializer != nullptr);
9652 return true;
9653 }
9654
9655 if (FirstInitializer && SecondInitializer) {
9656 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9657 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9658 if (FirstInitHash != SecondInitHash) {
9659 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9660 FirstField->getSourceRange(),
9661 FieldDifferentInitializers)
9662 << FirstII << FirstInitializer->getSourceRange();
9663 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9664 SecondField->getSourceRange(),
9665 FieldDifferentInitializers)
9666 << SecondII << SecondInitializer->getSourceRange();
9667 return true;
9668 }
9669 }
9670
9671 return false;
9672 };
9673
9674 auto ODRDiagTypeDefOrAlias =
9675 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash](
9676 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
9677 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
9678 bool IsTypeAlias) {
9679 auto FirstName = FirstTD->getDeclName();
9680 auto SecondName = SecondTD->getDeclName();
9681 if (FirstName != SecondName) {
9682 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9683 FirstTD->getSourceRange(), TypedefName)
9684 << IsTypeAlias << FirstName;
9685 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9686 SecondTD->getSourceRange(), TypedefName)
9687 << IsTypeAlias << SecondName;
9688 return true;
9689 }
9690
9691 QualType FirstType = FirstTD->getUnderlyingType();
9692 QualType SecondType = SecondTD->getUnderlyingType();
9693 if (ComputeQualTypeODRHash(FirstType) !=
9694 ComputeQualTypeODRHash(SecondType)) {
9695 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9696 FirstTD->getSourceRange(), TypedefType)
9697 << IsTypeAlias << FirstName << FirstType;
9698 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9699 SecondTD->getSourceRange(), TypedefType)
9700 << IsTypeAlias << SecondName << SecondType;
9701 return true;
9702 }
9703
9704 return false;
9705 };
9706
9707 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote,
9708 &ComputeQualTypeODRHash, &ComputeODRHash,
9709 this](NamedDecl *FirstRecord, StringRef FirstModule,
9710 StringRef SecondModule, VarDecl *FirstVD,
9711 VarDecl *SecondVD) {
9712 auto FirstName = FirstVD->getDeclName();
9713 auto SecondName = SecondVD->getDeclName();
9714 if (FirstName != SecondName) {
9715 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9716 FirstVD->getSourceRange(), VarName)
9717 << FirstName;
9718 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9719 SecondVD->getSourceRange(), VarName)
9720 << SecondName;
9721 return true;
9722 }
9723
9724 QualType FirstType = FirstVD->getType();
9725 QualType SecondType = SecondVD->getType();
9726 if (ComputeQualTypeODRHash(FirstType) !=
9727 ComputeQualTypeODRHash(SecondType)) {
9728 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9729 FirstVD->getSourceRange(), VarType)
9730 << FirstName << FirstType;
9731 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9732 SecondVD->getSourceRange(), VarType)
9733 << SecondName << SecondType;
9734 return true;
9735 }
9736
9737 if (!PP.getLangOpts().CPlusPlus)
9738 return false;
9739
9740 const Expr *FirstInit = FirstVD->getInit();
9741 const Expr *SecondInit = SecondVD->getInit();
9742 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
9743 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9744 FirstVD->getSourceRange(), VarSingleInitializer)
9745 << FirstName << (FirstInit == nullptr)
9746 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
9747 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9748 SecondVD->getSourceRange(), VarSingleInitializer)
9749 << SecondName << (SecondInit == nullptr)
9750 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
9751 return true;
9752 }
9753
9754 if (FirstInit && SecondInit &&
9755 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
9756 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9757 FirstVD->getSourceRange(), VarDifferentInitializer)
9758 << FirstName << FirstInit->getSourceRange();
9759 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9760 SecondVD->getSourceRange(), VarDifferentInitializer)
9761 << SecondName << SecondInit->getSourceRange();
9762 return true;
9763 }
9764
9765 const bool FirstIsConstexpr = FirstVD->isConstexpr();
9766 const bool SecondIsConstexpr = SecondVD->isConstexpr();
9767 if (FirstIsConstexpr != SecondIsConstexpr) {
9768 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9769 FirstVD->getSourceRange(), VarConstexpr)
9770 << FirstName << FirstIsConstexpr;
9771 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9772 SecondVD->getSourceRange(), VarConstexpr)
9773 << SecondName << SecondIsConstexpr;
9774 return true;
9775 }
9776 return false;
9777 };
9778
9779 auto DifferenceSelector = [](Decl *D) {
9780 assert(D && "valid Decl required");
9781 switch (D->getKind()) {
9782 default:
9783 return Other;
9784 case Decl::AccessSpec:
9785 switch (D->getAccess()) {
9786 case AS_public:
9787 return PublicSpecifer;
9788 case AS_private:
9789 return PrivateSpecifer;
9790 case AS_protected:
9791 return ProtectedSpecifer;
9792 case AS_none:
9793 break;
9794 }
9795 llvm_unreachable("Invalid access specifier");
9796 case Decl::StaticAssert:
9797 return StaticAssert;
9798 case Decl::Field:
9799 return Field;
9800 case Decl::CXXMethod:
9801 case Decl::CXXConstructor:
9802 case Decl::CXXDestructor:
9803 return CXXMethod;
9804 case Decl::TypeAlias:
9805 return TypeAlias;
9806 case Decl::Typedef:
9807 return TypeDef;
9808 case Decl::Var:
9809 return Var;
9810 case Decl::Friend:
9811 return Friend;
9812 case Decl::FunctionTemplate:
9813 return FunctionTemplate;
9814 }
9815 };
9816
9817 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9818 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9819 RecordDecl *Record,
9820 const DeclContext *DC) {
9821 for (auto *D : Record->decls()) {
9822 if (!ODRHash::isWhitelistedDecl(D, DC))
9823 continue;
9824 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9825 }
9826 };
9827
9828 struct DiffResult {
9829 Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
9830 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
9831 };
9832
9833 // If there is a diagnoseable difference, FirstDiffType and
9834 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9835 // filled in if not EndOfClass.
9836 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
9837 DeclHashes &SecondHashes) {
9838 DiffResult DR;
9839 auto FirstIt = FirstHashes.begin();
9840 auto SecondIt = SecondHashes.begin();
9841 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9842 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9843 FirstIt->second == SecondIt->second) {
9844 ++FirstIt;
9845 ++SecondIt;
9846 continue;
9847 }
9848
9849 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9850 DR.SecondDecl =
9851 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9852
9853 DR.FirstDiffType =
9854 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
9855 DR.SecondDiffType =
9856 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
9857 return DR;
9858 }
9859 return DR;
9860 };
9861
9862 // Use this to diagnose that an unexpected Decl was encountered
9863 // or no difference was detected. This causes a generic error
9864 // message to be emitted.
9865 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
9866 StringRef FirstModule,
9867 NamedDecl *SecondRecord,
9868 StringRef SecondModule) {
9869 Diag(FirstRecord->getLocation(),
9870 diag::err_module_odr_violation_different_definitions)
9871 << FirstRecord << FirstModule.empty() << FirstModule;
9872
9873 if (DR.FirstDecl) {
9874 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
9875 << FirstRecord << DR.FirstDecl->getSourceRange();
9876 }
9877
9878 Diag(SecondRecord->getLocation(),
9879 diag::note_module_odr_violation_different_definitions)
9880 << SecondModule;
9881
9882 if (DR.SecondDecl) {
9883 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
9884 << DR.SecondDecl->getSourceRange();
9885 }
9886 };
9887
9888 auto DiagnoseODRMismatch =
9889 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule,
9890 NamedDecl *SecondRecord, StringRef SecondModule) {
9891 SourceLocation FirstLoc;
9892 SourceRange FirstRange;
9893 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord);
9894 if (DR.FirstDiffType == EndOfClass && FirstTag) {
9895 FirstLoc = FirstTag->getBraceRange().getEnd();
9896 } else {
9897 FirstLoc = DR.FirstDecl->getLocation();
9898 FirstRange = DR.FirstDecl->getSourceRange();
9899 }
9900 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9901 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9902 << DR.FirstDiffType;
9903
9904 SourceLocation SecondLoc;
9905 SourceRange SecondRange;
9906 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord);
9907 if (DR.SecondDiffType == EndOfClass && SecondTag) {
9908 SecondLoc = SecondTag->getBraceRange().getEnd();
9909 } else {
9910 SecondLoc = DR.SecondDecl->getLocation();
9911 SecondRange = DR.SecondDecl->getSourceRange();
9912 }
9913 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9914 << SecondModule << SecondRange << DR.SecondDiffType;
9915 };
9916
Richard Smithcd45dbc2014-04-19 03:48:30 +00009917 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009918 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009919 // If we've already pointed out a specific problem with this class, don't
9920 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009921 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009922 continue;
9923
9924 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009925 CXXRecordDecl *FirstRecord = Merge.first;
9926 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009927 for (auto &RecordPair : Merge.second) {
9928 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009929 // Multiple different declarations got merged together; tell the user
9930 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009931 if (FirstRecord == SecondRecord)
9932 continue;
9933
9934 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009935
9936 auto *FirstDD = FirstRecord->DefinitionData;
9937 auto *SecondDD = RecordPair.second;
9938
9939 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9940
9941 // Diagnostics from DefinitionData are emitted here.
9942 if (FirstDD != SecondDD) {
9943 enum ODRDefinitionDataDifference {
9944 NumBases,
9945 NumVBases,
9946 BaseType,
9947 BaseVirtual,
9948 BaseAccess,
9949 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009950 auto ODRDiagBaseError = [FirstRecord, &FirstModule,
9951 this](SourceLocation Loc, SourceRange Range,
9952 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +00009953 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9954 << FirstRecord << FirstModule.empty() << FirstModule << Range
9955 << DiffType;
9956 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009957 auto ODRDiagBaseNote = [&SecondModule,
9958 this](SourceLocation Loc, SourceRange Range,
9959 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +00009960 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9961 << SecondModule << Range << DiffType;
9962 };
9963
Richard Trieue13eabe2017-09-30 02:19:17 +00009964 unsigned FirstNumBases = FirstDD->NumBases;
9965 unsigned FirstNumVBases = FirstDD->NumVBases;
9966 unsigned SecondNumBases = SecondDD->NumBases;
9967 unsigned SecondNumVBases = SecondDD->NumVBases;
9968
9969 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9970 unsigned NumBases = DD->NumBases;
9971 if (NumBases == 0) return SourceRange();
9972 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009973 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009974 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009975 };
9976
9977 if (FirstNumBases != SecondNumBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009978 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9979 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009980 << FirstNumBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009981 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9982 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009983 << SecondNumBases;
9984 Diagnosed = true;
9985 break;
9986 }
9987
9988 if (FirstNumVBases != SecondNumVBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009989 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9990 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009991 << FirstNumVBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009992 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9993 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009994 << SecondNumVBases;
9995 Diagnosed = true;
9996 break;
9997 }
9998
9999 auto FirstBases = FirstDD->bases();
10000 auto SecondBases = SecondDD->bases();
10001 unsigned i = 0;
10002 for (i = 0; i < FirstNumBases; ++i) {
10003 auto FirstBase = FirstBases[i];
10004 auto SecondBase = SecondBases[i];
10005 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10006 ComputeQualTypeODRHash(SecondBase.getType())) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010007 ODRDiagBaseError(FirstRecord->getLocation(),
10008 FirstBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +000010009 << (i + 1) << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010010 ODRDiagBaseNote(SecondRecord->getLocation(),
10011 SecondBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +000010012 << (i + 1) << SecondBase.getType();
10013 break;
10014 }
10015
10016 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010017 ODRDiagBaseError(FirstRecord->getLocation(),
10018 FirstBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +000010019 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010020 ODRDiagBaseNote(SecondRecord->getLocation(),
10021 SecondBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +000010022 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10023 break;
10024 }
10025
10026 if (FirstBase.getAccessSpecifierAsWritten() !=
10027 SecondBase.getAccessSpecifierAsWritten()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010028 ODRDiagBaseError(FirstRecord->getLocation(),
10029 FirstBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010030 << (i + 1) << FirstBase.getType()
10031 << (int)FirstBase.getAccessSpecifierAsWritten();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010032 ODRDiagBaseNote(SecondRecord->getLocation(),
10033 SecondBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010034 << (i + 1) << SecondBase.getType()
10035 << (int)SecondBase.getAccessSpecifierAsWritten();
10036 break;
10037 }
10038 }
10039
10040 if (i != FirstNumBases) {
10041 Diagnosed = true;
10042 break;
10043 }
10044 }
10045
Richard Trieu498117b2017-08-23 02:43:59 +000010046 const ClassTemplateDecl *FirstTemplate =
10047 FirstRecord->getDescribedClassTemplate();
10048 const ClassTemplateDecl *SecondTemplate =
10049 SecondRecord->getDescribedClassTemplate();
10050
10051 assert(!FirstTemplate == !SecondTemplate &&
10052 "Both pointers should be null or non-null");
10053
10054 enum ODRTemplateDifference {
10055 ParamEmptyName,
10056 ParamName,
10057 ParamSingleDefaultArgument,
10058 ParamDifferentDefaultArgument,
10059 };
10060
10061 if (FirstTemplate && SecondTemplate) {
10062 DeclHashes FirstTemplateHashes;
10063 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010064
10065 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010066 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10067 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010068 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010069 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010070 }
10071 };
10072
10073 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10074 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10075
10076 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10077 "Number of template parameters should be equal.");
10078
10079 auto FirstIt = FirstTemplateHashes.begin();
10080 auto FirstEnd = FirstTemplateHashes.end();
10081 auto SecondIt = SecondTemplateHashes.begin();
10082 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10083 if (FirstIt->second == SecondIt->second)
10084 continue;
10085
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010086 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this](
10087 SourceLocation Loc, SourceRange Range,
10088 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010089 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10090 << FirstRecord << FirstModule.empty() << FirstModule << Range
10091 << DiffType;
10092 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010093 auto ODRDiagTemplateNote = [&SecondModule, this](
10094 SourceLocation Loc, SourceRange Range,
10095 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010096 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10097 << SecondModule << Range << DiffType;
10098 };
10099
Vedant Kumar48b4f762018-04-14 01:40:48 +000010100 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10101 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010102
10103 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10104 "Parameter Decl's should be the same kind.");
10105
10106 DeclarationName FirstName = FirstDecl->getDeclName();
10107 DeclarationName SecondName = SecondDecl->getDeclName();
10108
10109 if (FirstName != SecondName) {
10110 const bool FirstNameEmpty =
10111 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10112 const bool SecondNameEmpty =
10113 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10114 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10115 "Both template parameters cannot be unnamed.");
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010116 ODRDiagTemplateError(FirstDecl->getLocation(),
10117 FirstDecl->getSourceRange(),
10118 FirstNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010119 << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010120 ODRDiagTemplateNote(SecondDecl->getLocation(),
10121 SecondDecl->getSourceRange(),
10122 SecondNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010123 << SecondName;
10124 break;
10125 }
10126
10127 switch (FirstDecl->getKind()) {
10128 default:
10129 llvm_unreachable("Invalid template parameter type.");
10130 case Decl::TemplateTypeParm: {
10131 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10132 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10133 const bool HasFirstDefaultArgument =
10134 FirstParam->hasDefaultArgument() &&
10135 !FirstParam->defaultArgumentWasInherited();
10136 const bool HasSecondDefaultArgument =
10137 SecondParam->hasDefaultArgument() &&
10138 !SecondParam->defaultArgumentWasInherited();
10139
10140 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010141 ODRDiagTemplateError(FirstDecl->getLocation(),
10142 FirstDecl->getSourceRange(),
10143 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010144 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010145 ODRDiagTemplateNote(SecondDecl->getLocation(),
10146 SecondDecl->getSourceRange(),
10147 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010148 << HasSecondDefaultArgument;
10149 break;
10150 }
10151
10152 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10153 "Expecting default arguments.");
10154
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010155 ODRDiagTemplateError(FirstDecl->getLocation(),
10156 FirstDecl->getSourceRange(),
10157 ParamDifferentDefaultArgument);
10158 ODRDiagTemplateNote(SecondDecl->getLocation(),
10159 SecondDecl->getSourceRange(),
10160 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010161
10162 break;
10163 }
10164 case Decl::NonTypeTemplateParm: {
10165 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10166 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10167 const bool HasFirstDefaultArgument =
10168 FirstParam->hasDefaultArgument() &&
10169 !FirstParam->defaultArgumentWasInherited();
10170 const bool HasSecondDefaultArgument =
10171 SecondParam->hasDefaultArgument() &&
10172 !SecondParam->defaultArgumentWasInherited();
10173
10174 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010175 ODRDiagTemplateError(FirstDecl->getLocation(),
10176 FirstDecl->getSourceRange(),
10177 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010178 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010179 ODRDiagTemplateNote(SecondDecl->getLocation(),
10180 SecondDecl->getSourceRange(),
10181 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010182 << HasSecondDefaultArgument;
10183 break;
10184 }
10185
10186 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10187 "Expecting default arguments.");
10188
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010189 ODRDiagTemplateError(FirstDecl->getLocation(),
10190 FirstDecl->getSourceRange(),
10191 ParamDifferentDefaultArgument);
10192 ODRDiagTemplateNote(SecondDecl->getLocation(),
10193 SecondDecl->getSourceRange(),
10194 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010195
10196 break;
10197 }
10198 case Decl::TemplateTemplateParm: {
10199 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10200 const auto *SecondParam =
10201 cast<TemplateTemplateParmDecl>(SecondDecl);
10202 const bool HasFirstDefaultArgument =
10203 FirstParam->hasDefaultArgument() &&
10204 !FirstParam->defaultArgumentWasInherited();
10205 const bool HasSecondDefaultArgument =
10206 SecondParam->hasDefaultArgument() &&
10207 !SecondParam->defaultArgumentWasInherited();
10208
10209 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010210 ODRDiagTemplateError(FirstDecl->getLocation(),
10211 FirstDecl->getSourceRange(),
10212 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010213 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010214 ODRDiagTemplateNote(SecondDecl->getLocation(),
10215 SecondDecl->getSourceRange(),
10216 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010217 << HasSecondDefaultArgument;
10218 break;
10219 }
10220
10221 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10222 "Expecting default arguments.");
10223
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010224 ODRDiagTemplateError(FirstDecl->getLocation(),
10225 FirstDecl->getSourceRange(),
10226 ParamDifferentDefaultArgument);
10227 ODRDiagTemplateNote(SecondDecl->getLocation(),
10228 SecondDecl->getSourceRange(),
10229 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010230
10231 break;
10232 }
10233 }
10234
10235 break;
10236 }
10237
10238 if (FirstIt != FirstEnd) {
10239 Diagnosed = true;
10240 break;
10241 }
10242 }
10243
Richard Trieue7f7ed22017-02-22 01:11:25 +000010244 DeclHashes FirstHashes;
10245 DeclHashes SecondHashes;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010246 const DeclContext *DC = FirstRecord;
10247 PopulateHashes(FirstHashes, FirstRecord, DC);
10248 PopulateHashes(SecondHashes, SecondRecord, DC);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010249
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010250 auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
10251 ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
10252 ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
10253 Decl *FirstDecl = DR.FirstDecl;
10254 Decl *SecondDecl = DR.SecondDecl;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010255
10256 if (FirstDiffType == Other || SecondDiffType == Other) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010257 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
10258 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010259 Diagnosed = true;
10260 break;
10261 }
10262
10263 if (FirstDiffType != SecondDiffType) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010264 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
10265 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010266 Diagnosed = true;
10267 break;
10268 }
10269
Richard Trieu639d7b62017-02-22 22:22:42 +000010270 assert(FirstDiffType == SecondDiffType);
10271
Richard Trieu639d7b62017-02-22 22:22:42 +000010272 switch (FirstDiffType) {
10273 case Other:
10274 case EndOfClass:
10275 case PublicSpecifer:
10276 case PrivateSpecifer:
10277 case ProtectedSpecifer:
10278 llvm_unreachable("Invalid diff type");
10279
10280 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010281 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10282 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010283
10284 Expr *FirstExpr = FirstSA->getAssertExpr();
10285 Expr *SecondExpr = SecondSA->getAssertExpr();
10286 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10287 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10288 if (FirstODRHash != SecondODRHash) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010289 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(),
10290 FirstExpr->getSourceRange(), StaticAssertCondition);
10291 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(),
10292 SecondExpr->getSourceRange(), StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010293 Diagnosed = true;
10294 break;
10295 }
10296
10297 StringLiteral *FirstStr = FirstSA->getMessage();
10298 StringLiteral *SecondStr = SecondSA->getMessage();
10299 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10300 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10301 SourceLocation FirstLoc, SecondLoc;
10302 SourceRange FirstRange, SecondRange;
10303 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010304 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010305 FirstRange = FirstStr->getSourceRange();
10306 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010307 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010308 FirstRange = FirstSA->getSourceRange();
10309 }
10310 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010311 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010312 SecondRange = SecondStr->getSourceRange();
10313 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010314 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010315 SecondRange = SecondSA->getSourceRange();
10316 }
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010317 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange,
10318 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010319 << (FirstStr == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010320 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange,
10321 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010322 << (SecondStr == nullptr);
10323 Diagnosed = true;
10324 break;
10325 }
10326
10327 if (FirstStr && SecondStr &&
10328 FirstStr->getString() != SecondStr->getString()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010329 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(),
10330 FirstStr->getSourceRange(), StaticAssertMessage);
10331 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(),
10332 SecondStr->getSourceRange(), StaticAssertMessage);
Richard Trieu639d7b62017-02-22 22:22:42 +000010333 Diagnosed = true;
10334 break;
10335 }
10336 break;
10337 }
Richard Trieud0786092017-02-23 00:23:01 +000010338 case Field: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010339 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
10340 cast<FieldDecl>(FirstDecl),
10341 cast<FieldDecl>(SecondDecl));
Richard Trieud0786092017-02-23 00:23:01 +000010342 break;
10343 }
Richard Trieu48143742017-02-28 21:24:38 +000010344 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010345 enum {
10346 DiagMethod,
10347 DiagConstructor,
10348 DiagDestructor,
10349 } FirstMethodType,
10350 SecondMethodType;
10351 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10352 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10353 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10354 return DiagMethod;
10355 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010356 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10357 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010358 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10359 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010360 auto FirstName = FirstMethod->getDeclName();
10361 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010362 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010363 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10364 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010365 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010366 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10367 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010368 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010369
10370 Diagnosed = true;
10371 break;
10372 }
10373
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010374 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10375 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010376 if (FirstDeleted != SecondDeleted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010377 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10378 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010379 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010380
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010381 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10382 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010383 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010384 Diagnosed = true;
10385 break;
10386 }
10387
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010388 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10389 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10390 if (FirstDefaulted != SecondDefaulted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010391 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10392 FirstMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010393 << FirstMethodType << FirstName << FirstDefaulted;
10394
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010395 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10396 SecondMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010397 << SecondMethodType << SecondName << SecondDefaulted;
10398 Diagnosed = true;
10399 break;
10400 }
10401
Richard Trieu583e2c12017-03-04 00:08:58 +000010402 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10403 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10404 const bool FirstPure = FirstMethod->isPure();
10405 const bool SecondPure = SecondMethod->isPure();
10406 if ((FirstVirtual || SecondVirtual) &&
10407 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010408 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10409 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010410 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010411 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10412 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010413 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010414 Diagnosed = true;
10415 break;
10416 }
10417
10418 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10419 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10420 // class needs to be checked instead.
10421 const auto FirstStorage = FirstMethod->getStorageClass();
10422 const auto SecondStorage = SecondMethod->getStorageClass();
10423 const bool FirstStatic = FirstStorage == SC_Static;
10424 const bool SecondStatic = SecondStorage == SC_Static;
10425 if (FirstStatic != SecondStatic) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010426 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10427 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010428 << FirstMethodType << FirstName << FirstStatic;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010429 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10430 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010431 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010432 Diagnosed = true;
10433 break;
10434 }
10435
10436 const bool FirstVolatile = FirstMethod->isVolatile();
10437 const bool SecondVolatile = SecondMethod->isVolatile();
10438 if (FirstVolatile != SecondVolatile) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010439 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10440 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010441 << FirstMethodType << FirstName << FirstVolatile;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010442 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10443 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010444 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010445 Diagnosed = true;
10446 break;
10447 }
10448
10449 const bool FirstConst = FirstMethod->isConst();
10450 const bool SecondConst = SecondMethod->isConst();
10451 if (FirstConst != SecondConst) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010452 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10453 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010454 << FirstMethodType << FirstName << FirstConst;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010455 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10456 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010457 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010458 Diagnosed = true;
10459 break;
10460 }
10461
10462 const bool FirstInline = FirstMethod->isInlineSpecified();
10463 const bool SecondInline = SecondMethod->isInlineSpecified();
10464 if (FirstInline != SecondInline) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010465 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10466 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010467 << FirstMethodType << FirstName << FirstInline;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010468 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10469 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010470 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010471 Diagnosed = true;
10472 break;
10473 }
10474
Richard Trieu02552272017-05-02 23:58:52 +000010475 const unsigned FirstNumParameters = FirstMethod->param_size();
10476 const unsigned SecondNumParameters = SecondMethod->param_size();
10477 if (FirstNumParameters != SecondNumParameters) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010478 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10479 FirstMethod->getSourceRange(),
10480 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010481 << FirstMethodType << FirstName << FirstNumParameters;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010482 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10483 SecondMethod->getSourceRange(),
10484 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010485 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010486 Diagnosed = true;
10487 break;
10488 }
10489
10490 // Need this status boolean to know when break out of the switch.
10491 bool ParameterMismatch = false;
10492 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10493 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10494 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10495
10496 QualType FirstParamType = FirstParam->getType();
10497 QualType SecondParamType = SecondParam->getType();
10498 if (FirstParamType != SecondParamType &&
10499 ComputeQualTypeODRHash(FirstParamType) !=
10500 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010501 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010502 FirstParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010503 ODRDiagDeclError(
10504 FirstRecord, FirstModule, FirstMethod->getLocation(),
10505 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010506 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10507 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010508 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010509 ODRDiagDeclError(
10510 FirstRecord, FirstModule, FirstMethod->getLocation(),
10511 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010512 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10513 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010514 }
10515
Vedant Kumar48b4f762018-04-14 01:40:48 +000010516 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010517 SecondParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010518 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10519 SecondMethod->getSourceRange(),
10520 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010521 << SecondMethodType << SecondName << (I + 1)
10522 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010523 << ParamDecayedType->getOriginalType();
10524 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010525 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10526 SecondMethod->getSourceRange(),
10527 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010528 << SecondMethodType << SecondName << (I + 1)
10529 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010530 }
10531 ParameterMismatch = true;
10532 break;
10533 }
10534
10535 DeclarationName FirstParamName = FirstParam->getDeclName();
10536 DeclarationName SecondParamName = SecondParam->getDeclName();
10537 if (FirstParamName != SecondParamName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010538 ODRDiagDeclError(FirstRecord, FirstModule,
10539 FirstMethod->getLocation(),
10540 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010541 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010542 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10543 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010544 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010545 ParameterMismatch = true;
10546 break;
10547 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010548
10549 const Expr *FirstInit = FirstParam->getInit();
10550 const Expr *SecondInit = SecondParam->getInit();
10551 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010552 ODRDiagDeclError(FirstRecord, FirstModule,
10553 FirstMethod->getLocation(),
10554 FirstMethod->getSourceRange(),
10555 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010556 << FirstMethodType << FirstName << (I + 1)
10557 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010558 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010559 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10560 SecondMethod->getSourceRange(),
10561 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010562 << SecondMethodType << SecondName << (I + 1)
10563 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010564 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10565 ParameterMismatch = true;
10566 break;
10567 }
10568
10569 if (FirstInit && SecondInit &&
10570 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010571 ODRDiagDeclError(FirstRecord, FirstModule,
10572 FirstMethod->getLocation(),
10573 FirstMethod->getSourceRange(),
10574 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010575 << FirstMethodType << FirstName << (I + 1)
10576 << FirstInit->getSourceRange();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010577 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10578 SecondMethod->getSourceRange(),
10579 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010580 << SecondMethodType << SecondName << (I + 1)
10581 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010582 ParameterMismatch = true;
10583 break;
10584
10585 }
Richard Trieu02552272017-05-02 23:58:52 +000010586 }
10587
10588 if (ParameterMismatch) {
10589 Diagnosed = true;
10590 break;
10591 }
10592
Richard Trieu7282d322018-04-25 00:31:15 +000010593 const auto *FirstTemplateArgs =
10594 FirstMethod->getTemplateSpecializationArgs();
10595 const auto *SecondTemplateArgs =
10596 SecondMethod->getTemplateSpecializationArgs();
10597
10598 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10599 (!FirstTemplateArgs && SecondTemplateArgs)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010600 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10601 FirstMethod->getSourceRange(),
10602 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010603 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010604 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10605 SecondMethod->getSourceRange(),
10606 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010607 << SecondMethodType << SecondName
10608 << (SecondTemplateArgs != nullptr);
10609
10610 Diagnosed = true;
10611 break;
10612 }
10613
10614 if (FirstTemplateArgs && SecondTemplateArgs) {
10615 // Remove pack expansions from argument list.
10616 auto ExpandTemplateArgumentList =
10617 [](const TemplateArgumentList *TAL) {
10618 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10619 for (const TemplateArgument &TA : TAL->asArray()) {
10620 if (TA.getKind() != TemplateArgument::Pack) {
10621 ExpandedList.push_back(&TA);
10622 continue;
10623 }
10624 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10625 ExpandedList.push_back(&PackTA);
10626 }
10627 }
10628 return ExpandedList;
10629 };
10630 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10631 ExpandTemplateArgumentList(FirstTemplateArgs);
10632 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10633 ExpandTemplateArgumentList(SecondTemplateArgs);
10634
10635 if (FirstExpandedList.size() != SecondExpandedList.size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010636 ODRDiagDeclError(FirstRecord, FirstModule,
10637 FirstMethod->getLocation(),
10638 FirstMethod->getSourceRange(),
10639 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010640 << FirstMethodType << FirstName
10641 << (unsigned)FirstExpandedList.size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010642 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10643 SecondMethod->getSourceRange(),
10644 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010645 << SecondMethodType << SecondName
10646 << (unsigned)SecondExpandedList.size();
10647
10648 Diagnosed = true;
10649 break;
10650 }
10651
10652 bool TemplateArgumentMismatch = false;
10653 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10654 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10655 &SecondTA = *SecondExpandedList[i];
10656 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10657 ComputeTemplateArgumentODRHash(SecondTA)) {
10658 continue;
10659 }
10660
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010661 ODRDiagDeclError(
10662 FirstRecord, FirstModule, FirstMethod->getLocation(),
10663 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010664 << FirstMethodType << FirstName << FirstTA << i + 1;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010665 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10666 SecondMethod->getSourceRange(),
10667 MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010668 << SecondMethodType << SecondName << SecondTA << i + 1;
10669
10670 TemplateArgumentMismatch = true;
10671 break;
10672 }
10673
10674 if (TemplateArgumentMismatch) {
10675 Diagnosed = true;
10676 break;
10677 }
10678 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010679
10680 // Compute the hash of the method as if it has no body.
10681 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10682 Hash.clear();
10683 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10684 return Hash.CalculateHash();
10685 };
10686
10687 // Compare the hash generated to the hash stored. A difference means
10688 // that a body was present in the original source. Due to merging,
10689 // the stardard way of detecting a body will not work.
10690 const bool HasFirstBody =
10691 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10692 const bool HasSecondBody =
10693 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10694
10695 if (HasFirstBody != HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010696 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10697 FirstMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010698 << FirstMethodType << FirstName << HasFirstBody;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010699 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10700 SecondMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010701 << SecondMethodType << SecondName << HasSecondBody;
10702 Diagnosed = true;
10703 break;
10704 }
10705
10706 if (HasFirstBody && HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010707 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10708 FirstMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010709 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010710 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10711 SecondMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010712 << SecondMethodType << SecondName;
10713 Diagnosed = true;
10714 break;
10715 }
10716
Richard Trieu48143742017-02-28 21:24:38 +000010717 break;
10718 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010719 case TypeAlias:
10720 case TypeDef: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010721 Diagnosed = ODRDiagTypeDefOrAlias(
10722 FirstRecord, FirstModule, SecondModule,
10723 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
10724 FirstDiffType == TypeAlias);
Richard Trieu11d566a2017-06-12 21:58:22 +000010725 break;
10726 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010727 case Var: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010728 Diagnosed =
10729 ODRDiagVar(FirstRecord, FirstModule, SecondModule,
10730 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
Richard Trieu6e13ff32017-06-16 02:44:29 +000010731 break;
10732 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010733 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010734 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10735 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010736
10737 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10738 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10739
10740 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10741 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10742
10743 if (FirstND && SecondND) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010744 ODRDiagDeclError(FirstRecord, FirstModule,
10745 FirstFriend->getFriendLoc(),
10746 FirstFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010747 << FirstND;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010748 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10749 SecondFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010750 << SecondND;
10751
10752 Diagnosed = true;
10753 break;
10754 }
10755
10756 if (FirstTSI && SecondTSI) {
10757 QualType FirstFriendType = FirstTSI->getType();
10758 QualType SecondFriendType = SecondTSI->getType();
10759 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10760 ComputeQualTypeODRHash(SecondFriendType));
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010761 ODRDiagDeclError(FirstRecord, FirstModule,
10762 FirstFriend->getFriendLoc(),
10763 FirstFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010764 << FirstFriendType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010765 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10766 SecondFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010767 << SecondFriendType;
10768 Diagnosed = true;
10769 break;
10770 }
10771
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010772 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(),
10773 FirstFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010774 << (FirstTSI == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010775 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10776 SecondFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010777 << (SecondTSI == nullptr);
10778
10779 Diagnosed = true;
10780 break;
10781 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010782 case FunctionTemplate: {
10783 FunctionTemplateDecl *FirstTemplate =
10784 cast<FunctionTemplateDecl>(FirstDecl);
10785 FunctionTemplateDecl *SecondTemplate =
10786 cast<FunctionTemplateDecl>(SecondDecl);
10787
10788 TemplateParameterList *FirstTPL =
10789 FirstTemplate->getTemplateParameters();
10790 TemplateParameterList *SecondTPL =
10791 SecondTemplate->getTemplateParameters();
10792
10793 if (FirstTPL->size() != SecondTPL->size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010794 ODRDiagDeclError(FirstRecord, FirstModule,
10795 FirstTemplate->getLocation(),
10796 FirstTemplate->getSourceRange(),
10797 FunctionTemplateDifferentNumberParameters)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010798 << FirstTemplate << FirstTPL->size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010799 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10800 SecondTemplate->getSourceRange(),
10801 FunctionTemplateDifferentNumberParameters)
10802 << SecondTemplate << SecondTPL->size();
Richard Trieu9359e8f2018-05-30 01:12:26 +000010803
10804 Diagnosed = true;
10805 break;
10806 }
10807
10808 bool ParameterMismatch = false;
10809 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10810 NamedDecl *FirstParam = FirstTPL->getParam(i);
10811 NamedDecl *SecondParam = SecondTPL->getParam(i);
10812
10813 if (FirstParam->getKind() != SecondParam->getKind()) {
10814 enum {
10815 TemplateTypeParameter,
10816 NonTypeTemplateParameter,
10817 TemplateTemplateParameter,
10818 };
10819 auto GetParamType = [](NamedDecl *D) {
10820 switch (D->getKind()) {
10821 default:
10822 llvm_unreachable("Unexpected template parameter type");
10823 case Decl::TemplateTypeParm:
10824 return TemplateTypeParameter;
10825 case Decl::NonTypeTemplateParm:
10826 return NonTypeTemplateParameter;
10827 case Decl::TemplateTemplateParm:
10828 return TemplateTemplateParameter;
10829 }
10830 };
10831
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010832 ODRDiagDeclError(FirstRecord, FirstModule,
10833 FirstTemplate->getLocation(),
10834 FirstTemplate->getSourceRange(),
10835 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010836 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010837 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10838 SecondTemplate->getSourceRange(),
10839 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010840 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10841
10842 ParameterMismatch = true;
10843 break;
10844 }
10845
10846 if (FirstParam->getName() != SecondParam->getName()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010847 ODRDiagDeclError(
10848 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10849 FirstTemplate->getSourceRange(), FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010850 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10851 << FirstParam;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010852 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10853 SecondTemplate->getSourceRange(),
10854 FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010855 << SecondTemplate << (i + 1)
10856 << (bool)SecondParam->getIdentifier() << SecondParam;
10857 ParameterMismatch = true;
10858 break;
10859 }
10860
10861 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10862 isa<TemplateTypeParmDecl>(SecondParam)) {
10863 TemplateTypeParmDecl *FirstTTPD =
10864 cast<TemplateTypeParmDecl>(FirstParam);
10865 TemplateTypeParmDecl *SecondTTPD =
10866 cast<TemplateTypeParmDecl>(SecondParam);
10867 bool HasFirstDefaultArgument =
10868 FirstTTPD->hasDefaultArgument() &&
10869 !FirstTTPD->defaultArgumentWasInherited();
10870 bool HasSecondDefaultArgument =
10871 SecondTTPD->hasDefaultArgument() &&
10872 !SecondTTPD->defaultArgumentWasInherited();
10873 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010874 ODRDiagDeclError(FirstRecord, FirstModule,
10875 FirstTemplate->getLocation(),
10876 FirstTemplate->getSourceRange(),
10877 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010878 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010879 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10880 SecondTemplate->getSourceRange(),
10881 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010882 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10883 ParameterMismatch = true;
10884 break;
10885 }
10886
10887 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10888 QualType FirstType = FirstTTPD->getDefaultArgument();
10889 QualType SecondType = SecondTTPD->getDefaultArgument();
10890 if (ComputeQualTypeODRHash(FirstType) !=
10891 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010892 ODRDiagDeclError(
10893 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10894 FirstTemplate->getSourceRange(),
10895 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010896 << FirstTemplate << (i + 1) << FirstType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010897 ODRDiagDeclNote(
10898 SecondModule, SecondTemplate->getLocation(),
10899 SecondTemplate->getSourceRange(),
10900 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010901 << SecondTemplate << (i + 1) << SecondType;
10902 ParameterMismatch = true;
10903 break;
10904 }
10905 }
10906
10907 if (FirstTTPD->isParameterPack() !=
10908 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010909 ODRDiagDeclError(FirstRecord, FirstModule,
10910 FirstTemplate->getLocation(),
10911 FirstTemplate->getSourceRange(),
10912 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010913 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010914 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10915 SecondTemplate->getSourceRange(),
10916 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010917 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10918 ParameterMismatch = true;
10919 break;
10920 }
10921 }
10922
10923 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10924 isa<TemplateTemplateParmDecl>(SecondParam)) {
10925 TemplateTemplateParmDecl *FirstTTPD =
10926 cast<TemplateTemplateParmDecl>(FirstParam);
10927 TemplateTemplateParmDecl *SecondTTPD =
10928 cast<TemplateTemplateParmDecl>(SecondParam);
10929
10930 TemplateParameterList *FirstTPL =
10931 FirstTTPD->getTemplateParameters();
10932 TemplateParameterList *SecondTPL =
10933 SecondTTPD->getTemplateParameters();
10934
10935 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10936 ComputeTemplateParameterListODRHash(SecondTPL)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010937 ODRDiagDeclError(FirstRecord, FirstModule,
10938 FirstTemplate->getLocation(),
10939 FirstTemplate->getSourceRange(),
10940 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010941 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010942 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10943 SecondTemplate->getSourceRange(),
10944 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010945 << SecondTemplate << (i + 1);
10946 ParameterMismatch = true;
10947 break;
10948 }
10949
10950 bool HasFirstDefaultArgument =
10951 FirstTTPD->hasDefaultArgument() &&
10952 !FirstTTPD->defaultArgumentWasInherited();
10953 bool HasSecondDefaultArgument =
10954 SecondTTPD->hasDefaultArgument() &&
10955 !SecondTTPD->defaultArgumentWasInherited();
10956 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010957 ODRDiagDeclError(FirstRecord, FirstModule,
10958 FirstTemplate->getLocation(),
10959 FirstTemplate->getSourceRange(),
10960 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010961 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010962 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10963 SecondTemplate->getSourceRange(),
10964 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010965 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10966 ParameterMismatch = true;
10967 break;
10968 }
10969
10970 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10971 TemplateArgument FirstTA =
10972 FirstTTPD->getDefaultArgument().getArgument();
10973 TemplateArgument SecondTA =
10974 SecondTTPD->getDefaultArgument().getArgument();
10975 if (ComputeTemplateArgumentODRHash(FirstTA) !=
10976 ComputeTemplateArgumentODRHash(SecondTA)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010977 ODRDiagDeclError(
10978 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10979 FirstTemplate->getSourceRange(),
10980 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010981 << FirstTemplate << (i + 1) << FirstTA;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010982 ODRDiagDeclNote(
10983 SecondModule, SecondTemplate->getLocation(),
10984 SecondTemplate->getSourceRange(),
10985 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010986 << SecondTemplate << (i + 1) << SecondTA;
10987 ParameterMismatch = true;
10988 break;
10989 }
10990 }
10991
10992 if (FirstTTPD->isParameterPack() !=
10993 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010994 ODRDiagDeclError(FirstRecord, FirstModule,
10995 FirstTemplate->getLocation(),
10996 FirstTemplate->getSourceRange(),
10997 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010998 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010999 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11000 SecondTemplate->getSourceRange(),
11001 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011002 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11003 ParameterMismatch = true;
11004 break;
11005 }
11006 }
11007
11008 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11009 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11010 NonTypeTemplateParmDecl *FirstNTTPD =
11011 cast<NonTypeTemplateParmDecl>(FirstParam);
11012 NonTypeTemplateParmDecl *SecondNTTPD =
11013 cast<NonTypeTemplateParmDecl>(SecondParam);
11014
11015 QualType FirstType = FirstNTTPD->getType();
11016 QualType SecondType = SecondNTTPD->getType();
11017 if (ComputeQualTypeODRHash(FirstType) !=
11018 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011019 ODRDiagDeclError(FirstRecord, FirstModule,
11020 FirstTemplate->getLocation(),
11021 FirstTemplate->getSourceRange(),
11022 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011023 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011024 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11025 SecondTemplate->getSourceRange(),
11026 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011027 << SecondTemplate << (i + 1);
11028 ParameterMismatch = true;
11029 break;
11030 }
11031
11032 bool HasFirstDefaultArgument =
11033 FirstNTTPD->hasDefaultArgument() &&
11034 !FirstNTTPD->defaultArgumentWasInherited();
11035 bool HasSecondDefaultArgument =
11036 SecondNTTPD->hasDefaultArgument() &&
11037 !SecondNTTPD->defaultArgumentWasInherited();
11038 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011039 ODRDiagDeclError(FirstRecord, FirstModule,
11040 FirstTemplate->getLocation(),
11041 FirstTemplate->getSourceRange(),
11042 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011043 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011044 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11045 SecondTemplate->getSourceRange(),
11046 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011047 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11048 ParameterMismatch = true;
11049 break;
11050 }
11051
11052 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11053 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11054 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11055 if (ComputeODRHash(FirstDefaultArgument) !=
11056 ComputeODRHash(SecondDefaultArgument)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011057 ODRDiagDeclError(
11058 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11059 FirstTemplate->getSourceRange(),
11060 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011061 << FirstTemplate << (i + 1) << FirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011062 ODRDiagDeclNote(
11063 SecondModule, SecondTemplate->getLocation(),
11064 SecondTemplate->getSourceRange(),
11065 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011066 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11067 ParameterMismatch = true;
11068 break;
11069 }
11070 }
11071
11072 if (FirstNTTPD->isParameterPack() !=
11073 SecondNTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011074 ODRDiagDeclError(FirstRecord, FirstModule,
11075 FirstTemplate->getLocation(),
11076 FirstTemplate->getSourceRange(),
11077 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011078 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011079 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11080 SecondTemplate->getSourceRange(),
11081 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011082 << SecondTemplate << (i + 1)
11083 << SecondNTTPD->isParameterPack();
11084 ParameterMismatch = true;
11085 break;
11086 }
11087 }
11088 }
11089
11090 if (ParameterMismatch) {
11091 Diagnosed = true;
11092 break;
11093 }
11094
11095 break;
11096 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011097 }
11098
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011099 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011100 continue;
11101
Richard Trieu708859a2017-06-08 00:56:21 +000011102 Diag(FirstDecl->getLocation(),
11103 diag::err_module_odr_violation_mismatch_decl_unknown)
11104 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11105 << FirstDecl->getSourceRange();
11106 Diag(SecondDecl->getLocation(),
11107 diag::note_module_odr_violation_mismatch_decl_unknown)
11108 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011109 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011110 }
11111
11112 if (!Diagnosed) {
11113 // All definitions are updates to the same declaration. This happens if a
11114 // module instantiates the declaration of a class template specialization
11115 // and two or more other modules instantiate its definition.
11116 //
11117 // FIXME: Indicate which modules had instantiations of this definition.
11118 // FIXME: How can this even happen?
11119 Diag(Merge.first->getLocation(),
11120 diag::err_module_odr_violation_different_instantiations)
11121 << Merge.first;
11122 }
11123 }
Richard Trieue6caa262017-12-23 00:41:01 +000011124
11125 // Issue ODR failures diagnostics for functions.
11126 for (auto &Merge : FunctionOdrMergeFailures) {
11127 enum ODRFunctionDifference {
11128 ReturnType,
11129 ParameterName,
11130 ParameterType,
11131 ParameterSingleDefaultArgument,
11132 ParameterDifferentDefaultArgument,
11133 FunctionBody,
11134 };
11135
11136 FunctionDecl *FirstFunction = Merge.first;
11137 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11138
11139 bool Diagnosed = false;
11140 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011141
Richard Trieue6caa262017-12-23 00:41:01 +000011142 if (FirstFunction == SecondFunction)
11143 continue;
11144
11145 std::string SecondModule =
11146 getOwningModuleNameForDiagnostic(SecondFunction);
11147
11148 auto ODRDiagError = [FirstFunction, &FirstModule,
11149 this](SourceLocation Loc, SourceRange Range,
11150 ODRFunctionDifference DiffType) {
11151 return Diag(Loc, diag::err_module_odr_violation_function)
11152 << FirstFunction << FirstModule.empty() << FirstModule << Range
11153 << DiffType;
11154 };
11155 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11156 SourceRange Range,
11157 ODRFunctionDifference DiffType) {
11158 return Diag(Loc, diag::note_module_odr_violation_function)
11159 << SecondModule << Range << DiffType;
11160 };
11161
11162 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11163 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11164 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11165 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11166 << FirstFunction->getReturnType();
11167 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11168 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11169 << SecondFunction->getReturnType();
11170 Diagnosed = true;
11171 break;
11172 }
11173
11174 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11175 "Merged functions with different number of parameters");
11176
11177 auto ParamSize = FirstFunction->param_size();
11178 bool ParameterMismatch = false;
11179 for (unsigned I = 0; I < ParamSize; ++I) {
11180 auto *FirstParam = FirstFunction->getParamDecl(I);
11181 auto *SecondParam = SecondFunction->getParamDecl(I);
11182
11183 assert(getContext().hasSameType(FirstParam->getType(),
11184 SecondParam->getType()) &&
11185 "Merged function has different parameter types.");
11186
11187 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11188 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11189 ParameterName)
11190 << I + 1 << FirstParam->getDeclName();
11191 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11192 ParameterName)
11193 << I + 1 << SecondParam->getDeclName();
11194 ParameterMismatch = true;
11195 break;
11196 };
11197
11198 QualType FirstParamType = FirstParam->getType();
11199 QualType SecondParamType = SecondParam->getType();
11200 if (FirstParamType != SecondParamType &&
11201 ComputeQualTypeODRHash(FirstParamType) !=
11202 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011203 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011204 FirstParamType->getAs<DecayedType>()) {
11205 ODRDiagError(FirstParam->getLocation(),
11206 FirstParam->getSourceRange(), ParameterType)
11207 << (I + 1) << FirstParamType << true
11208 << ParamDecayedType->getOriginalType();
11209 } else {
11210 ODRDiagError(FirstParam->getLocation(),
11211 FirstParam->getSourceRange(), ParameterType)
11212 << (I + 1) << FirstParamType << false;
11213 }
11214
Vedant Kumar48b4f762018-04-14 01:40:48 +000011215 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011216 SecondParamType->getAs<DecayedType>()) {
11217 ODRDiagNote(SecondParam->getLocation(),
11218 SecondParam->getSourceRange(), ParameterType)
11219 << (I + 1) << SecondParamType << true
11220 << ParamDecayedType->getOriginalType();
11221 } else {
11222 ODRDiagNote(SecondParam->getLocation(),
11223 SecondParam->getSourceRange(), ParameterType)
11224 << (I + 1) << SecondParamType << false;
11225 }
11226 ParameterMismatch = true;
11227 break;
11228 }
11229
11230 const Expr *FirstInit = FirstParam->getInit();
11231 const Expr *SecondInit = SecondParam->getInit();
11232 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11233 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11234 ParameterSingleDefaultArgument)
11235 << (I + 1) << (FirstInit == nullptr)
11236 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11237 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11238 ParameterSingleDefaultArgument)
11239 << (I + 1) << (SecondInit == nullptr)
11240 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11241 ParameterMismatch = true;
11242 break;
11243 }
11244
11245 if (FirstInit && SecondInit &&
11246 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11247 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11248 ParameterDifferentDefaultArgument)
11249 << (I + 1) << FirstInit->getSourceRange();
11250 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11251 ParameterDifferentDefaultArgument)
11252 << (I + 1) << SecondInit->getSourceRange();
11253 ParameterMismatch = true;
11254 break;
11255 }
11256
11257 assert(ComputeSubDeclODRHash(FirstParam) ==
11258 ComputeSubDeclODRHash(SecondParam) &&
11259 "Undiagnosed parameter difference.");
11260 }
11261
11262 if (ParameterMismatch) {
11263 Diagnosed = true;
11264 break;
11265 }
11266
11267 // If no error has been generated before now, assume the problem is in
11268 // the body and generate a message.
11269 ODRDiagError(FirstFunction->getLocation(),
11270 FirstFunction->getSourceRange(), FunctionBody);
11271 ODRDiagNote(SecondFunction->getLocation(),
11272 SecondFunction->getSourceRange(), FunctionBody);
11273 Diagnosed = true;
11274 break;
11275 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011276 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011277 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11278 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011279
11280 // Issue ODR failures diagnostics for enums.
11281 for (auto &Merge : EnumOdrMergeFailures) {
11282 enum ODREnumDifference {
11283 SingleScopedEnum,
11284 EnumTagKeywordMismatch,
11285 SingleSpecifiedType,
11286 DifferentSpecifiedTypes,
11287 DifferentNumberEnumConstants,
11288 EnumConstantName,
11289 EnumConstantSingleInitilizer,
11290 EnumConstantDifferentInitilizer,
11291 };
11292
11293 // If we've already pointed out a specific problem with this enum, don't
11294 // bother issuing a general "something's different" diagnostic.
11295 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11296 continue;
11297
11298 EnumDecl *FirstEnum = Merge.first;
11299 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11300
11301 using DeclHashes =
11302 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11303 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11304 DeclHashes &Hashes, EnumDecl *Enum) {
11305 for (auto *D : Enum->decls()) {
11306 // Due to decl merging, the first EnumDecl is the parent of
11307 // Decls in both records.
11308 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11309 continue;
11310 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11311 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11312 ComputeSubDeclODRHash(D));
11313 }
11314 };
11315 DeclHashes FirstHashes;
11316 PopulateHashes(FirstHashes, FirstEnum);
11317 bool Diagnosed = false;
11318 for (auto &SecondEnum : Merge.second) {
11319
11320 if (FirstEnum == SecondEnum)
11321 continue;
11322
11323 std::string SecondModule =
11324 getOwningModuleNameForDiagnostic(SecondEnum);
11325
11326 auto ODRDiagError = [FirstEnum, &FirstModule,
11327 this](SourceLocation Loc, SourceRange Range,
11328 ODREnumDifference DiffType) {
11329 return Diag(Loc, diag::err_module_odr_violation_enum)
11330 << FirstEnum << FirstModule.empty() << FirstModule << Range
11331 << DiffType;
11332 };
11333 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11334 SourceRange Range,
11335 ODREnumDifference DiffType) {
11336 return Diag(Loc, diag::note_module_odr_violation_enum)
11337 << SecondModule << Range << DiffType;
11338 };
11339
11340 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11341 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11342 SingleScopedEnum)
11343 << FirstEnum->isScoped();
11344 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11345 SingleScopedEnum)
11346 << SecondEnum->isScoped();
11347 Diagnosed = true;
11348 continue;
11349 }
11350
11351 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11352 if (FirstEnum->isScopedUsingClassTag() !=
11353 SecondEnum->isScopedUsingClassTag()) {
11354 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11355 EnumTagKeywordMismatch)
11356 << FirstEnum->isScopedUsingClassTag();
11357 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11358 EnumTagKeywordMismatch)
11359 << SecondEnum->isScopedUsingClassTag();
11360 Diagnosed = true;
11361 continue;
11362 }
11363 }
11364
11365 QualType FirstUnderlyingType =
11366 FirstEnum->getIntegerTypeSourceInfo()
11367 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11368 : QualType();
11369 QualType SecondUnderlyingType =
11370 SecondEnum->getIntegerTypeSourceInfo()
11371 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11372 : QualType();
11373 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11374 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11375 SingleSpecifiedType)
11376 << !FirstUnderlyingType.isNull();
11377 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11378 SingleSpecifiedType)
11379 << !SecondUnderlyingType.isNull();
11380 Diagnosed = true;
11381 continue;
11382 }
11383
11384 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11385 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11386 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11387 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11388 DifferentSpecifiedTypes)
11389 << FirstUnderlyingType;
11390 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11391 DifferentSpecifiedTypes)
11392 << SecondUnderlyingType;
11393 Diagnosed = true;
11394 continue;
11395 }
11396 }
11397
11398 DeclHashes SecondHashes;
11399 PopulateHashes(SecondHashes, SecondEnum);
11400
11401 if (FirstHashes.size() != SecondHashes.size()) {
11402 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11403 DifferentNumberEnumConstants)
11404 << (int)FirstHashes.size();
11405 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11406 DifferentNumberEnumConstants)
11407 << (int)SecondHashes.size();
11408 Diagnosed = true;
11409 continue;
11410 }
11411
11412 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11413 if (FirstHashes[I].second == SecondHashes[I].second)
11414 continue;
11415 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11416 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11417
11418 if (FirstEnumConstant->getDeclName() !=
11419 SecondEnumConstant->getDeclName()) {
11420
11421 ODRDiagError(FirstEnumConstant->getLocation(),
11422 FirstEnumConstant->getSourceRange(), EnumConstantName)
11423 << I + 1 << FirstEnumConstant;
11424 ODRDiagNote(SecondEnumConstant->getLocation(),
11425 SecondEnumConstant->getSourceRange(), EnumConstantName)
11426 << I + 1 << SecondEnumConstant;
11427 Diagnosed = true;
11428 break;
11429 }
11430
11431 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11432 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11433 if (!FirstInit && !SecondInit)
11434 continue;
11435
11436 if (!FirstInit || !SecondInit) {
11437 ODRDiagError(FirstEnumConstant->getLocation(),
11438 FirstEnumConstant->getSourceRange(),
11439 EnumConstantSingleInitilizer)
11440 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11441 ODRDiagNote(SecondEnumConstant->getLocation(),
11442 SecondEnumConstant->getSourceRange(),
11443 EnumConstantSingleInitilizer)
11444 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11445 Diagnosed = true;
11446 break;
11447 }
11448
11449 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11450 ODRDiagError(FirstEnumConstant->getLocation(),
11451 FirstEnumConstant->getSourceRange(),
11452 EnumConstantDifferentInitilizer)
11453 << I + 1 << FirstEnumConstant;
11454 ODRDiagNote(SecondEnumConstant->getLocation(),
11455 SecondEnumConstant->getSourceRange(),
11456 EnumConstantDifferentInitilizer)
11457 << I + 1 << SecondEnumConstant;
11458 Diagnosed = true;
11459 break;
11460 }
11461 }
11462 }
11463
11464 (void)Diagnosed;
11465 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11466 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011467}
11468
Richard Smithce18a182015-07-14 00:26:00 +000011469void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011470 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011471 ReadTimer->startTimer();
11472}
11473
Guy Benyei11169dd2012-12-18 14:30:41 +000011474void ASTReader::FinishedDeserializing() {
11475 assert(NumCurrentElementsDeserializing &&
11476 "FinishedDeserializing not paired with StartedDeserializing");
11477 if (NumCurrentElementsDeserializing == 1) {
11478 // We decrease NumCurrentElementsDeserializing only after pending actions
11479 // are finished, to avoid recursively re-calling finishPendingActions().
11480 finishPendingActions();
11481 }
11482 --NumCurrentElementsDeserializing;
11483
Richard Smitha0ce9c42014-07-29 23:23:27 +000011484 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011485 // Propagate exception specification and deduced type updates along
11486 // redeclaration chains.
11487 //
11488 // We do this now rather than in finishPendingActions because we want to
11489 // be able to walk the complete redeclaration chains of the updated decls.
11490 while (!PendingExceptionSpecUpdates.empty() ||
11491 !PendingDeducedTypeUpdates.empty()) {
11492 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011493 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011494 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011495 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011496 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011497 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011498 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011499 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011500 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011501 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011502 }
Richard Smitha62d1982018-08-03 01:00:01 +000011503
11504 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11505 PendingDeducedTypeUpdates.clear();
11506 for (auto Update : DTUpdates) {
11507 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11508 // FIXME: If the return type is already deduced, check that it matches.
11509 getContext().adjustDeducedFunctionResultType(Update.first,
11510 Update.second);
11511 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011512 }
11513
Richard Smithce18a182015-07-14 00:26:00 +000011514 if (ReadTimer)
11515 ReadTimer->stopTimer();
11516
Richard Smith0f4e2c42015-08-06 04:23:48 +000011517 diagnoseOdrViolations();
11518
Richard Smith04d05b52014-03-23 00:27:18 +000011519 // We are not in recursive loading, so it's safe to pass the "interesting"
11520 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011521 if (Consumer)
11522 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011523 }
11524}
11525
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011526void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011527 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11528 // Remove any fake results before adding any real ones.
11529 auto It = PendingFakeLookupResults.find(II);
11530 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011531 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011532 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011533 // FIXME: this works around module+PCH performance issue.
11534 // Rather than erase the result from the map, which is O(n), just clear
11535 // the vector of NamedDecls.
11536 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011537 }
11538 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011539
11540 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11541 SemaObj->TUScope->AddDecl(D);
11542 } else if (SemaObj->TUScope) {
11543 // Adding the decl to IdResolver may have failed because it was already in
11544 // (even though it was not added in scope). If it is already in, make sure
11545 // it gets in the scope as well.
11546 if (std::find(SemaObj->IdResolver.begin(Name),
11547 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11548 SemaObj->TUScope->AddDecl(D);
11549 }
11550}
11551
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011552ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11553 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011554 const PCHContainerReader &PCHContainerRdr,
11555 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11556 StringRef isysroot, bool DisableValidation,
11557 bool AllowASTWithCompilerErrors,
11558 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011559 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000011560 std::unique_ptr<llvm::Timer> ReadTimer)
11561 : Listener(DisableValidation
11562 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11563 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011564 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011565 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011566 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11567 PCHContainerRdr, PP.getHeaderSearchInfo()),
11568 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011569 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011570 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11571 AllowConfigurationMismatch(AllowConfigurationMismatch),
11572 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011573 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011574 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011575 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011576
11577 for (const auto &Ext : Extensions) {
11578 auto BlockName = Ext->getExtensionMetadata().BlockName;
11579 auto Known = ModuleFileExtensions.find(BlockName);
11580 if (Known != ModuleFileExtensions.end()) {
11581 Diags.Report(diag::warn_duplicate_module_file_extension)
11582 << BlockName;
11583 continue;
11584 }
11585
11586 ModuleFileExtensions.insert({BlockName, Ext});
11587 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011588}
11589
11590ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011591 if (OwnsDeserializationListener)
11592 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011593}
Richard Smith10379092016-05-06 23:14:07 +000011594
11595IdentifierResolver &ASTReader::getIdResolver() {
11596 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11597}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011598
JF Bastien0e828952019-06-26 19:50:12 +000011599Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11600 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000011601 Idx = 0;
11602 Record.clear();
11603 return Cursor.readRecord(AbbrevID, Record);
11604}
Kelvin Libe286f52018-09-15 13:54:15 +000011605//===----------------------------------------------------------------------===//
11606//// OMPClauseReader implementation
11607////===----------------------------------------------------------------------===//
11608
John McCallc2f18312019-12-14 03:01:28 -050011609// This has to be in namespace clang because it's friended by all
11610// of the OMP clauses.
11611namespace clang {
11612
11613class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11614 ASTRecordReader &Record;
11615 ASTContext &Context;
11616
11617public:
11618 OMPClauseReader(ASTRecordReader &Record)
11619 : Record(Record), Context(Record.getContext()) {}
11620
Johannes Doerfert419a5592020-03-30 19:58:40 -050011621#define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11622#include "llvm/Frontend/OpenMP/OMPKinds.def"
John McCallc2f18312019-12-14 03:01:28 -050011623 OMPClause *readClause();
11624 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11625 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11626};
11627
11628} // end namespace clang
11629
11630OMPClause *ASTRecordReader::readOMPClause() {
11631 return OMPClauseReader(*this).readClause();
11632}
11633
Kelvin Libe286f52018-09-15 13:54:15 +000011634OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011635 OMPClause *C = nullptr;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011636 switch (llvm::omp::Clause(Record.readInt())) {
11637 case llvm::omp::OMPC_if:
Kelvin Libe286f52018-09-15 13:54:15 +000011638 C = new (Context) OMPIfClause();
11639 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011640 case llvm::omp::OMPC_final:
Kelvin Libe286f52018-09-15 13:54:15 +000011641 C = new (Context) OMPFinalClause();
11642 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011643 case llvm::omp::OMPC_num_threads:
Kelvin Libe286f52018-09-15 13:54:15 +000011644 C = new (Context) OMPNumThreadsClause();
11645 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011646 case llvm::omp::OMPC_safelen:
Kelvin Libe286f52018-09-15 13:54:15 +000011647 C = new (Context) OMPSafelenClause();
11648 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011649 case llvm::omp::OMPC_simdlen:
Kelvin Libe286f52018-09-15 13:54:15 +000011650 C = new (Context) OMPSimdlenClause();
11651 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011652 case llvm::omp::OMPC_allocator:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011653 C = new (Context) OMPAllocatorClause();
11654 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011655 case llvm::omp::OMPC_collapse:
Kelvin Libe286f52018-09-15 13:54:15 +000011656 C = new (Context) OMPCollapseClause();
11657 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011658 case llvm::omp::OMPC_default:
Kelvin Libe286f52018-09-15 13:54:15 +000011659 C = new (Context) OMPDefaultClause();
11660 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011661 case llvm::omp::OMPC_proc_bind:
Kelvin Libe286f52018-09-15 13:54:15 +000011662 C = new (Context) OMPProcBindClause();
11663 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011664 case llvm::omp::OMPC_schedule:
Kelvin Libe286f52018-09-15 13:54:15 +000011665 C = new (Context) OMPScheduleClause();
11666 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011667 case llvm::omp::OMPC_ordered:
Kelvin Libe286f52018-09-15 13:54:15 +000011668 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11669 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011670 case llvm::omp::OMPC_nowait:
Kelvin Libe286f52018-09-15 13:54:15 +000011671 C = new (Context) OMPNowaitClause();
11672 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011673 case llvm::omp::OMPC_untied:
Kelvin Libe286f52018-09-15 13:54:15 +000011674 C = new (Context) OMPUntiedClause();
11675 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011676 case llvm::omp::OMPC_mergeable:
Kelvin Libe286f52018-09-15 13:54:15 +000011677 C = new (Context) OMPMergeableClause();
11678 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011679 case llvm::omp::OMPC_read:
Kelvin Libe286f52018-09-15 13:54:15 +000011680 C = new (Context) OMPReadClause();
11681 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011682 case llvm::omp::OMPC_write:
Kelvin Libe286f52018-09-15 13:54:15 +000011683 C = new (Context) OMPWriteClause();
11684 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011685 case llvm::omp::OMPC_update:
Alexey Bataev82f7c202020-03-03 13:22:35 -050011686 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
Kelvin Libe286f52018-09-15 13:54:15 +000011687 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011688 case llvm::omp::OMPC_capture:
Kelvin Libe286f52018-09-15 13:54:15 +000011689 C = new (Context) OMPCaptureClause();
11690 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011691 case llvm::omp::OMPC_seq_cst:
Kelvin Libe286f52018-09-15 13:54:15 +000011692 C = new (Context) OMPSeqCstClause();
11693 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011694 case llvm::omp::OMPC_acq_rel:
Alexey Bataevea9166b2020-02-06 16:30:23 -050011695 C = new (Context) OMPAcqRelClause();
11696 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011697 case llvm::omp::OMPC_acquire:
Alexey Bataev04a830f2020-02-10 14:30:39 -050011698 C = new (Context) OMPAcquireClause();
11699 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011700 case llvm::omp::OMPC_release:
Alexey Bataev95598342020-02-10 15:49:05 -050011701 C = new (Context) OMPReleaseClause();
11702 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011703 case llvm::omp::OMPC_relaxed:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050011704 C = new (Context) OMPRelaxedClause();
11705 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011706 case llvm::omp::OMPC_threads:
Kelvin Libe286f52018-09-15 13:54:15 +000011707 C = new (Context) OMPThreadsClause();
11708 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011709 case llvm::omp::OMPC_simd:
Kelvin Libe286f52018-09-15 13:54:15 +000011710 C = new (Context) OMPSIMDClause();
11711 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011712 case llvm::omp::OMPC_nogroup:
Kelvin Libe286f52018-09-15 13:54:15 +000011713 C = new (Context) OMPNogroupClause();
11714 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011715 case llvm::omp::OMPC_unified_address:
Kelvin Li1408f912018-09-26 04:28:39 +000011716 C = new (Context) OMPUnifiedAddressClause();
11717 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011718 case llvm::omp::OMPC_unified_shared_memory:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011719 C = new (Context) OMPUnifiedSharedMemoryClause();
11720 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011721 case llvm::omp::OMPC_reverse_offload:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011722 C = new (Context) OMPReverseOffloadClause();
11723 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011724 case llvm::omp::OMPC_dynamic_allocators:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011725 C = new (Context) OMPDynamicAllocatorsClause();
11726 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011727 case llvm::omp::OMPC_atomic_default_mem_order:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011728 C = new (Context) OMPAtomicDefaultMemOrderClause();
11729 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011730 case llvm::omp::OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011731 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11732 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011733 case llvm::omp::OMPC_firstprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011734 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11735 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011736 case llvm::omp::OMPC_lastprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011737 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11738 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011739 case llvm::omp::OMPC_shared:
Kelvin Libe286f52018-09-15 13:54:15 +000011740 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11741 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011742 case llvm::omp::OMPC_reduction:
Kelvin Libe286f52018-09-15 13:54:15 +000011743 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11744 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011745 case llvm::omp::OMPC_task_reduction:
Kelvin Libe286f52018-09-15 13:54:15 +000011746 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11747 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011748 case llvm::omp::OMPC_in_reduction:
Kelvin Libe286f52018-09-15 13:54:15 +000011749 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11750 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011751 case llvm::omp::OMPC_linear:
Kelvin Libe286f52018-09-15 13:54:15 +000011752 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11753 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011754 case llvm::omp::OMPC_aligned:
Kelvin Libe286f52018-09-15 13:54:15 +000011755 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11756 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011757 case llvm::omp::OMPC_copyin:
Kelvin Libe286f52018-09-15 13:54:15 +000011758 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11759 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011760 case llvm::omp::OMPC_copyprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011761 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11762 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011763 case llvm::omp::OMPC_flush:
Kelvin Libe286f52018-09-15 13:54:15 +000011764 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11765 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011766 case llvm::omp::OMPC_depobj:
Alexey Bataevc112e942020-02-28 09:52:15 -050011767 C = OMPDepobjClause::CreateEmpty(Context);
11768 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011769 case llvm::omp::OMPC_depend: {
Kelvin Libe286f52018-09-15 13:54:15 +000011770 unsigned NumVars = Record.readInt();
11771 unsigned NumLoops = Record.readInt();
11772 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11773 break;
11774 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011775 case llvm::omp::OMPC_device:
Kelvin Libe286f52018-09-15 13:54:15 +000011776 C = new (Context) OMPDeviceClause();
11777 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011778 case llvm::omp::OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011779 OMPMappableExprListSizeTy Sizes;
11780 Sizes.NumVars = Record.readInt();
11781 Sizes.NumUniqueDeclarations = Record.readInt();
11782 Sizes.NumComponentLists = Record.readInt();
11783 Sizes.NumComponents = Record.readInt();
11784 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011785 break;
11786 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011787 case llvm::omp::OMPC_num_teams:
Kelvin Libe286f52018-09-15 13:54:15 +000011788 C = new (Context) OMPNumTeamsClause();
11789 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011790 case llvm::omp::OMPC_thread_limit:
Kelvin Libe286f52018-09-15 13:54:15 +000011791 C = new (Context) OMPThreadLimitClause();
11792 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011793 case llvm::omp::OMPC_priority:
Kelvin Libe286f52018-09-15 13:54:15 +000011794 C = new (Context) OMPPriorityClause();
11795 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011796 case llvm::omp::OMPC_grainsize:
Kelvin Libe286f52018-09-15 13:54:15 +000011797 C = new (Context) OMPGrainsizeClause();
11798 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011799 case llvm::omp::OMPC_num_tasks:
Kelvin Libe286f52018-09-15 13:54:15 +000011800 C = new (Context) OMPNumTasksClause();
11801 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011802 case llvm::omp::OMPC_hint:
Kelvin Libe286f52018-09-15 13:54:15 +000011803 C = new (Context) OMPHintClause();
11804 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011805 case llvm::omp::OMPC_dist_schedule:
Kelvin Libe286f52018-09-15 13:54:15 +000011806 C = new (Context) OMPDistScheduleClause();
11807 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011808 case llvm::omp::OMPC_defaultmap:
Kelvin Libe286f52018-09-15 13:54:15 +000011809 C = new (Context) OMPDefaultmapClause();
11810 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011811 case llvm::omp::OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011812 OMPMappableExprListSizeTy Sizes;
11813 Sizes.NumVars = Record.readInt();
11814 Sizes.NumUniqueDeclarations = Record.readInt();
11815 Sizes.NumComponentLists = Record.readInt();
11816 Sizes.NumComponents = Record.readInt();
11817 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011818 break;
11819 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011820 case llvm::omp::OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011821 OMPMappableExprListSizeTy Sizes;
11822 Sizes.NumVars = Record.readInt();
11823 Sizes.NumUniqueDeclarations = Record.readInt();
11824 Sizes.NumComponentLists = Record.readInt();
11825 Sizes.NumComponents = Record.readInt();
11826 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011827 break;
11828 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011829 case llvm::omp::OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011830 OMPMappableExprListSizeTy Sizes;
11831 Sizes.NumVars = Record.readInt();
11832 Sizes.NumUniqueDeclarations = Record.readInt();
11833 Sizes.NumComponentLists = Record.readInt();
11834 Sizes.NumComponents = Record.readInt();
11835 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011836 break;
11837 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011838 case llvm::omp::OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011839 OMPMappableExprListSizeTy Sizes;
11840 Sizes.NumVars = Record.readInt();
11841 Sizes.NumUniqueDeclarations = Record.readInt();
11842 Sizes.NumComponentLists = Record.readInt();
11843 Sizes.NumComponents = Record.readInt();
11844 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011845 break;
11846 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011847 case llvm::omp::OMPC_allocate:
Alexey Bataeve04483e2019-03-27 14:14:31 +000011848 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11849 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011850 case llvm::omp::OMPC_nontemporal:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011851 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11852 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011853 case llvm::omp::OMPC_inclusive:
Alexey Bataev06dea732020-03-20 09:41:22 -040011854 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11855 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011856 case llvm::omp::OMPC_exclusive:
Alexey Bataev63828a32020-03-23 10:41:08 -040011857 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11858 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011859 case llvm::omp::OMPC_order:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011860 C = new (Context) OMPOrderClause();
11861 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011862 case llvm::omp::OMPC_destroy:
Alexey Bataev375437a2020-03-02 14:21:20 -050011863 C = new (Context) OMPDestroyClause();
11864 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011865 case llvm::omp::OMPC_detach:
Alexey Bataev0f0564b2020-03-17 09:17:42 -040011866 C = new (Context) OMPDetachClause();
11867 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011868#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11869 case llvm::omp::Enum: \
11870 break;
11871#include "llvm/Frontend/OpenMP/OMPKinds.def"
Kelvin Libe286f52018-09-15 13:54:15 +000011872 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011873 assert(C && "Unknown OMPClause type");
11874
Kelvin Libe286f52018-09-15 13:54:15 +000011875 Visit(C);
11876 C->setLocStart(Record.readSourceLocation());
11877 C->setLocEnd(Record.readSourceLocation());
11878
11879 return C;
11880}
11881
11882void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11883 C->setPreInitStmt(Record.readSubStmt(),
11884 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11885}
11886
11887void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11888 VisitOMPClauseWithPreInit(C);
11889 C->setPostUpdateExpr(Record.readSubExpr());
11890}
11891
11892void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11893 VisitOMPClauseWithPreInit(C);
11894 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11895 C->setNameModifierLoc(Record.readSourceLocation());
11896 C->setColonLoc(Record.readSourceLocation());
11897 C->setCondition(Record.readSubExpr());
11898 C->setLParenLoc(Record.readSourceLocation());
11899}
11900
11901void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011902 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000011903 C->setCondition(Record.readSubExpr());
11904 C->setLParenLoc(Record.readSourceLocation());
11905}
11906
11907void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11908 VisitOMPClauseWithPreInit(C);
11909 C->setNumThreads(Record.readSubExpr());
11910 C->setLParenLoc(Record.readSourceLocation());
11911}
11912
11913void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11914 C->setSafelen(Record.readSubExpr());
11915 C->setLParenLoc(Record.readSourceLocation());
11916}
11917
11918void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11919 C->setSimdlen(Record.readSubExpr());
11920 C->setLParenLoc(Record.readSourceLocation());
11921}
11922
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011923void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11924 C->setAllocator(Record.readExpr());
11925 C->setLParenLoc(Record.readSourceLocation());
11926}
11927
Kelvin Libe286f52018-09-15 13:54:15 +000011928void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11929 C->setNumForLoops(Record.readSubExpr());
11930 C->setLParenLoc(Record.readSourceLocation());
11931}
11932
11933void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
Atmn Patel577c9b02020-02-14 21:45:49 -060011934 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
Kelvin Libe286f52018-09-15 13:54:15 +000011935 C->setLParenLoc(Record.readSourceLocation());
11936 C->setDefaultKindKwLoc(Record.readSourceLocation());
11937}
11938
11939void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011940 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
Kelvin Libe286f52018-09-15 13:54:15 +000011941 C->setLParenLoc(Record.readSourceLocation());
11942 C->setProcBindKindKwLoc(Record.readSourceLocation());
11943}
11944
11945void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11946 VisitOMPClauseWithPreInit(C);
11947 C->setScheduleKind(
11948 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11949 C->setFirstScheduleModifier(
11950 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11951 C->setSecondScheduleModifier(
11952 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11953 C->setChunkSize(Record.readSubExpr());
11954 C->setLParenLoc(Record.readSourceLocation());
11955 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11956 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11957 C->setScheduleKindLoc(Record.readSourceLocation());
11958 C->setCommaLoc(Record.readSourceLocation());
11959}
11960
11961void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11962 C->setNumForLoops(Record.readSubExpr());
11963 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11964 C->setLoopNumIterations(I, Record.readSubExpr());
11965 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11966 C->setLoopCounter(I, Record.readSubExpr());
11967 C->setLParenLoc(Record.readSourceLocation());
11968}
11969
Alexey Bataev0f0564b2020-03-17 09:17:42 -040011970void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11971 C->setEventHandler(Record.readSubExpr());
11972 C->setLParenLoc(Record.readSourceLocation());
11973}
11974
Kelvin Libe286f52018-09-15 13:54:15 +000011975void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11976
11977void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11978
11979void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11980
11981void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11982
11983void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11984
Alexey Bataev82f7c202020-03-03 13:22:35 -050011985void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11986 if (C->isExtended()) {
11987 C->setLParenLoc(Record.readSourceLocation());
11988 C->setArgumentLoc(Record.readSourceLocation());
11989 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11990 }
11991}
Kelvin Libe286f52018-09-15 13:54:15 +000011992
11993void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11994
11995void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11996
Alexey Bataevea9166b2020-02-06 16:30:23 -050011997void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11998
Alexey Bataev04a830f2020-02-10 14:30:39 -050011999void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12000
Alexey Bataev95598342020-02-10 15:49:05 -050012001void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12002
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012003void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12004
Kelvin Libe286f52018-09-15 13:54:15 +000012005void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12006
12007void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12008
12009void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12010
Alexey Bataev375437a2020-03-02 14:21:20 -050012011void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *) {}
12012
Kelvin Li1408f912018-09-26 04:28:39 +000012013void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12014
Patrick Lyster4a370b92018-10-01 13:47:43 +000012015void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12016 OMPUnifiedSharedMemoryClause *) {}
12017
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012018void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12019
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012020void
12021OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12022}
12023
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012024void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12025 OMPAtomicDefaultMemOrderClause *C) {
12026 C->setAtomicDefaultMemOrderKind(
12027 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12028 C->setLParenLoc(Record.readSourceLocation());
12029 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12030}
12031
Kelvin Libe286f52018-09-15 13:54:15 +000012032void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12033 C->setLParenLoc(Record.readSourceLocation());
12034 unsigned NumVars = C->varlist_size();
12035 SmallVector<Expr *, 16> Vars;
12036 Vars.reserve(NumVars);
12037 for (unsigned i = 0; i != NumVars; ++i)
12038 Vars.push_back(Record.readSubExpr());
12039 C->setVarRefs(Vars);
12040 Vars.clear();
12041 for (unsigned i = 0; i != NumVars; ++i)
12042 Vars.push_back(Record.readSubExpr());
12043 C->setPrivateCopies(Vars);
12044}
12045
12046void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12047 VisitOMPClauseWithPreInit(C);
12048 C->setLParenLoc(Record.readSourceLocation());
12049 unsigned NumVars = C->varlist_size();
12050 SmallVector<Expr *, 16> Vars;
12051 Vars.reserve(NumVars);
12052 for (unsigned i = 0; i != NumVars; ++i)
12053 Vars.push_back(Record.readSubExpr());
12054 C->setVarRefs(Vars);
12055 Vars.clear();
12056 for (unsigned i = 0; i != NumVars; ++i)
12057 Vars.push_back(Record.readSubExpr());
12058 C->setPrivateCopies(Vars);
12059 Vars.clear();
12060 for (unsigned i = 0; i != NumVars; ++i)
12061 Vars.push_back(Record.readSubExpr());
12062 C->setInits(Vars);
12063}
12064
12065void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12066 VisitOMPClauseWithPostUpdate(C);
12067 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012068 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12069 C->setKindLoc(Record.readSourceLocation());
12070 C->setColonLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012071 unsigned NumVars = C->varlist_size();
12072 SmallVector<Expr *, 16> Vars;
12073 Vars.reserve(NumVars);
12074 for (unsigned i = 0; i != NumVars; ++i)
12075 Vars.push_back(Record.readSubExpr());
12076 C->setVarRefs(Vars);
12077 Vars.clear();
12078 for (unsigned i = 0; i != NumVars; ++i)
12079 Vars.push_back(Record.readSubExpr());
12080 C->setPrivateCopies(Vars);
12081 Vars.clear();
12082 for (unsigned i = 0; i != NumVars; ++i)
12083 Vars.push_back(Record.readSubExpr());
12084 C->setSourceExprs(Vars);
12085 Vars.clear();
12086 for (unsigned i = 0; i != NumVars; ++i)
12087 Vars.push_back(Record.readSubExpr());
12088 C->setDestinationExprs(Vars);
12089 Vars.clear();
12090 for (unsigned i = 0; i != NumVars; ++i)
12091 Vars.push_back(Record.readSubExpr());
12092 C->setAssignmentOps(Vars);
12093}
12094
12095void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12096 C->setLParenLoc(Record.readSourceLocation());
12097 unsigned NumVars = C->varlist_size();
12098 SmallVector<Expr *, 16> Vars;
12099 Vars.reserve(NumVars);
12100 for (unsigned i = 0; i != NumVars; ++i)
12101 Vars.push_back(Record.readSubExpr());
12102 C->setVarRefs(Vars);
12103}
12104
12105void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12106 VisitOMPClauseWithPostUpdate(C);
12107 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev1236eb62020-03-23 17:30:38 -040012108 C->setModifierLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012109 C->setColonLoc(Record.readSourceLocation());
Alexey Bataev1236eb62020-03-23 17:30:38 -040012110 C->setModifier(Record.readEnum<OpenMPReductionClauseModifier>());
Kelvin Libe286f52018-09-15 13:54:15 +000012111 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012112 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012113 C->setQualifierLoc(NNSL);
12114 C->setNameInfo(DNI);
12115
12116 unsigned NumVars = C->varlist_size();
12117 SmallVector<Expr *, 16> Vars;
12118 Vars.reserve(NumVars);
12119 for (unsigned i = 0; i != NumVars; ++i)
12120 Vars.push_back(Record.readSubExpr());
12121 C->setVarRefs(Vars);
12122 Vars.clear();
12123 for (unsigned i = 0; i != NumVars; ++i)
12124 Vars.push_back(Record.readSubExpr());
12125 C->setPrivates(Vars);
12126 Vars.clear();
12127 for (unsigned i = 0; i != NumVars; ++i)
12128 Vars.push_back(Record.readSubExpr());
12129 C->setLHSExprs(Vars);
12130 Vars.clear();
12131 for (unsigned i = 0; i != NumVars; ++i)
12132 Vars.push_back(Record.readSubExpr());
12133 C->setRHSExprs(Vars);
12134 Vars.clear();
12135 for (unsigned i = 0; i != NumVars; ++i)
12136 Vars.push_back(Record.readSubExpr());
12137 C->setReductionOps(Vars);
12138}
12139
12140void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12141 VisitOMPClauseWithPostUpdate(C);
12142 C->setLParenLoc(Record.readSourceLocation());
12143 C->setColonLoc(Record.readSourceLocation());
12144 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012145 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012146 C->setQualifierLoc(NNSL);
12147 C->setNameInfo(DNI);
12148
12149 unsigned NumVars = C->varlist_size();
12150 SmallVector<Expr *, 16> Vars;
12151 Vars.reserve(NumVars);
12152 for (unsigned I = 0; I != NumVars; ++I)
12153 Vars.push_back(Record.readSubExpr());
12154 C->setVarRefs(Vars);
12155 Vars.clear();
12156 for (unsigned I = 0; I != NumVars; ++I)
12157 Vars.push_back(Record.readSubExpr());
12158 C->setPrivates(Vars);
12159 Vars.clear();
12160 for (unsigned I = 0; I != NumVars; ++I)
12161 Vars.push_back(Record.readSubExpr());
12162 C->setLHSExprs(Vars);
12163 Vars.clear();
12164 for (unsigned I = 0; I != NumVars; ++I)
12165 Vars.push_back(Record.readSubExpr());
12166 C->setRHSExprs(Vars);
12167 Vars.clear();
12168 for (unsigned I = 0; I != NumVars; ++I)
12169 Vars.push_back(Record.readSubExpr());
12170 C->setReductionOps(Vars);
12171}
12172
12173void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12174 VisitOMPClauseWithPostUpdate(C);
12175 C->setLParenLoc(Record.readSourceLocation());
12176 C->setColonLoc(Record.readSourceLocation());
12177 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012178 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012179 C->setQualifierLoc(NNSL);
12180 C->setNameInfo(DNI);
12181
12182 unsigned NumVars = C->varlist_size();
12183 SmallVector<Expr *, 16> Vars;
12184 Vars.reserve(NumVars);
12185 for (unsigned I = 0; I != NumVars; ++I)
12186 Vars.push_back(Record.readSubExpr());
12187 C->setVarRefs(Vars);
12188 Vars.clear();
12189 for (unsigned I = 0; I != NumVars; ++I)
12190 Vars.push_back(Record.readSubExpr());
12191 C->setPrivates(Vars);
12192 Vars.clear();
12193 for (unsigned I = 0; I != NumVars; ++I)
12194 Vars.push_back(Record.readSubExpr());
12195 C->setLHSExprs(Vars);
12196 Vars.clear();
12197 for (unsigned I = 0; I != NumVars; ++I)
12198 Vars.push_back(Record.readSubExpr());
12199 C->setRHSExprs(Vars);
12200 Vars.clear();
12201 for (unsigned I = 0; I != NumVars; ++I)
12202 Vars.push_back(Record.readSubExpr());
12203 C->setReductionOps(Vars);
12204 Vars.clear();
12205 for (unsigned I = 0; I != NumVars; ++I)
12206 Vars.push_back(Record.readSubExpr());
12207 C->setTaskgroupDescriptors(Vars);
12208}
12209
12210void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12211 VisitOMPClauseWithPostUpdate(C);
12212 C->setLParenLoc(Record.readSourceLocation());
12213 C->setColonLoc(Record.readSourceLocation());
12214 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12215 C->setModifierLoc(Record.readSourceLocation());
12216 unsigned NumVars = C->varlist_size();
12217 SmallVector<Expr *, 16> Vars;
12218 Vars.reserve(NumVars);
12219 for (unsigned i = 0; i != NumVars; ++i)
12220 Vars.push_back(Record.readSubExpr());
12221 C->setVarRefs(Vars);
12222 Vars.clear();
12223 for (unsigned i = 0; i != NumVars; ++i)
12224 Vars.push_back(Record.readSubExpr());
12225 C->setPrivates(Vars);
12226 Vars.clear();
12227 for (unsigned i = 0; i != NumVars; ++i)
12228 Vars.push_back(Record.readSubExpr());
12229 C->setInits(Vars);
12230 Vars.clear();
12231 for (unsigned i = 0; i != NumVars; ++i)
12232 Vars.push_back(Record.readSubExpr());
12233 C->setUpdates(Vars);
12234 Vars.clear();
12235 for (unsigned i = 0; i != NumVars; ++i)
12236 Vars.push_back(Record.readSubExpr());
12237 C->setFinals(Vars);
12238 C->setStep(Record.readSubExpr());
12239 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012240 Vars.clear();
12241 for (unsigned I = 0; I != NumVars + 1; ++I)
12242 Vars.push_back(Record.readSubExpr());
12243 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012244}
12245
12246void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12247 C->setLParenLoc(Record.readSourceLocation());
12248 C->setColonLoc(Record.readSourceLocation());
12249 unsigned NumVars = C->varlist_size();
12250 SmallVector<Expr *, 16> Vars;
12251 Vars.reserve(NumVars);
12252 for (unsigned i = 0; i != NumVars; ++i)
12253 Vars.push_back(Record.readSubExpr());
12254 C->setVarRefs(Vars);
12255 C->setAlignment(Record.readSubExpr());
12256}
12257
12258void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12259 C->setLParenLoc(Record.readSourceLocation());
12260 unsigned NumVars = C->varlist_size();
12261 SmallVector<Expr *, 16> Exprs;
12262 Exprs.reserve(NumVars);
12263 for (unsigned i = 0; i != NumVars; ++i)
12264 Exprs.push_back(Record.readSubExpr());
12265 C->setVarRefs(Exprs);
12266 Exprs.clear();
12267 for (unsigned i = 0; i != NumVars; ++i)
12268 Exprs.push_back(Record.readSubExpr());
12269 C->setSourceExprs(Exprs);
12270 Exprs.clear();
12271 for (unsigned i = 0; i != NumVars; ++i)
12272 Exprs.push_back(Record.readSubExpr());
12273 C->setDestinationExprs(Exprs);
12274 Exprs.clear();
12275 for (unsigned i = 0; i != NumVars; ++i)
12276 Exprs.push_back(Record.readSubExpr());
12277 C->setAssignmentOps(Exprs);
12278}
12279
12280void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12281 C->setLParenLoc(Record.readSourceLocation());
12282 unsigned NumVars = C->varlist_size();
12283 SmallVector<Expr *, 16> Exprs;
12284 Exprs.reserve(NumVars);
12285 for (unsigned i = 0; i != NumVars; ++i)
12286 Exprs.push_back(Record.readSubExpr());
12287 C->setVarRefs(Exprs);
12288 Exprs.clear();
12289 for (unsigned i = 0; i != NumVars; ++i)
12290 Exprs.push_back(Record.readSubExpr());
12291 C->setSourceExprs(Exprs);
12292 Exprs.clear();
12293 for (unsigned i = 0; i != NumVars; ++i)
12294 Exprs.push_back(Record.readSubExpr());
12295 C->setDestinationExprs(Exprs);
12296 Exprs.clear();
12297 for (unsigned i = 0; i != NumVars; ++i)
12298 Exprs.push_back(Record.readSubExpr());
12299 C->setAssignmentOps(Exprs);
12300}
12301
12302void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12303 C->setLParenLoc(Record.readSourceLocation());
12304 unsigned NumVars = C->varlist_size();
12305 SmallVector<Expr *, 16> Vars;
12306 Vars.reserve(NumVars);
12307 for (unsigned i = 0; i != NumVars; ++i)
12308 Vars.push_back(Record.readSubExpr());
12309 C->setVarRefs(Vars);
12310}
12311
Alexey Bataevc112e942020-02-28 09:52:15 -050012312void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12313 C->setDepobj(Record.readSubExpr());
12314 C->setLParenLoc(Record.readSourceLocation());
12315}
12316
Kelvin Libe286f52018-09-15 13:54:15 +000012317void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12318 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev13a15042020-04-01 15:06:38 -040012319 C->setModifier(Record.readSubExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012320 C->setDependencyKind(
12321 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12322 C->setDependencyLoc(Record.readSourceLocation());
12323 C->setColonLoc(Record.readSourceLocation());
12324 unsigned NumVars = C->varlist_size();
12325 SmallVector<Expr *, 16> Vars;
12326 Vars.reserve(NumVars);
12327 for (unsigned I = 0; I != NumVars; ++I)
12328 Vars.push_back(Record.readSubExpr());
12329 C->setVarRefs(Vars);
12330 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12331 C->setLoopData(I, Record.readSubExpr());
12332}
12333
12334void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12335 VisitOMPClauseWithPreInit(C);
Alexey Bataev2f8894a2020-03-18 15:01:15 -040012336 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
Kelvin Libe286f52018-09-15 13:54:15 +000012337 C->setDevice(Record.readSubExpr());
Alexey Bataev2f8894a2020-03-18 15:01:15 -040012338 C->setModifierLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012339 C->setLParenLoc(Record.readSourceLocation());
12340}
12341
12342void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12343 C->setLParenLoc(Record.readSourceLocation());
Reid Klecknerba1ffd22020-04-03 12:35:30 -070012344 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
Kelvin Lief579432018-12-18 22:18:41 +000012345 C->setMapTypeModifier(
12346 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12347 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12348 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012349 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012350 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012351 C->setMapType(
12352 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12353 C->setMapLoc(Record.readSourceLocation());
12354 C->setColonLoc(Record.readSourceLocation());
12355 auto NumVars = C->varlist_size();
12356 auto UniqueDecls = C->getUniqueDeclarationsNum();
12357 auto TotalLists = C->getTotalComponentListNum();
12358 auto TotalComponents = C->getTotalComponentsNum();
12359
12360 SmallVector<Expr *, 16> Vars;
12361 Vars.reserve(NumVars);
12362 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012363 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012364 C->setVarRefs(Vars);
12365
Michael Kruse4304e9d2019-02-19 16:38:20 +000012366 SmallVector<Expr *, 16> UDMappers;
12367 UDMappers.reserve(NumVars);
12368 for (unsigned I = 0; I < NumVars; ++I)
12369 UDMappers.push_back(Record.readExpr());
12370 C->setUDMapperRefs(UDMappers);
12371
Kelvin Libe286f52018-09-15 13:54:15 +000012372 SmallVector<ValueDecl *, 16> Decls;
12373 Decls.reserve(UniqueDecls);
12374 for (unsigned i = 0; i < UniqueDecls; ++i)
12375 Decls.push_back(Record.readDeclAs<ValueDecl>());
12376 C->setUniqueDecls(Decls);
12377
12378 SmallVector<unsigned, 16> ListsPerDecl;
12379 ListsPerDecl.reserve(UniqueDecls);
12380 for (unsigned i = 0; i < UniqueDecls; ++i)
12381 ListsPerDecl.push_back(Record.readInt());
12382 C->setDeclNumLists(ListsPerDecl);
12383
12384 SmallVector<unsigned, 32> ListSizes;
12385 ListSizes.reserve(TotalLists);
12386 for (unsigned i = 0; i < TotalLists; ++i)
12387 ListSizes.push_back(Record.readInt());
12388 C->setComponentListSizes(ListSizes);
12389
12390 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12391 Components.reserve(TotalComponents);
12392 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012393 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012394 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12395 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12396 AssociatedExpr, AssociatedDecl));
12397 }
12398 C->setComponents(Components, ListSizes);
12399}
12400
Alexey Bataeve04483e2019-03-27 14:14:31 +000012401void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12402 C->setLParenLoc(Record.readSourceLocation());
12403 C->setColonLoc(Record.readSourceLocation());
12404 C->setAllocator(Record.readSubExpr());
12405 unsigned NumVars = C->varlist_size();
12406 SmallVector<Expr *, 16> Vars;
12407 Vars.reserve(NumVars);
12408 for (unsigned i = 0; i != NumVars; ++i)
12409 Vars.push_back(Record.readSubExpr());
12410 C->setVarRefs(Vars);
12411}
12412
Kelvin Libe286f52018-09-15 13:54:15 +000012413void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12414 VisitOMPClauseWithPreInit(C);
12415 C->setNumTeams(Record.readSubExpr());
12416 C->setLParenLoc(Record.readSourceLocation());
12417}
12418
12419void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12420 VisitOMPClauseWithPreInit(C);
12421 C->setThreadLimit(Record.readSubExpr());
12422 C->setLParenLoc(Record.readSourceLocation());
12423}
12424
12425void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +000012426 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012427 C->setPriority(Record.readSubExpr());
12428 C->setLParenLoc(Record.readSourceLocation());
12429}
12430
12431void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000012432 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012433 C->setGrainsize(Record.readSubExpr());
12434 C->setLParenLoc(Record.readSourceLocation());
12435}
12436
12437void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000012438 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012439 C->setNumTasks(Record.readSubExpr());
12440 C->setLParenLoc(Record.readSourceLocation());
12441}
12442
12443void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12444 C->setHint(Record.readSubExpr());
12445 C->setLParenLoc(Record.readSourceLocation());
12446}
12447
12448void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12449 VisitOMPClauseWithPreInit(C);
12450 C->setDistScheduleKind(
12451 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12452 C->setChunkSize(Record.readSubExpr());
12453 C->setLParenLoc(Record.readSourceLocation());
12454 C->setDistScheduleKindLoc(Record.readSourceLocation());
12455 C->setCommaLoc(Record.readSourceLocation());
12456}
12457
12458void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12459 C->setDefaultmapKind(
12460 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12461 C->setDefaultmapModifier(
12462 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12463 C->setLParenLoc(Record.readSourceLocation());
12464 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12465 C->setDefaultmapKindLoc(Record.readSourceLocation());
12466}
12467
12468void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12469 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012470 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012471 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012472 auto NumVars = C->varlist_size();
12473 auto UniqueDecls = C->getUniqueDeclarationsNum();
12474 auto TotalLists = C->getTotalComponentListNum();
12475 auto TotalComponents = C->getTotalComponentsNum();
12476
12477 SmallVector<Expr *, 16> Vars;
12478 Vars.reserve(NumVars);
12479 for (unsigned i = 0; i != NumVars; ++i)
12480 Vars.push_back(Record.readSubExpr());
12481 C->setVarRefs(Vars);
12482
Michael Kruse01f670d2019-02-22 22:29:42 +000012483 SmallVector<Expr *, 16> UDMappers;
12484 UDMappers.reserve(NumVars);
12485 for (unsigned I = 0; I < NumVars; ++I)
12486 UDMappers.push_back(Record.readSubExpr());
12487 C->setUDMapperRefs(UDMappers);
12488
Kelvin Libe286f52018-09-15 13:54:15 +000012489 SmallVector<ValueDecl *, 16> Decls;
12490 Decls.reserve(UniqueDecls);
12491 for (unsigned i = 0; i < UniqueDecls; ++i)
12492 Decls.push_back(Record.readDeclAs<ValueDecl>());
12493 C->setUniqueDecls(Decls);
12494
12495 SmallVector<unsigned, 16> ListsPerDecl;
12496 ListsPerDecl.reserve(UniqueDecls);
12497 for (unsigned i = 0; i < UniqueDecls; ++i)
12498 ListsPerDecl.push_back(Record.readInt());
12499 C->setDeclNumLists(ListsPerDecl);
12500
12501 SmallVector<unsigned, 32> ListSizes;
12502 ListSizes.reserve(TotalLists);
12503 for (unsigned i = 0; i < TotalLists; ++i)
12504 ListSizes.push_back(Record.readInt());
12505 C->setComponentListSizes(ListSizes);
12506
12507 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12508 Components.reserve(TotalComponents);
12509 for (unsigned i = 0; i < TotalComponents; ++i) {
12510 Expr *AssociatedExpr = Record.readSubExpr();
12511 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12512 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12513 AssociatedExpr, AssociatedDecl));
12514 }
12515 C->setComponents(Components, ListSizes);
12516}
12517
12518void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12519 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012520 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012521 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012522 auto NumVars = C->varlist_size();
12523 auto UniqueDecls = C->getUniqueDeclarationsNum();
12524 auto TotalLists = C->getTotalComponentListNum();
12525 auto TotalComponents = C->getTotalComponentsNum();
12526
12527 SmallVector<Expr *, 16> Vars;
12528 Vars.reserve(NumVars);
12529 for (unsigned i = 0; i != NumVars; ++i)
12530 Vars.push_back(Record.readSubExpr());
12531 C->setVarRefs(Vars);
12532
Michael Kruse0336c752019-02-25 20:34:15 +000012533 SmallVector<Expr *, 16> UDMappers;
12534 UDMappers.reserve(NumVars);
12535 for (unsigned I = 0; I < NumVars; ++I)
12536 UDMappers.push_back(Record.readSubExpr());
12537 C->setUDMapperRefs(UDMappers);
12538
Kelvin Libe286f52018-09-15 13:54:15 +000012539 SmallVector<ValueDecl *, 16> Decls;
12540 Decls.reserve(UniqueDecls);
12541 for (unsigned i = 0; i < UniqueDecls; ++i)
12542 Decls.push_back(Record.readDeclAs<ValueDecl>());
12543 C->setUniqueDecls(Decls);
12544
12545 SmallVector<unsigned, 16> ListsPerDecl;
12546 ListsPerDecl.reserve(UniqueDecls);
12547 for (unsigned i = 0; i < UniqueDecls; ++i)
12548 ListsPerDecl.push_back(Record.readInt());
12549 C->setDeclNumLists(ListsPerDecl);
12550
12551 SmallVector<unsigned, 32> ListSizes;
12552 ListSizes.reserve(TotalLists);
12553 for (unsigned i = 0; i < TotalLists; ++i)
12554 ListSizes.push_back(Record.readInt());
12555 C->setComponentListSizes(ListSizes);
12556
12557 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12558 Components.reserve(TotalComponents);
12559 for (unsigned i = 0; i < TotalComponents; ++i) {
12560 Expr *AssociatedExpr = Record.readSubExpr();
12561 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12562 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12563 AssociatedExpr, AssociatedDecl));
12564 }
12565 C->setComponents(Components, ListSizes);
12566}
12567
12568void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12569 C->setLParenLoc(Record.readSourceLocation());
12570 auto NumVars = C->varlist_size();
12571 auto UniqueDecls = C->getUniqueDeclarationsNum();
12572 auto TotalLists = C->getTotalComponentListNum();
12573 auto TotalComponents = C->getTotalComponentsNum();
12574
12575 SmallVector<Expr *, 16> Vars;
12576 Vars.reserve(NumVars);
12577 for (unsigned i = 0; i != NumVars; ++i)
12578 Vars.push_back(Record.readSubExpr());
12579 C->setVarRefs(Vars);
12580 Vars.clear();
12581 for (unsigned i = 0; i != NumVars; ++i)
12582 Vars.push_back(Record.readSubExpr());
12583 C->setPrivateCopies(Vars);
12584 Vars.clear();
12585 for (unsigned i = 0; i != NumVars; ++i)
12586 Vars.push_back(Record.readSubExpr());
12587 C->setInits(Vars);
12588
12589 SmallVector<ValueDecl *, 16> Decls;
12590 Decls.reserve(UniqueDecls);
12591 for (unsigned i = 0; i < UniqueDecls; ++i)
12592 Decls.push_back(Record.readDeclAs<ValueDecl>());
12593 C->setUniqueDecls(Decls);
12594
12595 SmallVector<unsigned, 16> ListsPerDecl;
12596 ListsPerDecl.reserve(UniqueDecls);
12597 for (unsigned i = 0; i < UniqueDecls; ++i)
12598 ListsPerDecl.push_back(Record.readInt());
12599 C->setDeclNumLists(ListsPerDecl);
12600
12601 SmallVector<unsigned, 32> ListSizes;
12602 ListSizes.reserve(TotalLists);
12603 for (unsigned i = 0; i < TotalLists; ++i)
12604 ListSizes.push_back(Record.readInt());
12605 C->setComponentListSizes(ListSizes);
12606
12607 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12608 Components.reserve(TotalComponents);
12609 for (unsigned i = 0; i < TotalComponents; ++i) {
12610 Expr *AssociatedExpr = Record.readSubExpr();
12611 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12612 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12613 AssociatedExpr, AssociatedDecl));
12614 }
12615 C->setComponents(Components, ListSizes);
12616}
12617
12618void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12619 C->setLParenLoc(Record.readSourceLocation());
12620 auto NumVars = C->varlist_size();
12621 auto UniqueDecls = C->getUniqueDeclarationsNum();
12622 auto TotalLists = C->getTotalComponentListNum();
12623 auto TotalComponents = C->getTotalComponentsNum();
12624
12625 SmallVector<Expr *, 16> Vars;
12626 Vars.reserve(NumVars);
12627 for (unsigned i = 0; i != NumVars; ++i)
12628 Vars.push_back(Record.readSubExpr());
12629 C->setVarRefs(Vars);
12630 Vars.clear();
12631
12632 SmallVector<ValueDecl *, 16> Decls;
12633 Decls.reserve(UniqueDecls);
12634 for (unsigned i = 0; i < UniqueDecls; ++i)
12635 Decls.push_back(Record.readDeclAs<ValueDecl>());
12636 C->setUniqueDecls(Decls);
12637
12638 SmallVector<unsigned, 16> ListsPerDecl;
12639 ListsPerDecl.reserve(UniqueDecls);
12640 for (unsigned i = 0; i < UniqueDecls; ++i)
12641 ListsPerDecl.push_back(Record.readInt());
12642 C->setDeclNumLists(ListsPerDecl);
12643
12644 SmallVector<unsigned, 32> ListSizes;
12645 ListSizes.reserve(TotalLists);
12646 for (unsigned i = 0; i < TotalLists; ++i)
12647 ListSizes.push_back(Record.readInt());
12648 C->setComponentListSizes(ListSizes);
12649
12650 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12651 Components.reserve(TotalComponents);
12652 for (unsigned i = 0; i < TotalComponents; ++i) {
12653 Expr *AssociatedExpr = Record.readSubExpr();
12654 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12655 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12656 AssociatedExpr, AssociatedDecl));
12657 }
12658 C->setComponents(Components, ListSizes);
12659}
Alexey Bataevb6e70842019-12-16 15:54:17 -050012660
12661void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12662 C->setLParenLoc(Record.readSourceLocation());
12663 unsigned NumVars = C->varlist_size();
12664 SmallVector<Expr *, 16> Vars;
12665 Vars.reserve(NumVars);
12666 for (unsigned i = 0; i != NumVars; ++i)
12667 Vars.push_back(Record.readSubExpr());
12668 C->setVarRefs(Vars);
Alexey Bataev0860db92019-12-19 10:01:10 -050012669 Vars.clear();
12670 Vars.reserve(NumVars);
12671 for (unsigned i = 0; i != NumVars; ++i)
12672 Vars.push_back(Record.readSubExpr());
12673 C->setPrivateRefs(Vars);
Alexey Bataevb6e70842019-12-16 15:54:17 -050012674}
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012675
Alexey Bataev06dea732020-03-20 09:41:22 -040012676void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12677 C->setLParenLoc(Record.readSourceLocation());
12678 unsigned NumVars = C->varlist_size();
12679 SmallVector<Expr *, 16> Vars;
12680 Vars.reserve(NumVars);
12681 for (unsigned i = 0; i != NumVars; ++i)
12682 Vars.push_back(Record.readSubExpr());
12683 C->setVarRefs(Vars);
12684}
12685
Alexey Bataev63828a32020-03-23 10:41:08 -040012686void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12687 C->setLParenLoc(Record.readSourceLocation());
12688 unsigned NumVars = C->varlist_size();
12689 SmallVector<Expr *, 16> Vars;
12690 Vars.reserve(NumVars);
12691 for (unsigned i = 0; i != NumVars; ++i)
12692 Vars.push_back(Record.readSubExpr());
12693 C->setVarRefs(Vars);
12694}
12695
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012696void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12697 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12698 C->setLParenLoc(Record.readSourceLocation());
12699 C->setKindKwLoc(Record.readSourceLocation());
12700}
Johannes Doerfert1228d422019-12-19 20:42:12 -060012701
Johannes Doerfert55eca282020-03-13 23:42:05 -050012702OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
12703 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
Johannes Doerfertb86bf832020-02-15 18:07:42 -060012704 TI.Sets.resize(readUInt32());
12705 for (auto &Set : TI.Sets) {
Johannes Doerfert1228d422019-12-19 20:42:12 -060012706 Set.Kind = readEnum<llvm::omp::TraitSet>();
12707 Set.Selectors.resize(readUInt32());
12708 for (auto &Selector : Set.Selectors) {
12709 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12710 Selector.ScoreOrCondition = nullptr;
12711 if (readBool())
12712 Selector.ScoreOrCondition = readExprRef();
12713 Selector.Properties.resize(readUInt32());
12714 for (auto &Property : Selector.Properties)
12715 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12716 }
12717 }
Johannes Doerfert55eca282020-03-13 23:42:05 -050012718 return &TI;
Johannes Doerfert1228d422019-12-19 20:42:12 -060012719}