blob: aaa59fcf506219962222d206647d9c933d14814c [file] [log] [blame]
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001//===- ASTReader.cpp - AST File Reader ------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Serialization/ASTReader.h"
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000018#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTUnresolvedSet.h"
20#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000021#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000023#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclGroup.h"
25#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000027#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000030#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000032#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000037#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000039#include "clang/AST/UnresolvedSet.h"
40#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000041#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000042#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000043#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000046#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000049#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Basic/ObjCRuntime.h"
51#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000052#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Basic/SourceManager.h"
56#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000057#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include "clang/Basic/TargetInfo.h"
59#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000062#include "clang/Lex/HeaderSearch.h"
63#include "clang/Lex/HeaderSearchOptions.h"
64#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000066#include "clang/Lex/PreprocessingRecord.h"
67#include "clang/Lex/Preprocessor.h"
68#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000069#include "clang/Lex/Token.h"
70#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000071#include "clang/Sema/Scope.h"
72#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000074#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000076#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000077#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000078#include "clang/Serialization/InMemoryModuleCache.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/Module.h"
80#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000081#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000082#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include "llvm/ADT/APFloat.h"
85#include "llvm/ADT/APInt.h"
86#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000087#include "llvm/ADT/ArrayRef.h"
88#include "llvm/ADT/DenseMap.h"
89#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000090#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000091#include "llvm/ADT/IntrusiveRefCntPtr.h"
92#include "llvm/ADT/None.h"
93#include "llvm/ADT/Optional.h"
94#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000095#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000096#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000098#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +000099#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/StringMap.h"
101#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000103#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000104#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000105#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000106#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000107#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000108#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000110#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000111#include "llvm/Support/ErrorHandling.h"
112#include "llvm/Support/FileSystem.h"
113#include "llvm/Support/MemoryBuffer.h"
114#include "llvm/Support/Path.h"
115#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000116#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000117#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000118#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000119#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000121#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000123#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000125#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <limits>
127#include <map>
128#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000129#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000130#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000131#include <tuple>
132#include <utility>
133#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000134
135using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000136using namespace clang::serialization;
137using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000138using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000139
Ben Langmuircb69b572014-03-07 06:40:32 +0000140//===----------------------------------------------------------------------===//
141// ChainedASTReaderListener implementation
142//===----------------------------------------------------------------------===//
143
144bool
145ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
146 return First->ReadFullVersionInformation(FullVersion) ||
147 Second->ReadFullVersionInformation(FullVersion);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000150void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
151 First->ReadModuleName(ModuleName);
152 Second->ReadModuleName(ModuleName);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
156 First->ReadModuleMapFile(ModuleMapPath);
157 Second->ReadModuleMapFile(ModuleMapPath);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000160bool
161ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
162 bool Complain,
163 bool AllowCompatibleDifferences) {
164 return First->ReadLanguageOptions(LangOpts, Complain,
165 AllowCompatibleDifferences) ||
166 Second->ReadLanguageOptions(LangOpts, Complain,
167 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000169
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000170bool ChainedASTReaderListener::ReadTargetOptions(
171 const TargetOptions &TargetOpts, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadTargetOptions(TargetOpts, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadTargetOptions(TargetOpts, Complain,
176 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000177}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000178
Ben Langmuircb69b572014-03-07 06:40:32 +0000179bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000180 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000181 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
182 Second->ReadDiagnosticOptions(DiagOpts, Complain);
183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000184
Ben Langmuircb69b572014-03-07 06:40:32 +0000185bool
186ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
187 bool Complain) {
188 return First->ReadFileSystemOptions(FSOpts, Complain) ||
189 Second->ReadFileSystemOptions(FSOpts, Complain);
190}
191
192bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000193 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
194 bool Complain) {
195 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
196 Complain) ||
197 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
198 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000200
Ben Langmuircb69b572014-03-07 06:40:32 +0000201bool ChainedASTReaderListener::ReadPreprocessorOptions(
202 const PreprocessorOptions &PPOpts, bool Complain,
203 std::string &SuggestedPredefines) {
204 return First->ReadPreprocessorOptions(PPOpts, Complain,
205 SuggestedPredefines) ||
206 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
207}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000208
Ben Langmuircb69b572014-03-07 06:40:32 +0000209void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
210 unsigned Value) {
211 First->ReadCounter(M, Value);
212 Second->ReadCounter(M, Value);
213}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000214
Ben Langmuircb69b572014-03-07 06:40:32 +0000215bool ChainedASTReaderListener::needsInputFileVisitation() {
216 return First->needsInputFileVisitation() ||
217 Second->needsInputFileVisitation();
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
221 return First->needsSystemInputFileVisitation() ||
222 Second->needsSystemInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Richard Smith216a3bd2015-08-13 17:57:10 +0000225void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
226 ModuleKind Kind) {
227 First->visitModuleFile(Filename, Kind);
228 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000230
Ben Langmuircb69b572014-03-07 06:40:32 +0000231bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000232 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000233 bool isOverridden,
234 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000235 bool Continue = false;
236 if (First->needsInputFileVisitation() &&
237 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
239 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 if (Second->needsInputFileVisitation() &&
241 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000242 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
243 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000244 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000245}
246
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000247void ChainedASTReaderListener::readModuleFileExtension(
248 const ModuleFileExtensionMetadata &Metadata) {
249 First->readModuleFileExtension(Metadata);
250 Second->readModuleFileExtension(Metadata);
251}
252
Guy Benyei11169dd2012-12-18 14:30:41 +0000253//===----------------------------------------------------------------------===//
254// PCH validator implementation
255//===----------------------------------------------------------------------===//
256
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000257ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000259/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000260/// language options.
261///
262/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000263/// \param AllowCompatibleDifferences If true, differences between compatible
264/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000265///
266/// \returns true if the languagae options mis-match, false otherwise.
267static bool checkLanguageOptions(const LangOptions &LangOpts,
268 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000269 DiagnosticsEngine *Diags,
270 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#define LANGOPT(Name, Bits, Default, Description) \
272 if (ExistingLangOpts.Name != LangOpts.Name) { \
273 if (Diags) \
274 Diags->Report(diag::err_pch_langopt_mismatch) \
275 << Description << LangOpts.Name << ExistingLangOpts.Name; \
276 return true; \
277 }
278
279#define VALUE_LANGOPT(Name, Bits, Default, Description) \
280 if (ExistingLangOpts.Name != LangOpts.Name) { \
281 if (Diags) \
282 Diags->Report(diag::err_pch_langopt_value_mismatch) \
283 << Description; \
284 return true; \
285 }
286
287#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
289 if (Diags) \
290 Diags->Report(diag::err_pch_langopt_value_mismatch) \
291 << Description; \
292 return true; \
293 }
294
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000295#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
296 if (!AllowCompatibleDifferences) \
297 LANGOPT(Name, Bits, Default, Description)
298
299#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
300 if (!AllowCompatibleDifferences) \
301 ENUM_LANGOPT(Name, Bits, Default, Description)
302
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000303#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
304 if (!AllowCompatibleDifferences) \
305 VALUE_LANGOPT(Name, Bits, Default, Description)
306
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define BENIGN_LANGOPT(Name, Bits, Default, Description)
308#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000309#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310#include "clang/Basic/LangOptions.def"
311
Ben Langmuircd98cb72015-06-23 18:20:18 +0000312 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
313 if (Diags)
314 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
315 return true;
316 }
317
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
319 if (Diags)
320 Diags->Report(diag::err_pch_langopt_value_mismatch)
321 << "target Objective-C runtime";
322 return true;
323 }
324
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000325 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
326 LangOpts.CommentOpts.BlockCommandNames) {
327 if (Diags)
328 Diags->Report(diag::err_pch_langopt_value_mismatch)
329 << "block command names";
330 return true;
331 }
332
Vedant Kumar85a83c22017-06-01 20:01:01 +0000333 // Sanitizer feature mismatches are treated as compatible differences. If
334 // compatible differences aren't allowed, we still only want to check for
335 // mismatches of non-modular sanitizers (the only ones which can affect AST
336 // generation).
337 if (!AllowCompatibleDifferences) {
338 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
339 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
340 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
341 ExistingSanitizers.clear(ModularSanitizers);
342 ImportedSanitizers.clear(ModularSanitizers);
343 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
344 const std::string Flag = "-fsanitize=";
345 if (Diags) {
346#define SANITIZER(NAME, ID) \
347 { \
348 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
349 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
350 if (InExistingModule != InImportedModule) \
351 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
352 << InExistingModule << (Flag + NAME); \
353 }
354#include "clang/Basic/Sanitizers.def"
355 }
356 return true;
357 }
358 }
359
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 return false;
361}
362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000363/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000364/// target options.
365///
366/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
367///
368/// \returns true if the target options mis-match, false otherwise.
369static bool checkTargetOptions(const TargetOptions &TargetOpts,
370 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000371 DiagnosticsEngine *Diags,
372 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000373#define CHECK_TARGET_OPT(Field, Name) \
374 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
375 if (Diags) \
376 Diags->Report(diag::err_pch_targetopt_mismatch) \
377 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
378 return true; \
379 }
380
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000381 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000384
385 // We can tolerate different CPUs in many cases, notably when one CPU
386 // supports a strict superset of another. When allowing compatible
387 // differences skip this check.
388 if (!AllowCompatibleDifferences)
389 CHECK_TARGET_OPT(CPU, "target CPU");
390
Guy Benyei11169dd2012-12-18 14:30:41 +0000391#undef CHECK_TARGET_OPT
392
393 // Compare feature sets.
394 SmallVector<StringRef, 4> ExistingFeatures(
395 ExistingTargetOpts.FeaturesAsWritten.begin(),
396 ExistingTargetOpts.FeaturesAsWritten.end());
397 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
398 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000399 llvm::sort(ExistingFeatures);
400 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000401
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000402 // We compute the set difference in both directions explicitly so that we can
403 // diagnose the differences differently.
404 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
405 std::set_difference(
406 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
407 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
408 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
409 ExistingFeatures.begin(), ExistingFeatures.end(),
410 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000412 // If we are allowing compatible differences and the read feature set is
413 // a strict subset of the existing feature set, there is nothing to diagnose.
414 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
415 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 if (Diags) {
418 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000420 << /* is-existing-feature */ false << Feature;
421 for (StringRef Feature : UnmatchedExistingFeatures)
422 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000426 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000427}
428
429bool
430PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000431 bool Complain,
432 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 const LangOptions &ExistingLangOpts = PP.getLangOpts();
434 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000435 Complain ? &Reader.Diags : nullptr,
436 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000437}
438
439bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000440 bool Complain,
441 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
443 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000444 Complain ? &Reader.Diags : nullptr,
445 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000446}
447
448namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000449
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000450using MacroDefinitionsMap =
451 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
452using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000453
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000454} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000455
Ben Langmuirb92de022014-04-29 16:25:26 +0000456static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000460
461 // Check current mappings for new -Werror mappings, and the stored mappings
462 // for cases that were explicitly mapped to *not* be errors that are now
463 // errors because of options like -Werror.
464 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
465
Vedant Kumar48b4f762018-04-14 01:40:48 +0000466 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000467 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
468 diag::kind DiagID = DiagIDMappingPair.first;
469 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
470 if (CurLevel < DiagnosticsEngine::Error)
471 continue; // not significant
472 Level StoredLevel =
473 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
474 if (StoredLevel < DiagnosticsEngine::Error) {
475 if (Complain)
476 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
477 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
478 return true;
479 }
480 }
481 }
482
483 return false;
484}
485
Alp Tokerac4e8e52014-06-22 21:58:33 +0000486static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
487 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
488 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
489 return true;
490 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000491}
492
493static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
494 DiagnosticsEngine &Diags,
495 bool IsSystem, bool Complain) {
496 // Top-level options
497 if (IsSystem) {
498 if (Diags.getSuppressSystemWarnings())
499 return false;
500 // If -Wsystem-headers was not enabled before, be conservative
501 if (StoredDiags.getSuppressSystemWarnings()) {
502 if (Complain)
503 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
504 return true;
505 }
506 }
507
508 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
509 if (Complain)
510 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
511 return true;
512 }
513
514 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
515 !StoredDiags.getEnableAllWarnings()) {
516 if (Complain)
517 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
518 return true;
519 }
520
521 if (isExtHandlingFromDiagsError(Diags) &&
522 !isExtHandlingFromDiagsError(StoredDiags)) {
523 if (Complain)
524 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
525 return true;
526 }
527
528 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
529}
530
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000531/// Return the top import module if it is implicit, nullptr otherwise.
532static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
533 Preprocessor &PP) {
534 // If the original import came from a file explicitly generated by the user,
535 // don't check the diagnostic mappings.
536 // FIXME: currently this is approximated by checking whether this is not a
537 // module import of an implicitly-loaded module file.
538 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
539 // the transitive closure of its imports, since unrelated modules cannot be
540 // imported until after this module finishes validation.
541 ModuleFile *TopImport = &*ModuleMgr.rbegin();
542 while (!TopImport->ImportedBy.empty())
543 TopImport = TopImport->ImportedBy[0];
544 if (TopImport->Kind != MK_ImplicitModule)
545 return nullptr;
546
547 StringRef ModuleName = TopImport->ModuleName;
548 assert(!ModuleName.empty() && "diagnostic options read before module name");
549
550 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
551 assert(M && "missing module");
552 return M;
553}
554
Ben Langmuirb92de022014-04-29 16:25:26 +0000555bool PCHValidator::ReadDiagnosticOptions(
556 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
557 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
558 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
559 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000560 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000561 // This should never fail, because we would have processed these options
562 // before writing them to an ASTFile.
563 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
564
565 ModuleManager &ModuleMgr = Reader.getModuleManager();
566 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
567
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000568 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
569 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000570 return false;
571
Ben Langmuirb92de022014-04-29 16:25:26 +0000572 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
573 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000574 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
575 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000576}
577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000578/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000579/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000580static void
581collectMacroDefinitions(const PreprocessorOptions &PPOpts,
582 MacroDefinitionsMap &Macros,
583 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000584 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
585 StringRef Macro = PPOpts.Macros[I].first;
586 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000587
588 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
589 StringRef MacroName = MacroPair.first;
590 StringRef MacroBody = MacroPair.second;
591
592 // For an #undef'd macro, we only care about the name.
593 if (IsUndef) {
594 if (MacroNames && !Macros.count(MacroName))
595 MacroNames->push_back(MacroName);
596
597 Macros[MacroName] = std::make_pair("", true);
598 continue;
599 }
600
601 // For a #define'd macro, figure out the actual definition.
602 if (MacroName.size() == Macro.size())
603 MacroBody = "1";
604 else {
605 // Note: GCC drops anything following an end-of-line character.
606 StringRef::size_type End = MacroBody.find_first_of("\n\r");
607 MacroBody = MacroBody.substr(0, End);
608 }
609
610 if (MacroNames && !Macros.count(MacroName))
611 MacroNames->push_back(MacroName);
612 Macros[MacroName] = std::make_pair(MacroBody, false);
613 }
614}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000616/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000617/// against the preprocessor options in an existing preprocessor.
618///
619/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000620/// \param Validate If true, validate preprocessor options. If false, allow
621/// macros defined by \p ExistingPPOpts to override those defined by
622/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000623static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
624 const PreprocessorOptions &ExistingPPOpts,
625 DiagnosticsEngine *Diags,
626 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000627 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000628 const LangOptions &LangOpts,
629 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 // Check macro definitions.
631 MacroDefinitionsMap ASTFileMacros;
632 collectMacroDefinitions(PPOpts, ASTFileMacros);
633 MacroDefinitionsMap ExistingMacros;
634 SmallVector<StringRef, 4> ExistingMacroNames;
635 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
636
Vedant Kumar48b4f762018-04-14 01:40:48 +0000637 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000639 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
641
642 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000643 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
644 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000645 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 // FIXME: Check whether this identifier was referenced anywhere in the
647 // AST file. If so, we should reject the AST file. Unfortunately, this
648 // information isn't in the control block. What shall we do about it?
649
650 if (Existing.second) {
651 SuggestedPredefines += "#undef ";
652 SuggestedPredefines += MacroName.str();
653 SuggestedPredefines += '\n';
654 } else {
655 SuggestedPredefines += "#define ";
656 SuggestedPredefines += MacroName.str();
657 SuggestedPredefines += ' ';
658 SuggestedPredefines += Existing.first.str();
659 SuggestedPredefines += '\n';
660 }
661 continue;
662 }
663
664 // If the macro was defined in one but undef'd in the other, we have a
665 // conflict.
666 if (Existing.second != Known->second.second) {
667 if (Diags) {
668 Diags->Report(diag::err_pch_macro_def_undef)
669 << MacroName << Known->second.second;
670 }
671 return true;
672 }
673
674 // If the macro was #undef'd in both, or if the macro bodies are identical,
675 // it's fine.
676 if (Existing.second || Existing.first == Known->second.first)
677 continue;
678
679 // The macro bodies differ; complain.
680 if (Diags) {
681 Diags->Report(diag::err_pch_macro_def_conflict)
682 << MacroName << Known->second.first << Existing.first;
683 }
684 return true;
685 }
686
687 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000688 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000689 if (Diags) {
690 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
691 }
692 return true;
693 }
694
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000695 // Detailed record is important since it is used for the module cache hash.
696 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000697 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000698 if (Diags) {
699 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
700 }
701 return true;
702 }
703
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000705 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
706 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000707
708 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
709 !ExistingPPOpts.PCHThroughHeader.empty()) {
710 // In case the through header is an include, we must add all the includes
711 // to the predefines so the start point can be determined.
712 SuggestedPredefines += "#include \"";
713 SuggestedPredefines += File;
714 SuggestedPredefines += "\"\n";
715 continue;
716 }
717
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 if (File == ExistingPPOpts.ImplicitPCHInclude)
719 continue;
720
721 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
722 != PPOpts.Includes.end())
723 continue;
724
725 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000726 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 SuggestedPredefines += "\"\n";
728 }
729
Vedant Kumar48b4f762018-04-14 01:40:48 +0000730 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
731 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
733 File)
734 != PPOpts.MacroIncludes.end())
735 continue;
736
737 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000738 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 SuggestedPredefines += "\"\n##\n";
740 }
741
742 return false;
743}
744
745bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
746 bool Complain,
747 std::string &SuggestedPredefines) {
748 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
749
750 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000751 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000753 SuggestedPredefines,
754 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000755}
756
Yaxun Liu43712e02016-09-07 18:40:20 +0000757bool SimpleASTReaderListener::ReadPreprocessorOptions(
758 const PreprocessorOptions &PPOpts,
759 bool Complain,
760 std::string &SuggestedPredefines) {
761 return checkPreprocessorOptions(PPOpts,
762 PP.getPreprocessorOpts(),
763 nullptr,
764 PP.getFileManager(),
765 SuggestedPredefines,
766 PP.getLangOpts(),
767 false);
768}
769
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000770/// Check the header search options deserialized from the control block
771/// against the header search options in an existing preprocessor.
772///
773/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
774static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
775 StringRef SpecificModuleCachePath,
776 StringRef ExistingModuleCachePath,
777 DiagnosticsEngine *Diags,
778 const LangOptions &LangOpts) {
779 if (LangOpts.Modules) {
780 if (SpecificModuleCachePath != ExistingModuleCachePath) {
781 if (Diags)
782 Diags->Report(diag::err_pch_modulecache_mismatch)
783 << SpecificModuleCachePath << ExistingModuleCachePath;
784 return true;
785 }
786 }
787
788 return false;
789}
790
791bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
792 StringRef SpecificModuleCachePath,
793 bool Complain) {
794 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
795 PP.getHeaderSearchInfo().getModuleCachePath(),
796 Complain ? &Reader.Diags : nullptr,
797 PP.getLangOpts());
798}
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
801 PP.setCounterValue(Value);
802}
803
804//===----------------------------------------------------------------------===//
805// AST reader implementation
806//===----------------------------------------------------------------------===//
807
Nico Weber824285e2014-05-08 04:26:47 +0000808void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
809 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000811 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000812}
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
815 return serialization::ComputeHash(Sel);
816}
817
Guy Benyei11169dd2012-12-18 14:30:41 +0000818std::pair<unsigned, unsigned>
819ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000821
Justin Bogner57ba0b22014-03-28 22:03:24 +0000822 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
823 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 return std::make_pair(KeyLen, DataLen);
825}
826
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000827ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000828ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000829 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000830
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
833 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
834 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 if (N == 0)
836 return SelTable.getNullarySelector(FirstII);
837 else if (N == 1)
838 return SelTable.getUnarySelector(FirstII);
839
840 SmallVector<IdentifierInfo *, 16> Args;
841 Args.push_back(FirstII);
842 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 Args.push_back(Reader.getLocalIdentifier(
844 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000845
846 return SelTable.getSelector(N, Args.data());
847}
848
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000849ASTSelectorLookupTrait::data_type
850ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000852 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000853
854 data_type Result;
855
Justin Bogner57ba0b22014-03-28 22:03:24 +0000856 Result.ID = Reader.getGlobalSelectorID(
857 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000858 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
859 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
860 Result.InstanceBits = FullInstanceBits & 0x3;
861 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
862 Result.FactoryBits = FullFactoryBits & 0x3;
863 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
864 unsigned NumInstanceMethods = FullInstanceBits >> 3;
865 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000866
867 // Load instance methods
868 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000869 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000870 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 Result.Instance.push_back(Method);
872 }
873
874 // Load factory methods
875 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000876 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000877 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 Result.Factory.push_back(Method);
879 }
880
881 return Result;
882}
883
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000884unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000885 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000886}
887
888std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000890 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000891
Justin Bogner57ba0b22014-03-28 22:03:24 +0000892 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
893 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000894 return std::make_pair(KeyLen, DataLen);
895}
896
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000897ASTIdentifierLookupTraitBase::internal_key_type
898ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000900 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000901}
902
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000903/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000904static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
905 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000906 return II.hadMacroDefinition() ||
907 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000908 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000909 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000910 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000911 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000912}
913
Richard Smith76c2f2c2015-07-17 20:09:43 +0000914static bool readBit(unsigned &Bits) {
915 bool Value = Bits & 0x1;
916 Bits >>= 1;
917 return Value;
918}
919
Richard Smith79bf9202015-08-24 03:33:22 +0000920IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
921 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000922
Richard Smith79bf9202015-08-24 03:33:22 +0000923 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
924 return Reader.getGlobalIdentifierID(F, RawID >> 1);
925}
926
Richard Smitheb4b58f62016-02-05 01:40:54 +0000927static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
928 if (!II.isFromAST()) {
929 II.setIsFromAST();
930 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
931 if (isInterestingIdentifier(Reader, II, IsModule))
932 II.setChangedSinceDeserialization();
933 }
934}
935
Guy Benyei11169dd2012-12-18 14:30:41 +0000936IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
937 const unsigned char* d,
938 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000939 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000940
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 bool IsInteresting = RawID & 0x01;
943
944 // Wipe out the "is interesting" bit.
945 RawID = RawID >> 1;
946
Richard Smith76c2f2c2015-07-17 20:09:43 +0000947 // Build the IdentifierInfo and link the identifier ID with it.
948 IdentifierInfo *II = KnownII;
949 if (!II) {
950 II = &Reader.getIdentifierTable().getOwn(k);
951 KnownII = II;
952 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000953 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000954 Reader.markIdentifierUpToDate(II);
955
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
957 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000958 // For uninteresting identifiers, there's nothing else to do. Just notify
959 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 return II;
962 }
963
Justin Bogner57ba0b22014-03-28 22:03:24 +0000964 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
965 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000966 bool CPlusPlusOperatorKeyword = readBit(Bits);
967 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000968 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000969 bool Poisoned = readBit(Bits);
970 bool ExtensionToken = readBit(Bits);
971 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972
973 assert(Bits == 0 && "Extra bits in the identifier?");
974 DataLen -= 8;
975
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // Set or check the various bits in the IdentifierInfo structure.
977 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000978 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000979 II->revertTokenIDToIdentifier();
980 if (!F.isModule())
981 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
982 else if (HasRevertedBuiltin && II->getBuiltinID()) {
983 II->revertBuiltin();
984 assert((II->hasRevertedBuiltin() ||
985 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
986 "Incorrect ObjC keyword or builtin ID");
987 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 assert(II->isExtensionToken() == ExtensionToken &&
989 "Incorrect extension token flag");
990 (void)ExtensionToken;
991 if (Poisoned)
992 II->setIsPoisoned(true);
993 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
994 "Incorrect C++ operator keyword flag");
995 (void)CPlusPlusOperatorKeyword;
996
997 // If this identifier is a macro, deserialize the macro
998 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000999 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001000 uint32_t MacroDirectivesOffset =
1001 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001002 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001003
Richard Smithd7329392015-04-21 21:46:32 +00001004 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 }
1006
1007 Reader.SetIdentifierInfo(ID, II);
1008
1009 // Read all of the declarations visible at global scope with this
1010 // name.
1011 if (DataLen > 0) {
1012 SmallVector<uint32_t, 4> DeclIDs;
1013 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 DeclIDs.push_back(Reader.getGlobalDeclID(
1015 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1017 }
1018
1019 return II;
1020}
1021
Richard Smitha06c7e62015-08-26 23:55:49 +00001022DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1023 : Kind(Name.getNameKind()) {
1024 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001026 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001034 Data = Name.getCXXOverloadedOperator();
1035 break;
1036 case DeclarationName::CXXLiteralOperatorName:
1037 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1038 break;
Richard Smith35845152017-02-07 01:37:30 +00001039 case DeclarationName::CXXDeductionGuideName:
1040 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1041 ->getDeclName().getAsIdentifierInfo();
1042 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001043 case DeclarationName::CXXConstructorName:
1044 case DeclarationName::CXXDestructorName:
1045 case DeclarationName::CXXConversionFunctionName:
1046 case DeclarationName::CXXUsingDirective:
1047 Data = 0;
1048 break;
1049 }
1050}
1051
1052unsigned DeclarationNameKey::getHash() const {
1053 llvm::FoldingSetNodeID ID;
1054 ID.AddInteger(Kind);
1055
1056 switch (Kind) {
1057 case DeclarationName::Identifier:
1058 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001059 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001060 ID.AddString(((IdentifierInfo*)Data)->getName());
1061 break;
1062 case DeclarationName::ObjCZeroArgSelector:
1063 case DeclarationName::ObjCOneArgSelector:
1064 case DeclarationName::ObjCMultiArgSelector:
1065 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1066 break;
1067 case DeclarationName::CXXOperatorName:
1068 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 break;
1070 case DeclarationName::CXXConstructorName:
1071 case DeclarationName::CXXDestructorName:
1072 case DeclarationName::CXXConversionFunctionName:
1073 case DeclarationName::CXXUsingDirective:
1074 break;
1075 }
1076
1077 return ID.ComputeHash();
1078}
1079
Richard Smithd88a7f12015-09-01 20:35:42 +00001080ModuleFile *
1081ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1082 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001083
Richard Smithd88a7f12015-09-01 20:35:42 +00001084 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1085 return Reader.getLocalModuleFile(F, ModuleFileID);
1086}
1087
Guy Benyei11169dd2012-12-18 14:30:41 +00001088std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001089ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001090 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001091
Justin Bogner57ba0b22014-03-28 22:03:24 +00001092 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1093 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 return std::make_pair(KeyLen, DataLen);
1095}
1096
Richard Smitha06c7e62015-08-26 23:55:49 +00001097ASTDeclContextNameLookupTrait::internal_key_type
1098ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001099 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
Vedant Kumar48b4f762018-04-14 01:40:48 +00001101 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001102 uint64_t Data;
1103 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001105 case DeclarationName::CXXLiteralOperatorName:
1106 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001108 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 break;
1110 case DeclarationName::ObjCZeroArgSelector:
1111 case DeclarationName::ObjCOneArgSelector:
1112 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001113 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001114 (uint64_t)Reader.getLocalSelector(
1115 F, endian::readNext<uint32_t, little, unaligned>(
1116 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 break;
1118 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001119 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 case DeclarationName::CXXConstructorName:
1122 case DeclarationName::CXXDestructorName:
1123 case DeclarationName::CXXConversionFunctionName:
1124 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001125 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001126 break;
1127 }
1128
Richard Smitha06c7e62015-08-26 23:55:49 +00001129 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001130}
1131
Richard Smithd88a7f12015-09-01 20:35:42 +00001132void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1133 const unsigned char *d,
1134 unsigned DataLen,
1135 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001136 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001137
Richard Smithd88a7f12015-09-01 20:35:42 +00001138 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1139 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1140 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001142}
1143
Richard Smith0f4e2c42015-08-06 04:23:48 +00001144bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1145 BitstreamCursor &Cursor,
1146 uint64_t Offset,
1147 DeclContext *DC) {
1148 assert(Offset != 0);
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001151 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1152 Error(std::move(Err));
1153 return true;
1154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001155
Richard Smith0f4e2c42015-08-06 04:23:48 +00001156 RecordData Record;
1157 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001158 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1159 if (!MaybeCode) {
1160 Error(MaybeCode.takeError());
1161 return true;
1162 }
1163 unsigned Code = MaybeCode.get();
1164
1165 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1166 if (!MaybeRecCode) {
1167 Error(MaybeRecCode.takeError());
1168 return true;
1169 }
1170 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001171 if (RecCode != DECL_CONTEXT_LEXICAL) {
1172 Error("Expected lexical block");
1173 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 }
1175
Richard Smith82f8fcd2015-08-06 22:07:25 +00001176 assert(!isa<TranslationUnitDecl>(DC) &&
1177 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001178 // If we are handling a C++ class template instantiation, we can see multiple
1179 // lexical updates for the same record. It's important that we select only one
1180 // of them, so that field numbering works properly. Just pick the first one we
1181 // see.
1182 auto &Lex = LexicalDecls[DC];
1183 if (!Lex.first) {
1184 Lex = std::make_pair(
1185 &M, llvm::makeArrayRef(
1186 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1187 Blob.data()),
1188 Blob.size() / 4));
1189 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001190 DC->setHasExternalLexicalStorage(true);
1191 return false;
1192}
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
Richard Smith0f4e2c42015-08-06 04:23:48 +00001194bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1195 BitstreamCursor &Cursor,
1196 uint64_t Offset,
1197 DeclID ID) {
1198 assert(Offset != 0);
1199
1200 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001201 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1202 Error(std::move(Err));
1203 return true;
1204 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001205
1206 RecordData Record;
1207 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001208 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1209 if (!MaybeCode) {
1210 Error(MaybeCode.takeError());
1211 return true;
1212 }
1213 unsigned Code = MaybeCode.get();
1214
1215 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1216 if (!MaybeRecCode) {
1217 Error(MaybeRecCode.takeError());
1218 return true;
1219 }
1220 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001221 if (RecCode != DECL_CONTEXT_VISIBLE) {
1222 Error("Expected visible lookup table block");
1223 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 }
1225
Richard Smith0f4e2c42015-08-06 04:23:48 +00001226 // We can't safely determine the primary context yet, so delay attaching the
1227 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001228 auto *Data = (const unsigned char*)Blob.data();
1229 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 return false;
1231}
1232
Richard Smith37a93df2017-02-18 00:32:02 +00001233void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001235 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001236 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001237 Diag(diag::note_module_cache_path)
1238 << PP.getHeaderSearchInfo().getModuleCachePath();
1239 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001240}
1241
1242void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001243 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 if (Diags.isDiagnosticInFlight())
1245 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1246 else
1247 Diag(DiagID) << Arg1 << Arg2;
1248}
1249
JF Bastien0e828952019-06-26 19:50:12 +00001250void ASTReader::Error(llvm::Error &&Err) const {
1251 Error(toString(std::move(Err)));
1252}
1253
Guy Benyei11169dd2012-12-18 14:30:41 +00001254//===----------------------------------------------------------------------===//
1255// Source Manager Deserialization
1256//===----------------------------------------------------------------------===//
1257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001258/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001259/// \returns true if there was an error.
1260bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001261 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001262 unsigned Idx = 0;
1263 LineTableInfo &LineTable = SourceMgr.getLineTable();
1264
1265 // Parse the file names
1266 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001267 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001268 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001270 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001271 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1272 }
Richard Smith63078492015-09-01 07:41:55 +00001273 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001274
1275 // Parse the line entries
1276 std::vector<LineEntry> Entries;
1277 while (Idx < Record.size()) {
1278 int FID = Record[Idx++];
1279 assert(FID >= 0 && "Serialized line entries for non-local file.");
1280 // Remap FileID from 1-based old view.
1281 FID += F.SLocEntryBaseID - 1;
1282
1283 // Extract the line entries
1284 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001285 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 Entries.clear();
1287 Entries.reserve(NumEntries);
1288 for (unsigned I = 0; I != NumEntries; ++I) {
1289 unsigned FileOffset = Record[Idx++];
1290 unsigned LineNo = Record[Idx++];
1291 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001292 SrcMgr::CharacteristicKind FileKind
1293 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 unsigned IncludeOffset = Record[Idx++];
1295 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1296 FileKind, IncludeOffset));
1297 }
1298 LineTable.AddEntry(FileID::get(FID), Entries);
1299 }
1300
1301 return false;
1302}
1303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001304/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001305bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1306 using namespace SrcMgr;
1307
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309
1310 // Set the source-location entry cursor to the current position in
1311 // the stream. This cursor will be used to read the contents of the
1312 // source manager block initially, and then lazily read
1313 // source-location entries as needed.
1314 SLocEntryCursor = F.Stream;
1315
1316 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001317 if (llvm::Error Err = F.Stream.SkipBlock()) {
1318 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return true;
1320 }
1321
1322 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001323 if (llvm::Error Err =
1324 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1325 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 return true;
1327 }
1328
1329 RecordData Record;
1330 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001331 Expected<llvm::BitstreamEntry> MaybeE =
1332 SLocEntryCursor.advanceSkippingSubblocks();
1333 if (!MaybeE) {
1334 Error(MaybeE.takeError());
1335 return true;
1336 }
1337 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001338
Chris Lattnere7b154b2013-01-19 21:39:22 +00001339 switch (E.Kind) {
1340 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1341 case llvm::BitstreamEntry::Error:
1342 Error("malformed block record in AST file");
1343 return true;
1344 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001346 case llvm::BitstreamEntry::Record:
1347 // The interesting case.
1348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001349 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001350
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001353 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001354 Expected<unsigned> MaybeRecord =
1355 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1356 if (!MaybeRecord) {
1357 Error(MaybeRecord.takeError());
1358 return true;
1359 }
1360 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 default: // Default behavior: ignore.
1362 break;
1363
1364 case SM_SLOC_FILE_ENTRY:
1365 case SM_SLOC_BUFFER_ENTRY:
1366 case SM_SLOC_EXPANSION_ENTRY:
1367 // Once we hit one of the source location entries, we're done.
1368 return false;
1369 }
1370 }
1371}
1372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001373/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001374/// and the PCH file was moved from its original location, try to resolve the
1375/// file by assuming that header+PCH were moved together and the header is in
1376/// the same place relative to the PCH.
1377static std::string
1378resolveFileRelativeToOriginalDir(const std::string &Filename,
1379 const std::string &OriginalDir,
1380 const std::string &CurrDir) {
1381 assert(OriginalDir != CurrDir &&
1382 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001383
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001385
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 SmallString<128> filePath(Filename);
1387 fs::make_absolute(filePath);
1388 assert(path::is_absolute(OriginalDir));
1389 SmallString<128> currPCHPath(CurrDir);
1390
1391 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1392 fileDirE = path::end(path::parent_path(filePath));
1393 path::const_iterator origDirI = path::begin(OriginalDir),
1394 origDirE = path::end(OriginalDir);
1395 // Skip the common path components from filePath and OriginalDir.
1396 while (fileDirI != fileDirE && origDirI != origDirE &&
1397 *fileDirI == *origDirI) {
1398 ++fileDirI;
1399 ++origDirI;
1400 }
1401 for (; origDirI != origDirE; ++origDirI)
1402 path::append(currPCHPath, "..");
1403 path::append(currPCHPath, fileDirI, fileDirE);
1404 path::append(currPCHPath, path::filename(Filename));
1405 return currPCHPath.str();
1406}
1407
1408bool ASTReader::ReadSLocEntry(int ID) {
1409 if (ID == 0)
1410 return false;
1411
1412 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1413 Error("source location entry ID out-of-range for AST file");
1414 return true;
1415 }
1416
Richard Smithaada85c2016-02-06 02:06:43 +00001417 // Local helper to read the (possibly-compressed) buffer data following the
1418 // entry record.
1419 auto ReadBuffer = [this](
1420 BitstreamCursor &SLocEntryCursor,
1421 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1422 RecordData Record;
1423 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001424 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1425 if (!MaybeCode) {
1426 Error(MaybeCode.takeError());
1427 return nullptr;
1428 }
1429 unsigned Code = MaybeCode.get();
1430
1431 Expected<unsigned> MaybeRecCode =
1432 SLocEntryCursor.readRecord(Code, Record, &Blob);
1433 if (!MaybeRecCode) {
1434 Error(MaybeRecCode.takeError());
1435 return nullptr;
1436 }
1437 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001438
1439 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001440 if (!llvm::zlib::isAvailable()) {
1441 Error("zlib is not available");
1442 return nullptr;
1443 }
Richard Smithaada85c2016-02-06 02:06:43 +00001444 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001445 if (llvm::Error E =
1446 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1447 Error("could not decompress embedded file contents: " +
1448 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001449 return nullptr;
1450 }
1451 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1452 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1453 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1454 } else {
1455 Error("AST record has invalid code");
1456 return nullptr;
1457 }
1458 };
1459
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001461 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1462 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1463 Error(std::move(Err));
1464 return true;
1465 }
1466
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001467 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 unsigned BaseOffset = F->SLocEntryBaseOffset;
1469
1470 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001471 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1472 if (!MaybeEntry) {
1473 Error(MaybeEntry.takeError());
1474 return true;
1475 }
1476 llvm::BitstreamEntry Entry = MaybeEntry.get();
1477
Chris Lattnere7b154b2013-01-19 21:39:22 +00001478 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 Error("incorrectly-formatted source location entry in AST file");
1480 return true;
1481 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001482
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001484 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001485 Expected<unsigned> MaybeSLOC =
1486 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1487 if (!MaybeSLOC) {
1488 Error(MaybeSLOC.takeError());
1489 return true;
1490 }
1491 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 default:
1493 Error("incorrectly-formatted source location entry in AST file");
1494 return true;
1495
1496 case SM_SLOC_FILE_ENTRY: {
1497 // We will detect whether a file changed and return 'Failure' for it, but
1498 // we will also try to fail gracefully by setting up the SLocEntry.
1499 unsigned InputID = Record[4];
1500 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001501 const FileEntry *File = IF.getFile();
1502 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001504 // Note that we only check if a File was returned. If it was out-of-date
1505 // we have complained but we will continue creating a FileID to recover
1506 // gracefully.
1507 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 return true;
1509
1510 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1511 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1512 // This is the module's main file.
1513 IncludeLoc = getImportLocation(F);
1514 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001515 SrcMgr::CharacteristicKind
1516 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001517 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1519 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001520 SrcMgr::FileInfo &FileInfo =
1521 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 FileInfo.NumCreatedFIDs = Record[5];
1523 if (Record[3])
1524 FileInfo.setHasLineDirectives();
1525
1526 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1527 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001528 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1530 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1531 NumFileDecls));
1532 }
Richard Smithaada85c2016-02-06 02:06:43 +00001533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001535 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001537 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1538 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001539 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1540 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001542 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 }
1544
1545 break;
1546 }
1547
1548 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001549 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001551 SrcMgr::CharacteristicKind
1552 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001554 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 IncludeLoc = getImportLocation(F);
1556 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001557
Richard Smithaada85c2016-02-06 02:06:43 +00001558 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1559 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001561 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001562 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 break;
1564 }
1565
1566 case SM_SLOC_EXPANSION_ENTRY: {
1567 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1568 SourceMgr.createExpansionLoc(SpellingLoc,
1569 ReadSourceLocation(*F, Record[2]),
1570 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001571 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 Record[4],
1573 ID,
1574 BaseOffset + Record[0]);
1575 break;
1576 }
1577 }
1578
1579 return false;
1580}
1581
1582std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1583 if (ID == 0)
1584 return std::make_pair(SourceLocation(), "");
1585
1586 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1587 Error("source location entry ID out-of-range for AST file");
1588 return std::make_pair(SourceLocation(), "");
1589 }
1590
1591 // Find which module file this entry lands in.
1592 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001593 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 return std::make_pair(SourceLocation(), "");
1595
1596 // FIXME: Can we map this down to a particular submodule? That would be
1597 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001598 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001599}
1600
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001601/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001602SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1603 if (F->ImportLoc.isValid())
1604 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001605
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 // Otherwise we have a PCH. It's considered to be "imported" at the first
1607 // location of its includer.
1608 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001609 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001610 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001611 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 return F->ImportedBy[0]->FirstLoc;
1614}
1615
JF Bastien0e828952019-06-26 19:50:12 +00001616/// Enter a subblock of the specified BlockID with the specified cursor. Read
1617/// the abbreviations that are at the top of the block and then leave the cursor
1618/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001619bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001620 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1621 // FIXME this drops errors on the floor.
1622 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001623 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001625
1626 while (true) {
1627 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001628 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1629 if (!MaybeCode) {
1630 // FIXME this drops errors on the floor.
1631 consumeError(MaybeCode.takeError());
1632 return true;
1633 }
1634 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001635
1636 // We expect all abbrevs to be at the start of the block.
1637 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001638 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1639 // FIXME this drops errors on the floor.
1640 consumeError(std::move(Err));
1641 return true;
1642 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 return false;
1644 }
JF Bastien0e828952019-06-26 19:50:12 +00001645 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1646 // FIXME this drops errors on the floor.
1647 consumeError(std::move(Err));
1648 return true;
1649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 }
1651}
1652
Richard Smithe40f2ba2013-08-07 21:41:30 +00001653Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001654 unsigned &Idx) {
1655 Token Tok;
1656 Tok.startToken();
1657 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1658 Tok.setLength(Record[Idx++]);
1659 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1660 Tok.setIdentifierInfo(II);
1661 Tok.setKind((tok::TokenKind)Record[Idx++]);
1662 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1663 return Tok;
1664}
1665
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001666MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001667 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668
1669 // Keep track of where we are in the stream, then jump back there
1670 // after reading this macro.
1671 SavedStreamPosition SavedPosition(Stream);
1672
JF Bastien0e828952019-06-26 19:50:12 +00001673 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1674 // FIXME this drops errors on the floor.
1675 consumeError(std::move(Err));
1676 return nullptr;
1677 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001679 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001680 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001683 // Advance to the next record, but if we get to the end of the block, don't
1684 // pop it (removing all the abbreviations from the cursor) since we want to
1685 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001686 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001687 Expected<llvm::BitstreamEntry> MaybeEntry =
1688 Stream.advanceSkippingSubblocks(Flags);
1689 if (!MaybeEntry) {
1690 Error(MaybeEntry.takeError());
1691 return Macro;
1692 }
1693 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001694
Chris Lattnerefa77172013-01-20 00:00:22 +00001695 switch (Entry.Kind) {
1696 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1697 case llvm::BitstreamEntry::Error:
1698 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001699 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001700 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001701 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001702 case llvm::BitstreamEntry::Record:
1703 // The interesting case.
1704 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 }
1706
1707 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001709 PreprocessorRecordTypes RecType;
1710 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1711 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1712 else {
1713 Error(MaybeRecType.takeError());
1714 return Macro;
1715 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001717 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001718 case PP_MACRO_DIRECTIVE_HISTORY:
1719 return Macro;
1720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 case PP_MACRO_OBJECT_LIKE:
1722 case PP_MACRO_FUNCTION_LIKE: {
1723 // If we already have a macro, that means that we've hit the end
1724 // of the definition of the macro we were looking for. We're
1725 // done.
1726 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001728
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001731 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001732 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001733 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001734 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1737 // Decode function-like macro info.
1738 bool isC99VarArgs = Record[NextIndex++];
1739 bool isGNUVarArgs = Record[NextIndex++];
1740 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001741 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 unsigned NumArgs = Record[NextIndex++];
1743 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001744 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001745
1746 // Install function-like macro info.
1747 MI->setIsFunctionLike();
1748 if (isC99VarArgs) MI->setIsC99Varargs();
1749 if (isGNUVarArgs) MI->setIsGNUVarargs();
1750 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001751 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 }
1753
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 // Remember that we saw this macro last so that we add the tokens that
1755 // form its body to it.
1756 Macro = MI;
1757
1758 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1759 Record[NextIndex]) {
1760 // We have a macro definition. Register the association
1761 PreprocessedEntityID
1762 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1763 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001764 PreprocessingRecord::PPEntityID PPID =
1765 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001766 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001767 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001768 if (PPDef)
1769 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001770 }
1771
1772 ++NumMacrosRead;
1773 break;
1774 }
1775
1776 case PP_TOKEN: {
1777 // If we see a TOKEN before a PP_MACRO_*, then the file is
1778 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001779 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001780
John McCallf413f5e2013-05-03 00:10:13 +00001781 unsigned Idx = 0;
1782 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 Macro->AddTokenToBody(Tok);
1784 break;
1785 }
1786 }
1787 }
1788}
1789
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001790PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001791ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1792 unsigned LocalID) const {
1793 if (!M.ModuleOffsetMap.empty())
1794 ReadModuleOffsetMap(M);
1795
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001796 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001798 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001800
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 return LocalID + I->second;
1802}
1803
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001804unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1805 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001806}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001807
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001808HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001809HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001810 internal_key_type ikey = {FE->getSize(),
1811 M.HasTimestamps ? FE->getModificationTime() : 0,
1812 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001813 return ikey;
1814}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001815
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001816bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001817 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 return false;
1819
Mehdi Amini004b9c72016-10-10 22:52:47 +00001820 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001821 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001822
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001824 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001825 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001826 if (!Key.Imported) {
1827 if (auto File = FileMgr.getFile(Key.Filename))
1828 return *File;
1829 return nullptr;
1830 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001831
1832 std::string Resolved = Key.Filename;
1833 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001834 if (auto File = FileMgr.getFile(Resolved))
1835 return *File;
1836 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001837 };
1838
1839 const FileEntry *FEA = GetFile(a);
1840 const FileEntry *FEB = GetFile(b);
1841 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001842}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001843
Guy Benyei11169dd2012-12-18 14:30:41 +00001844std::pair<unsigned, unsigned>
1845HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001846 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001847
Vedant Kumar48b4f762018-04-14 01:40:48 +00001848 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1849 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001850 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001851}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001852
1853HeaderFileInfoTrait::internal_key_type
1854HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001855 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001856
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001857 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001858 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1859 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001860 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001861 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001862 return ikey;
1863}
1864
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001865HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001866HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001868 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001869
1870 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 HeaderFileInfo HFI;
1872 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001873 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001874 HFI.isImport |= (Flags >> 5) & 0x01;
1875 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1876 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001878 // FIXME: Find a better way to handle this. Maybe just store a
1879 // "has been included" flag?
1880 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1881 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001882 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1883 M, endian::readNext<uint32_t, little, unaligned>(d));
1884 if (unsigned FrameworkOffset =
1885 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001886 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 // since 0 is used as an indicator for "no framework name".
1888 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1889 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1890 }
Richard Smith386bb072015-08-18 23:42:23 +00001891
1892 assert((End - d) % 4 == 0 &&
1893 "Wrong data length in HeaderFileInfo deserialization");
1894 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001895 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001896 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1897 LocalSMID >>= 2;
1898
1899 // This header is part of a module. Associate it with the module to enable
1900 // implicit module import.
1901 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1902 Module *Mod = Reader.getSubmodule(GlobalSMID);
1903 FileManager &FileMgr = Reader.getFileManager();
1904 ModuleMap &ModMap =
1905 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1906
1907 std::string Filename = key.Filename;
1908 if (key.Imported)
1909 Reader.ResolveImportedPath(M, Filename);
1910 // FIXME: This is not always the right filename-as-written, but we're not
1911 // going to use this information to rebuild the module, so it doesn't make
1912 // a lot of difference.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001913 Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001914 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1915 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001916 }
1917
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 // This HeaderFileInfo was externally loaded.
1919 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001920 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 return HFI;
1922}
1923
Richard Smithd7329392015-04-21 21:46:32 +00001924void ASTReader::addPendingMacro(IdentifierInfo *II,
1925 ModuleFile *M,
1926 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001927 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1928 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001929}
1930
1931void ASTReader::ReadDefinedMacros() {
1932 // Note that we are loading defined macros.
1933 Deserializing Macros(this);
1934
Vedant Kumar48b4f762018-04-14 01:40:48 +00001935 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001936 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001937
1938 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001939 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 continue;
1941
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001942 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001943 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1944 Error(std::move(Err));
1945 return;
1946 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001947
1948 RecordData Record;
1949 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001950 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1951 if (!MaybeE) {
1952 Error(MaybeE.takeError());
1953 return;
1954 }
1955 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001956
Chris Lattnere7b154b2013-01-19 21:39:22 +00001957 switch (E.Kind) {
1958 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1959 case llvm::BitstreamEntry::Error:
1960 Error("malformed block record in AST file");
1961 return;
1962 case llvm::BitstreamEntry::EndBlock:
1963 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001964
JF Bastien0e828952019-06-26 19:50:12 +00001965 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001966 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001967 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1968 if (!MaybeRecord) {
1969 Error(MaybeRecord.takeError());
1970 return;
1971 }
1972 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001973 default: // Default behavior: ignore.
1974 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001975
Chris Lattnere7b154b2013-01-19 21:39:22 +00001976 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001977 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001978 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001979 if (II->isOutOfDate())
1980 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001981 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001982 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001983
Chris Lattnere7b154b2013-01-19 21:39:22 +00001984 case PP_TOKEN:
1985 // Ignore tokens.
1986 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 break;
1989 }
JF Bastien0e828952019-06-26 19:50:12 +00001990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001992 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
1994}
1995
1996namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001997
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001998 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 class IdentifierLookupVisitor {
2000 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002001 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002003 unsigned &NumIdentifierLookups;
2004 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002005 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002006
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002008 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2009 unsigned &NumIdentifierLookups,
2010 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002011 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2012 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002013 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002014 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002015
2016 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002018 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002020
Vedant Kumar48b4f762018-04-14 01:40:48 +00002021 ASTIdentifierLookupTable *IdTable
2022 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 if (!IdTable)
2024 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002025
2026 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002027 Found);
2028 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002029 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002030 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 if (Pos == IdTable->end())
2032 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002033
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 // Dereferencing the iterator has the effect of building the
2035 // IdentifierInfo node and populating it with the various
2036 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002037 ++NumIdentifierLookupHits;
2038 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 return true;
2040 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002042 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 // files.
2044 IdentifierInfo *getIdentifierInfo() const { return Found; }
2045 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002046
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002047} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
2049void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2050 // Note that we are loading an identifier.
2051 Deserializing AnIdentifier(this);
2052
2053 unsigned PriorGeneration = 0;
2054 if (getContext().getLangOpts().Modules)
2055 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002056
2057 // If there is a global index, look there first to determine which modules
2058 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002059 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002060 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002061 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002062 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2063 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002064 }
2065 }
2066
Douglas Gregor7211ac12013-01-25 23:32:03 +00002067 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002068 NumIdentifierLookups,
2069 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002070 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002071 markIdentifierUpToDate(&II);
2072}
2073
2074void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2075 if (!II)
2076 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002077
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 II->setOutOfDate(false);
2079
2080 // Update the generation for this identifier.
2081 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002082 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002083}
2084
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002085void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2086 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002087 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002088
2089 BitstreamCursor &Cursor = M.MacroCursor;
2090 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002091 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2092 Error(std::move(Err));
2093 return;
2094 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002095
Richard Smith713369b2015-04-23 20:40:50 +00002096 struct ModuleMacroRecord {
2097 SubmoduleID SubModID;
2098 MacroInfo *MI;
2099 SmallVector<SubmoduleID, 8> Overrides;
2100 };
2101 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002102
Richard Smithd7329392015-04-21 21:46:32 +00002103 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2104 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2105 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002106 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002107 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002108 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002109 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002110 if (!MaybeEntry) {
2111 Error(MaybeEntry.takeError());
2112 return;
2113 }
2114 llvm::BitstreamEntry Entry = MaybeEntry.get();
2115
Richard Smithd7329392015-04-21 21:46:32 +00002116 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2117 Error("malformed block record in AST file");
2118 return;
2119 }
2120
2121 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002122 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2123 if (!MaybePP) {
2124 Error(MaybePP.takeError());
2125 return;
2126 }
2127 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002128 case PP_MACRO_DIRECTIVE_HISTORY:
2129 break;
2130
2131 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002132 ModuleMacros.push_back(ModuleMacroRecord());
2133 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002134 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2135 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002136 for (int I = 2, N = Record.size(); I != N; ++I)
2137 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002138 continue;
2139 }
2140
2141 default:
2142 Error("malformed block record in AST file");
2143 return;
2144 }
2145
2146 // We found the macro directive history; that's the last record
2147 // for this macro.
2148 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002149 }
2150
Richard Smithd7329392015-04-21 21:46:32 +00002151 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002152 {
2153 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002154 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002155 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002156 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002157 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002158 Module *Mod = getSubmodule(ModID);
2159 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002160 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002161 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002162 }
2163
2164 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002165 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002166 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002167 }
2168 }
2169
2170 // Don't read the directive history for a module; we don't have anywhere
2171 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002172 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002173 return;
2174
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002175 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002176 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002177 unsigned Idx = 0, N = Record.size();
2178 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002179 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002180 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002181 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002182 switch (K) {
2183 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002184 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002185 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002186 break;
2187 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002188 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002189 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002190 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002191 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002192 bool isPublic = Record[Idx++];
2193 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2194 break;
2195 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002196
2197 if (!Latest)
2198 Latest = MD;
2199 if (Earliest)
2200 Earliest->setPrevious(MD);
2201 Earliest = MD;
2202 }
2203
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002204 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002205 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002206}
2207
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002208ASTReader::InputFileInfo
2209ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 // Go find this input file.
2211 BitstreamCursor &Cursor = F.InputFilesCursor;
2212 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002213 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2214 // FIXME this drops errors on the floor.
2215 consumeError(std::move(Err));
2216 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002217
JF Bastien0e828952019-06-26 19:50:12 +00002218 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2219 if (!MaybeCode) {
2220 // FIXME this drops errors on the floor.
2221 consumeError(MaybeCode.takeError());
2222 }
2223 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002224 RecordData Record;
2225 StringRef Blob;
2226
JF Bastien0e828952019-06-26 19:50:12 +00002227 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2228 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2229 "invalid record type for input file");
2230 else {
2231 // FIXME this drops errors on the floor.
2232 consumeError(Maybe.takeError());
2233 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002234
2235 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002236 InputFileInfo R;
2237 R.StoredSize = static_cast<off_t>(Record[1]);
2238 R.StoredTime = static_cast<time_t>(Record[2]);
2239 R.Overridden = static_cast<bool>(Record[3]);
2240 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002241 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002242 R.Filename = Blob;
2243 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002244 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002245}
2246
Manman Renc8c94152016-10-21 23:35:03 +00002247static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002248InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 // If this ID is bogus, just return an empty input file.
2250 if (ID == 0 || ID > F.InputFilesLoaded.size())
2251 return InputFile();
2252
2253 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002254 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return F.InputFilesLoaded[ID-1];
2256
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002257 if (F.InputFilesLoaded[ID-1].isNotFound())
2258 return InputFile();
2259
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002261 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002263 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2264 // FIXME this drops errors on the floor.
2265 consumeError(std::move(Err));
2266 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002267
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002268 InputFileInfo FI = readInputFileInfo(F, ID);
2269 off_t StoredSize = FI.StoredSize;
2270 time_t StoredTime = FI.StoredTime;
2271 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002272 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002273 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002274
Harlan Haskins8d323d12019-08-01 21:31:56 +00002275 const FileEntry *File = nullptr;
2276 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2277 File = *FE;
2278
Ben Langmuir198c1682014-03-07 07:27:49 +00002279 // If we didn't find the file, resolve it relative to the
2280 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002281 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2282 F.OriginalDir != F.BaseDirectory) {
2283 std::string Resolved = resolveFileRelativeToOriginalDir(
2284 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002285 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002286 if (auto FE = FileMgr.getFile(Resolved))
2287 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002288 }
2289
2290 // For an overridden file, create a virtual file with the stored
2291 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002292 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002293 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002294
Craig Toppera13603a2014-05-22 05:54:18 +00002295 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002296 if (Complain) {
2297 std::string ErrorStr = "could not find file '";
2298 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002299 ErrorStr += "' referenced by AST file '";
2300 ErrorStr += F.FileName;
2301 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002302 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002304 // Record that we didn't find the file.
2305 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2306 return InputFile();
2307 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002308
Ben Langmuir198c1682014-03-07 07:27:49 +00002309 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002310 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002311 // can lead to problems when lexing using the source locations from the
2312 // PCH.
2313 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002314 // FIXME: Reject if the overrides are different.
2315 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002316 if (Complain)
2317 Error(diag::err_fe_pch_file_overridden, Filename);
2318 // After emitting the diagnostic, recover by disabling the override so
2319 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002320 //
2321 // FIXME: This recovery is just as broken as the original state; there may
2322 // be another precompiled module that's using the overridden contents, or
2323 // we might be half way through parsing it. Instead, we should treat the
2324 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002325 SM.disableFileContentsOverride(File);
2326 // The FileEntry is a virtual file entry with the size of the contents
2327 // that would override the original contents. Set it to the original's
2328 // size/time.
2329 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2330 StoredSize, StoredTime);
2331 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002332
Ben Langmuir198c1682014-03-07 07:27:49 +00002333 bool IsOutOfDate = false;
2334
2335 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002336 if (!Overridden && //
2337 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002338 (StoredTime && StoredTime != File->getModificationTime() &&
2339 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002340 )) {
2341 if (Complain) {
2342 // Build a list of the PCH imports that got us here (in reverse).
2343 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002344 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002345 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002346
Ben Langmuir198c1682014-03-07 07:27:49 +00002347 // The top-level PCH is stale.
2348 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002349 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2350 if (DiagnosticKind == 0)
2351 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2352 else if (DiagnosticKind == 1)
2353 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2354 else
2355 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002356
Ben Langmuir198c1682014-03-07 07:27:49 +00002357 // Print the import stack.
2358 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2359 Diag(diag::note_pch_required_by)
2360 << Filename << ImportStack[0]->FileName;
2361 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002362 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002363 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002364 }
2365
Ben Langmuir198c1682014-03-07 07:27:49 +00002366 if (!Diags.isDiagnosticInFlight())
2367 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 }
2369
Ben Langmuir198c1682014-03-07 07:27:49 +00002370 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002372 // FIXME: If the file is overridden and we've already opened it,
2373 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002374
Richard Smitha8cfffa2015-11-26 02:04:16 +00002375 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002376
2377 // Note that we've loaded this input file.
2378 F.InputFilesLoaded[ID-1] = IF;
2379 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002380}
2381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002382/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002383/// is not an absolute path, add the system or module root to the beginning of
2384/// the file name.
2385void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2386 // Resolve relative to the base directory, if we have one.
2387 if (!M.BaseDirectory.empty())
2388 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002389}
2390
Richard Smith7ed1bc92014-12-05 22:42:13 +00002391void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2393 return;
2394
Richard Smith7ed1bc92014-12-05 22:42:13 +00002395 SmallString<128> Buffer;
2396 llvm::sys::path::append(Buffer, Prefix, Filename);
2397 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002398}
2399
Richard Smith0f99d6a2015-08-09 08:48:41 +00002400static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2401 switch (ARR) {
2402 case ASTReader::Failure: return true;
2403 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2404 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2405 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2406 case ASTReader::ConfigurationMismatch:
2407 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2408 case ASTReader::HadErrors: return true;
2409 case ASTReader::Success: return false;
2410 }
2411
2412 llvm_unreachable("unknown ASTReadResult");
2413}
2414
Richard Smith0516b182015-09-08 19:40:14 +00002415ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2416 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2417 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002418 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002419 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2420 // FIXME this drops errors on the floor.
2421 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002422 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002423 }
Richard Smith0516b182015-09-08 19:40:14 +00002424
2425 // Read all of the records in the options block.
2426 RecordData Record;
2427 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002428 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002429 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2430 if (!MaybeEntry) {
2431 // FIXME this drops errors on the floor.
2432 consumeError(MaybeEntry.takeError());
2433 return Failure;
2434 }
2435 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002436
Richard Smith0516b182015-09-08 19:40:14 +00002437 switch (Entry.Kind) {
2438 case llvm::BitstreamEntry::Error:
2439 case llvm::BitstreamEntry::SubBlock:
2440 return Failure;
2441
2442 case llvm::BitstreamEntry::EndBlock:
2443 return Result;
2444
2445 case llvm::BitstreamEntry::Record:
2446 // The interesting case.
2447 break;
2448 }
2449
2450 // Read and process a record.
2451 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002452 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2453 if (!MaybeRecordType) {
2454 // FIXME this drops errors on the floor.
2455 consumeError(MaybeRecordType.takeError());
2456 return Failure;
2457 }
2458 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002459 case LANGUAGE_OPTIONS: {
2460 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2461 if (ParseLanguageOptions(Record, Complain, Listener,
2462 AllowCompatibleConfigurationMismatch))
2463 Result = ConfigurationMismatch;
2464 break;
2465 }
2466
2467 case TARGET_OPTIONS: {
2468 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2469 if (ParseTargetOptions(Record, Complain, Listener,
2470 AllowCompatibleConfigurationMismatch))
2471 Result = ConfigurationMismatch;
2472 break;
2473 }
2474
Richard Smith0516b182015-09-08 19:40:14 +00002475 case FILE_SYSTEM_OPTIONS: {
2476 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2477 if (!AllowCompatibleConfigurationMismatch &&
2478 ParseFileSystemOptions(Record, Complain, Listener))
2479 Result = ConfigurationMismatch;
2480 break;
2481 }
2482
2483 case HEADER_SEARCH_OPTIONS: {
2484 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2485 if (!AllowCompatibleConfigurationMismatch &&
2486 ParseHeaderSearchOptions(Record, Complain, Listener))
2487 Result = ConfigurationMismatch;
2488 break;
2489 }
2490
2491 case PREPROCESSOR_OPTIONS:
2492 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2493 if (!AllowCompatibleConfigurationMismatch &&
2494 ParsePreprocessorOptions(Record, Complain, Listener,
2495 SuggestedPredefines))
2496 Result = ConfigurationMismatch;
2497 break;
2498 }
2499 }
2500}
2501
Guy Benyei11169dd2012-12-18 14:30:41 +00002502ASTReader::ASTReadResult
2503ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002504 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002505 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002507 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002508 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509
JF Bastien0e828952019-06-26 19:50:12 +00002510 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2511 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 return Failure;
2513 }
2514
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002515 // Lambda to read the unhashed control block the first time it's called.
2516 //
2517 // For PCM files, the unhashed control block cannot be read until after the
2518 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2519 // need to look ahead before reading the IMPORTS record. For consistency,
2520 // this block is always read somehow (see BitstreamEntry::EndBlock).
2521 bool HasReadUnhashedControlBlock = false;
2522 auto readUnhashedControlBlockOnce = [&]() {
2523 if (!HasReadUnhashedControlBlock) {
2524 HasReadUnhashedControlBlock = true;
2525 if (ASTReadResult Result =
2526 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2527 return Result;
2528 }
2529 return Success;
2530 };
2531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 // Read all of the records and blocks in the control block.
2533 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002534 unsigned NumInputs = 0;
2535 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002536 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002537 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002538 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2539 if (!MaybeEntry) {
2540 Error(MaybeEntry.takeError());
2541 return Failure;
2542 }
2543 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002544
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545 switch (Entry.Kind) {
2546 case llvm::BitstreamEntry::Error:
2547 Error("malformed block record in AST file");
2548 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002549 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002550 // Validate the module before returning. This call catches an AST with
2551 // no module name and no imports.
2552 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2553 return Result;
2554
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002555 // Validate input files.
2556 const HeaderSearchOptions &HSOpts =
2557 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002558
Richard Smitha1825302014-10-23 22:18:29 +00002559 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002560 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2561 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002562 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2563 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002565
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002566 // If we are reading a module, we will create a verification timestamp,
2567 // so we verify all input files. Otherwise, verify only user input
2568 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002569
2570 unsigned N = NumUserInputs;
2571 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002572 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002573 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002574 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002575 N = NumInputs;
2576
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002577 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002578 InputFile IF = getInputFile(F, I+1, Complain);
2579 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002581 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002583
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002584 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002585 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002586
Ben Langmuircb69b572014-03-07 06:40:32 +00002587 if (Listener && Listener->needsInputFileVisitation()) {
2588 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2589 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002590 for (unsigned I = 0; I < N; ++I) {
2591 bool IsSystem = I >= NumUserInputs;
2592 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002593 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002594 F.Kind == MK_ExplicitModule ||
2595 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002596 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002597 }
2598
Richard Smith8a308ec2015-11-05 00:54:55 +00002599 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002600 }
2601
Chris Lattnere7b154b2013-01-19 21:39:22 +00002602 case llvm::BitstreamEntry::SubBlock:
2603 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 case INPUT_FILES_BLOCK_ID:
2605 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002606 if (llvm::Error Err = Stream.SkipBlock()) {
2607 Error(std::move(Err));
2608 return Failure;
2609 }
2610 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 Error("malformed block record in AST file");
2612 return Failure;
2613 }
2614 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002615
2616 case OPTIONS_BLOCK_ID:
2617 // If we're reading the first module for this group, check its options
2618 // are compatible with ours. For modules it imports, no further checking
2619 // is required, because we checked them when we built it.
2620 if (Listener && !ImportedBy) {
2621 // Should we allow the configuration of the module file to differ from
2622 // the configuration of the current translation unit in a compatible
2623 // way?
2624 //
2625 // FIXME: Allow this for files explicitly specified with -include-pch.
2626 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002627 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002628
Richard Smith8a308ec2015-11-05 00:54:55 +00002629 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2630 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002631 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002632 if (Result == Failure) {
2633 Error("malformed block record in AST file");
2634 return Result;
2635 }
2636
Richard Smith8a308ec2015-11-05 00:54:55 +00002637 if (DisableValidation ||
2638 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2639 Result = Success;
2640
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002641 // If we can't load the module, exit early since we likely
2642 // will rebuild the module anyway. The stream may be in the
2643 // middle of a block.
2644 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002645 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002646 } else if (llvm::Error Err = Stream.SkipBlock()) {
2647 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002648 return Failure;
2649 }
2650 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002651
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 default:
JF Bastien0e828952019-06-26 19:50:12 +00002653 if (llvm::Error Err = Stream.SkipBlock()) {
2654 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 return Failure;
2656 }
2657 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002659
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660 case llvm::BitstreamEntry::Record:
2661 // The interesting case.
2662 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 }
2664
2665 // Read and process a record.
2666 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002667 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002668 Expected<unsigned> MaybeRecordType =
2669 Stream.readRecord(Entry.ID, Record, &Blob);
2670 if (!MaybeRecordType) {
2671 Error(MaybeRecordType.takeError());
2672 return Failure;
2673 }
2674 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case METADATA: {
2676 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2677 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002678 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2679 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 return VersionMismatch;
2681 }
2682
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002683 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2685 Diag(diag::err_pch_with_compiler_errors);
2686 return HadErrors;
2687 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002688 if (hasErrors) {
2689 Diags.ErrorOccurred = true;
2690 Diags.UncompilableErrorOccurred = true;
2691 Diags.UnrecoverableErrorOccurred = true;
2692 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002693
2694 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002695 // Relative paths in a relocatable PCH are relative to our sysroot.
2696 if (F.RelocatablePCH)
2697 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698
Richard Smithe75ee0f2015-08-17 07:13:32 +00002699 F.HasTimestamps = Record[5];
2700
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002701 F.PCHHasObjectFile = Record[6];
2702
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002704 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2706 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002707 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 return VersionMismatch;
2709 }
2710 break;
2711 }
2712
2713 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002714 // Validate the AST before processing any imports (otherwise, untangling
2715 // them can be error-prone and expensive). A module will have a name and
2716 // will already have been validated, but this catches the PCH case.
2717 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2718 return Result;
2719
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002720 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 unsigned Idx = 0, N = Record.size();
2722 while (Idx < N) {
2723 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002724 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 // The import location will be the local one for now; we will adjust
2726 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002727 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002729 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002730 off_t StoredSize = (off_t)Record[Idx++];
2731 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002732 ASTFileSignature StoredSignature = {
2733 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2734 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2735 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002736
2737 std::string ImportedName = ReadString(Record, Idx);
2738 std::string ImportedFile;
2739
2740 // For prebuilt and explicit modules first consult the file map for
2741 // an override. Note that here we don't search prebuilt module
2742 // directories, only the explicit name to file mappings. Also, we will
2743 // still verify the size/signature making sure it is essentially the
2744 // same file but perhaps in a different location.
2745 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2746 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2747 ImportedName, /*FileMapOnly*/ true);
2748
2749 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002750 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2751 // ModuleCache as when writing.
2752 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002753 else
2754 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002755
Richard Smith0f99d6a2015-08-09 08:48:41 +00002756 // If our client can't cope with us being out of date, we can't cope with
2757 // our dependency being missing.
2758 unsigned Capabilities = ClientLoadCapabilities;
2759 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2760 Capabilities &= ~ARR_Missing;
2761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002763 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2764 Loaded, StoredSize, StoredModTime,
2765 StoredSignature, Capabilities);
2766
2767 // If we diagnosed a problem, produce a backtrace.
2768 if (isDiagnosedResult(Result, Capabilities))
2769 Diag(diag::note_module_file_imported_by)
2770 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2771
2772 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 case Failure: return Failure;
2774 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002775 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 case OutOfDate: return OutOfDate;
2777 case VersionMismatch: return VersionMismatch;
2778 case ConfigurationMismatch: return ConfigurationMismatch;
2779 case HadErrors: return HadErrors;
2780 case Success: break;
2781 }
2782 }
2783 break;
2784 }
2785
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 case ORIGINAL_FILE:
2787 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002788 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002790 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 break;
2792
2793 case ORIGINAL_FILE_ID:
2794 F.OriginalSourceFileID = FileID::get(Record[0]);
2795 break;
2796
2797 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002798 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002801 case MODULE_NAME:
2802 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002803 Diag(diag::remark_module_import)
2804 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2805 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002806 if (Listener)
2807 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002808
2809 // Validate the AST as soon as we have a name so we can exit early on
2810 // failure.
2811 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2812 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002813
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002814 break;
2815
Richard Smith223d3f22014-12-06 03:21:08 +00002816 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002817 // Save the BaseDirectory as written in the PCM for computing the module
2818 // filename for the ModuleCache.
2819 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002820 assert(!F.ModuleName.empty() &&
2821 "MODULE_DIRECTORY found before MODULE_NAME");
2822 // If we've already loaded a module map file covering this module, we may
2823 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002824 Module *M = PP.getHeaderSearchInfo().lookupModule(
2825 F.ModuleName, /*AllowSearch*/ true,
2826 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002827 if (M && M->Directory) {
2828 // If we're implicitly loading a module, the base directory can't
2829 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002830 // Don't emit module relocation error if we have -fno-validate-pch
2831 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2832 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002833 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2834 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002835 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2836 Diag(diag::err_imported_module_relocated)
2837 << F.ModuleName << Blob << M->Directory->getName();
2838 return OutOfDate;
2839 }
2840 }
2841 F.BaseDirectory = M->Directory->getName();
2842 } else {
2843 F.BaseDirectory = Blob;
2844 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002845 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002846 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002847
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002848 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002849 if (ASTReadResult Result =
2850 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2851 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002852 break;
2853
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002854 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002855 NumInputs = Record[0];
2856 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002857 F.InputFileOffsets =
2858 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002859 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002860 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 break;
2862 }
2863 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002864}
2865
Ben Langmuir2c9af442014-04-10 17:57:43 +00002866ASTReader::ASTReadResult
2867ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002868 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002869
JF Bastien0e828952019-06-26 19:50:12 +00002870 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2871 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002872 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 }
2874
2875 // Read all of the records and blocks for the AST file.
2876 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002877 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002878 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2879 if (!MaybeEntry) {
2880 Error(MaybeEntry.takeError());
2881 return Failure;
2882 }
2883 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002884
Chris Lattnere7b154b2013-01-19 21:39:22 +00002885 switch (Entry.Kind) {
2886 case llvm::BitstreamEntry::Error:
2887 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002888 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002889 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002890 // Outside of C++, we do not store a lookup map for the translation unit.
2891 // Instead, mark it as needing a lookup map to be built if this module
2892 // contains any declarations lexically within it (which it always does!).
2893 // This usually has no cost, since we very rarely need the lookup map for
2894 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002895 if (ASTContext *Ctx = ContextObj) {
2896 DeclContext *DC = Ctx->getTranslationUnitDecl();
2897 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2898 DC->setMustBuildLookupTable();
2899 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002900
Ben Langmuir2c9af442014-04-10 17:57:43 +00002901 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002902 case llvm::BitstreamEntry::SubBlock:
2903 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 case DECLTYPES_BLOCK_ID:
2905 // We lazily load the decls block, but we want to set up the
2906 // DeclsCursor cursor to point into it. Clone our current bitcode
2907 // cursor to it, enter the block and read the abbrevs in that block.
2908 // With the main cursor, we just skip over it.
2909 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002910 if (llvm::Error Err = Stream.SkipBlock()) {
2911 Error(std::move(Err));
2912 return Failure;
2913 }
2914 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002916 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 }
2918 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002919
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 case PREPROCESSOR_BLOCK_ID:
2921 F.MacroCursor = Stream;
2922 if (!PP.getExternalSource())
2923 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002924
JF Bastien0e828952019-06-26 19:50:12 +00002925 if (llvm::Error Err = Stream.SkipBlock()) {
2926 Error(std::move(Err));
2927 return Failure;
2928 }
2929 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002931 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 }
2933 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2934 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002935
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 case PREPROCESSOR_DETAIL_BLOCK_ID:
2937 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002938
2939 if (llvm::Error Err = Stream.SkipBlock()) {
2940 Error(std::move(Err));
2941 return Failure;
2942 }
2943 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00002945 Error("malformed preprocessor detail record in AST file");
2946 return Failure;
2947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002949 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002950
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 if (!PP.getPreprocessingRecord())
2952 PP.createPreprocessingRecord();
2953 if (!PP.getPreprocessingRecord()->getExternalSource())
2954 PP.getPreprocessingRecord()->SetExternalSource(*this);
2955 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002956
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 case SOURCE_MANAGER_BLOCK_ID:
2958 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002959 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002961
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002963 if (ASTReadResult Result =
2964 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002965 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002967
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002969 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002970
2971 if (llvm::Error Err = Stream.SkipBlock()) {
2972 Error(std::move(Err));
2973 return Failure;
2974 }
2975 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002977 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 }
2979 CommentsCursors.push_back(std::make_pair(C, &F));
2980 break;
2981 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002982
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 default:
JF Bastien0e828952019-06-26 19:50:12 +00002984 if (llvm::Error Err = Stream.SkipBlock()) {
2985 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002987 }
2988 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 }
2990 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002991
Chris Lattnere7b154b2013-01-19 21:39:22 +00002992 case llvm::BitstreamEntry::Record:
2993 // The interesting case.
2994 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 }
2996
2997 // Read and process a record.
2998 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002999 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003000 Expected<unsigned> MaybeRecordType =
3001 Stream.readRecord(Entry.ID, Record, &Blob);
3002 if (!MaybeRecordType) {
3003 Error(MaybeRecordType.takeError());
3004 return Failure;
3005 }
3006 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003007
3008 // If we're not loading an AST context, we don't care about most records.
3009 if (!ContextObj) {
3010 switch (RecordType) {
3011 case IDENTIFIER_TABLE:
3012 case IDENTIFIER_OFFSET:
3013 case INTERESTING_IDENTIFIERS:
3014 case STATISTICS:
3015 case PP_CONDITIONAL_STACK:
3016 case PP_COUNTER_VALUE:
3017 case SOURCE_LOCATION_OFFSETS:
3018 case MODULE_OFFSET_MAP:
3019 case SOURCE_MANAGER_LINE_TABLE:
3020 case SOURCE_LOCATION_PRELOADS:
3021 case PPD_ENTITIES_OFFSETS:
3022 case HEADER_SEARCH_TABLE:
3023 case IMPORTED_MODULES:
3024 case MACRO_OFFSET:
3025 break;
3026 default:
3027 continue;
3028 }
3029 }
3030
3031 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 default: // Default behavior: ignore.
3033 break;
3034
3035 case TYPE_OFFSET: {
3036 if (F.LocalNumTypes != 0) {
3037 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003040 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 F.LocalNumTypes = Record[0];
3042 unsigned LocalBaseTypeIndex = Record[1];
3043 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 if (F.LocalNumTypes > 0) {
3046 // Introduce the global -> local mapping for types within this module.
3047 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003048
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 // Introduce the local -> global mapping for types within this module.
3050 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003051 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003053
3054 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056 break;
3057 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003058
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 case DECL_OFFSET: {
3060 if (F.LocalNumDecls != 0) {
3061 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003064 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 F.LocalNumDecls = Record[0];
3066 unsigned LocalBaseDeclID = Record[1];
3067 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003068
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003070 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 // module.
3072 GlobalDeclMap.insert(
3073 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003074
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 // Introduce the local -> global mapping for declarations within this
3076 // module.
3077 F.DeclRemap.insertOrReplace(
3078 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003079
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 // Introduce the global -> local mapping for declarations within this
3081 // module.
3082 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003083
Ben Langmuir52ca6782014-10-20 16:27:32 +00003084 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 break;
3087 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003090 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003091 LexicalContents Contents(
3092 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3093 Blob.data()),
3094 static_cast<unsigned int>(Blob.size() / 4));
3095 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 TU->setHasExternalLexicalStorage(true);
3097 break;
3098 }
3099
3100 case UPDATE_VISIBLE: {
3101 unsigned Idx = 0;
3102 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003103 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003104 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003105 // If we've already loaded the decl, perform the updates when we finish
3106 // loading this block.
3107 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003108 PendingUpdateRecords.push_back(
3109 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 break;
3111 }
3112
3113 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003114 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003116 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3117 (const unsigned char *)F.IdentifierTableData + Record[0],
3118 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3119 (const unsigned char *)F.IdentifierTableData,
3120 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003121
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3123 }
3124 break;
3125
3126 case IDENTIFIER_OFFSET: {
3127 if (F.LocalNumIdentifiers != 0) {
3128 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003129 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003131 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 F.LocalNumIdentifiers = Record[0];
3133 unsigned LocalBaseIdentifierID = Record[1];
3134 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 if (F.LocalNumIdentifiers > 0) {
3137 // Introduce the global -> local mapping for identifiers within this
3138 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003139 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003141
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 // Introduce the local -> global mapping for identifiers within this
3143 // module.
3144 F.IdentifierRemap.insertOrReplace(
3145 std::make_pair(LocalBaseIdentifierID,
3146 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003147
Ben Langmuir52ca6782014-10-20 16:27:32 +00003148 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3149 + F.LocalNumIdentifiers);
3150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 break;
3152 }
3153
Richard Smith33e0f7e2015-07-22 02:08:40 +00003154 case INTERESTING_IDENTIFIERS:
3155 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3156 break;
3157
Ben Langmuir332aafe2014-01-31 01:06:56 +00003158 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003159 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3160 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003162 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 break;
3164
David Blaikie9ffe5a32017-01-30 05:00:26 +00003165 case MODULAR_CODEGEN_DECLS:
3166 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3167 // them (ie: if we're not codegenerating this module).
3168 if (F.Kind == MK_MainFile)
3169 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3170 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3171 break;
3172
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003174 if (SpecialTypes.empty()) {
3175 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3176 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3177 break;
3178 }
3179
3180 if (SpecialTypes.size() != Record.size()) {
3181 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003182 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003183 }
3184
3185 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3186 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3187 if (!SpecialTypes[I])
3188 SpecialTypes[I] = ID;
3189 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3190 // merge step?
3191 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 break;
3193
3194 case STATISTICS:
3195 TotalNumStatements += Record[0];
3196 TotalNumMacros += Record[1];
3197 TotalLexicalDeclContexts += Record[2];
3198 TotalVisibleDeclContexts += Record[3];
3199 break;
3200
3201 case UNUSED_FILESCOPED_DECLS:
3202 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3203 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3204 break;
3205
3206 case DELEGATING_CTORS:
3207 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3208 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3209 break;
3210
3211 case WEAK_UNDECLARED_IDENTIFIERS:
3212 if (Record.size() % 4 != 0) {
3213 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003214 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003216
3217 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 // files. This isn't the way to do it :)
3219 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003220
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 // Translate the weak, undeclared identifiers into global IDs.
3222 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3223 WeakUndeclaredIdentifiers.push_back(
3224 getGlobalIdentifierID(F, Record[I++]));
3225 WeakUndeclaredIdentifiers.push_back(
3226 getGlobalIdentifierID(F, Record[I++]));
3227 WeakUndeclaredIdentifiers.push_back(
3228 ReadSourceLocation(F, Record, I).getRawEncoding());
3229 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3230 }
3231 break;
3232
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003234 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 F.LocalNumSelectors = Record[0];
3236 unsigned LocalBaseSelectorID = Record[1];
3237 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003238
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003240 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 // module.
3242 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003243
3244 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // module.
3246 F.SelectorRemap.insertOrReplace(
3247 std::make_pair(LocalBaseSelectorID,
3248 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003249
3250 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 }
3252 break;
3253 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003254
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003256 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 if (Record[0])
3258 F.SelectorLookupTable
3259 = ASTSelectorLookupTable::Create(
3260 F.SelectorLookupTableData + Record[0],
3261 F.SelectorLookupTableData,
3262 ASTSelectorLookupTrait(*this, F));
3263 TotalNumMethodPoolEntries += Record[1];
3264 break;
3265
3266 case REFERENCED_SELECTOR_POOL:
3267 if (!Record.empty()) {
3268 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003269 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 Record[Idx++]));
3271 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3272 getRawEncoding());
3273 }
3274 }
3275 break;
3276
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003277 case PP_CONDITIONAL_STACK:
3278 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003279 unsigned Idx = 0, End = Record.size() - 1;
3280 bool ReachedEOFWhileSkipping = Record[Idx++];
3281 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3282 if (ReachedEOFWhileSkipping) {
3283 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3284 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3285 bool FoundNonSkipPortion = Record[Idx++];
3286 bool FoundElse = Record[Idx++];
3287 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3288 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3289 FoundElse, ElseLoc);
3290 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003291 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003292 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003293 auto Loc = ReadSourceLocation(F, Record, Idx);
3294 bool WasSkipping = Record[Idx++];
3295 bool FoundNonSkip = Record[Idx++];
3296 bool FoundElse = Record[Idx++];
3297 ConditionalStack.push_back(
3298 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3299 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003300 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003301 }
3302 break;
3303
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 case PP_COUNTER_VALUE:
3305 if (!Record.empty() && Listener)
3306 Listener->ReadCounter(F, Record[0]);
3307 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003308
Guy Benyei11169dd2012-12-18 14:30:41 +00003309 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003310 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 F.NumFileSortedDecls = Record[0];
3312 break;
3313
3314 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003315 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 F.LocalNumSLocEntries = Record[0];
3317 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003318 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003319 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003320 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003321 if (!F.SLocEntryBaseID) {
3322 Error("ran out of source locations");
3323 break;
3324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003325 // Make our entry in the range map. BaseID is negative and growing, so
3326 // we invert it. Because we invert it, though, we need the other end of
3327 // the range.
3328 unsigned RangeStart =
3329 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3330 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3331 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3332
3333 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3334 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3335 GlobalSLocOffsetMap.insert(
3336 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3337 - SLocSpaceSize,&F));
3338
3339 // Initialize the remapping table.
3340 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003341 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003343 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 TotalNumSLocEntries += F.LocalNumSLocEntries;
3347 break;
3348 }
3349
Richard Smith37a93df2017-02-18 00:32:02 +00003350 case MODULE_OFFSET_MAP:
3351 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003353
3354 case SOURCE_MANAGER_LINE_TABLE:
3355 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003356 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 break;
3358
3359 case SOURCE_LOCATION_PRELOADS: {
3360 // Need to transform from the local view (1-based IDs) to the global view,
3361 // which is based off F.SLocEntryBaseID.
3362 if (!F.PreloadSLocEntries.empty()) {
3363 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003364 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003366
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 F.PreloadSLocEntries.swap(Record);
3368 break;
3369 }
3370
3371 case EXT_VECTOR_DECLS:
3372 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3373 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3374 break;
3375
3376 case VTABLE_USES:
3377 if (Record.size() % 3 != 0) {
3378 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003379 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003381
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 // Later tables overwrite earlier ones.
3383 // FIXME: Modules will have some trouble with this. This is clearly not
3384 // the right way to do this.
3385 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3388 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3389 VTableUses.push_back(
3390 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3391 VTableUses.push_back(Record[Idx++]);
3392 }
3393 break;
3394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 case PENDING_IMPLICIT_INSTANTIATIONS:
3396 if (PendingInstantiations.size() % 2 != 0) {
3397 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003398 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 }
3400
3401 if (Record.size() % 2 != 0) {
3402 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003403 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 }
3405
3406 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3407 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3408 PendingInstantiations.push_back(
3409 ReadSourceLocation(F, Record, I).getRawEncoding());
3410 }
3411 break;
3412
3413 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003414 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003415 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003416 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003417 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3419 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3420 break;
3421
3422 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003423 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3424 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3425 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003426
3427 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003428
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 unsigned StartingID;
3430 if (!PP.getPreprocessingRecord())
3431 PP.createPreprocessingRecord();
3432 if (!PP.getPreprocessingRecord()->getExternalSource())
3433 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003434 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003436 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 F.BasePreprocessedEntityID = StartingID;
3438
3439 if (F.NumPreprocessedEntities > 0) {
3440 // Introduce the global -> local mapping for preprocessed entities in
3441 // this module.
3442 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003443
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 // Introduce the local -> global mapping for preprocessed entities in
3445 // this module.
3446 F.PreprocessedEntityRemap.insertOrReplace(
3447 std::make_pair(LocalBasePreprocessedEntityID,
3448 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3449 }
3450
3451 break;
3452 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003453
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003454 case PPD_SKIPPED_RANGES: {
3455 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3456 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3457 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3458
3459 if (!PP.getPreprocessingRecord())
3460 PP.createPreprocessingRecord();
3461 if (!PP.getPreprocessingRecord()->getExternalSource())
3462 PP.getPreprocessingRecord()->SetExternalSource(*this);
3463 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3464 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003465
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003466 if (F.NumPreprocessedSkippedRanges > 0)
3467 GlobalSkippedRangeMap.insert(
3468 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3469 break;
3470 }
3471
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003472 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 if (Record.size() % 2 != 0) {
3474 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003475 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003477 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3478 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3479 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3480
3481 // If we've already loaded the decl, perform the updates when we finish
3482 // loading this block.
3483 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003484 PendingUpdateRecords.push_back(
3485 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003488
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003489 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 if (F.LocalNumObjCCategoriesInMap != 0) {
3491 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003494
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003496 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003498
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 case OBJC_CATEGORIES:
3500 F.ObjCCategories.swap(Record);
3501 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 case CUDA_SPECIAL_DECL_REFS:
3504 // Later tables overwrite earlier ones.
3505 // FIXME: Modules will have trouble with this.
3506 CUDASpecialDeclRefs.clear();
3507 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3508 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3509 break;
3510
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003511 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003512 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 if (Record[0]) {
3515 F.HeaderFileInfoTable
3516 = HeaderFileInfoLookupTable::Create(
3517 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3518 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003519 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003521 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003522
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 PP.getHeaderSearchInfo().SetExternalSource(this);
3524 if (!PP.getHeaderSearchInfo().getExternalLookup())
3525 PP.getHeaderSearchInfo().SetExternalLookup(this);
3526 }
3527 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003528
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 case FP_PRAGMA_OPTIONS:
3530 // Later tables overwrite earlier ones.
3531 FPPragmaOptions.swap(Record);
3532 break;
3533
3534 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003535 for (unsigned I = 0, E = Record.size(); I != E; ) {
3536 auto Name = ReadString(Record, I);
3537 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003538 Opt.Supported = Record[I++] != 0;
3539 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003540 Opt.Avail = Record[I++];
3541 Opt.Core = Record[I++];
3542 }
3543 break;
3544
3545 case OPENCL_EXTENSION_TYPES:
3546 for (unsigned I = 0, E = Record.size(); I != E;) {
3547 auto TypeID = static_cast<::TypeID>(Record[I++]);
3548 auto *Type = GetType(TypeID).getTypePtr();
3549 auto NumExt = static_cast<unsigned>(Record[I++]);
3550 for (unsigned II = 0; II != NumExt; ++II) {
3551 auto Ext = ReadString(Record, I);
3552 OpenCLTypeExtMap[Type].insert(Ext);
3553 }
3554 }
3555 break;
3556
3557 case OPENCL_EXTENSION_DECLS:
3558 for (unsigned I = 0, E = Record.size(); I != E;) {
3559 auto DeclID = static_cast<::DeclID>(Record[I++]);
3560 auto *Decl = GetDecl(DeclID);
3561 auto NumExt = static_cast<unsigned>(Record[I++]);
3562 for (unsigned II = 0; II != NumExt; ++II) {
3563 auto Ext = ReadString(Record, I);
3564 OpenCLDeclExtMap[Decl].insert(Ext);
3565 }
3566 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003567 break;
3568
3569 case TENTATIVE_DEFINITIONS:
3570 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3571 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3572 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003573
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 case KNOWN_NAMESPACES:
3575 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3576 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3577 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003578
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003579 case UNDEFINED_BUT_USED:
3580 if (UndefinedButUsed.size() % 2 != 0) {
3581 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003582 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003583 }
3584
3585 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003586 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003587 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003588 }
3589 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003590 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3591 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003592 ReadSourceLocation(F, Record, I).getRawEncoding());
3593 }
3594 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003595
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003596 case DELETE_EXPRS_TO_ANALYZE:
3597 for (unsigned I = 0, N = Record.size(); I != N;) {
3598 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3599 const uint64_t Count = Record[I++];
3600 DelayedDeleteExprs.push_back(Count);
3601 for (uint64_t C = 0; C < Count; ++C) {
3602 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3603 bool IsArrayForm = Record[I++] == 1;
3604 DelayedDeleteExprs.push_back(IsArrayForm);
3605 }
3606 }
3607 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003608
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003609 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003610 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 // If we aren't loading a module (which has its own exports), make
3612 // all of the imported modules visible.
3613 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003614 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3615 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3616 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003617 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003618 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003619 if (DeserializationListener)
3620 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 }
3623 }
3624 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003625
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 case MACRO_OFFSET: {
3627 if (F.LocalNumMacros != 0) {
3628 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003629 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003631 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 F.LocalNumMacros = Record[0];
3633 unsigned LocalBaseMacroID = Record[1];
3634 F.BaseMacroID = getTotalNumMacros();
3635
3636 if (F.LocalNumMacros > 0) {
3637 // Introduce the global -> local mapping for macros within this module.
3638 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3639
3640 // Introduce the local -> global mapping for macros within this module.
3641 F.MacroRemap.insertOrReplace(
3642 std::make_pair(LocalBaseMacroID,
3643 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003644
3645 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 }
3647 break;
3648 }
3649
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003650 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003651 LateParsedTemplates.append(Record.begin(), Record.end());
3652 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003653
3654 case OPTIMIZE_PRAGMA_OPTIONS:
3655 if (Record.size() != 1) {
3656 Error("invalid pragma optimize record");
3657 return Failure;
3658 }
3659 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3660 break;
Nico Weber72889432014-09-06 01:25:55 +00003661
Nico Weber779355f2016-03-02 23:22:00 +00003662 case MSSTRUCT_PRAGMA_OPTIONS:
3663 if (Record.size() != 1) {
3664 Error("invalid pragma ms_struct record");
3665 return Failure;
3666 }
3667 PragmaMSStructState = Record[0];
3668 break;
3669
Nico Weber42932312016-03-03 00:17:35 +00003670 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3671 if (Record.size() != 2) {
3672 Error("invalid pragma ms_struct record");
3673 return Failure;
3674 }
3675 PragmaMSPointersToMembersState = Record[0];
3676 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3677 break;
3678
Nico Weber72889432014-09-06 01:25:55 +00003679 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3680 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3681 UnusedLocalTypedefNameCandidates.push_back(
3682 getGlobalDeclID(F, Record[I]));
3683 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003684
3685 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3686 if (Record.size() != 1) {
3687 Error("invalid cuda pragma options record");
3688 return Failure;
3689 }
3690 ForceCUDAHostDeviceDepth = Record[0];
3691 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003692
3693 case PACK_PRAGMA_OPTIONS: {
3694 if (Record.size() < 3) {
3695 Error("invalid pragma pack record");
3696 return Failure;
3697 }
3698 PragmaPackCurrentValue = Record[0];
3699 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3700 unsigned NumStackEntries = Record[2];
3701 unsigned Idx = 3;
3702 // Reset the stack when importing a new module.
3703 PragmaPackStack.clear();
3704 for (unsigned I = 0; I < NumStackEntries; ++I) {
3705 PragmaPackStackEntry Entry;
3706 Entry.Value = Record[Idx++];
3707 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003708 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003709 PragmaPackStrings.push_back(ReadString(Record, Idx));
3710 Entry.SlotLabel = PragmaPackStrings.back();
3711 PragmaPackStack.push_back(Entry);
3712 }
3713 break;
3714 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 }
3716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003717}
3718
Richard Smith37a93df2017-02-18 00:32:02 +00003719void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3720 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3721
3722 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003723 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003724 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3725 F.ModuleOffsetMap = StringRef();
3726
3727 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3728 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3729 F.SLocRemap.insert(std::make_pair(0U, 0));
3730 F.SLocRemap.insert(std::make_pair(2U, 1));
3731 }
3732
3733 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003734 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003735 RemapBuilder SLocRemap(F.SLocRemap);
3736 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3737 RemapBuilder MacroRemap(F.MacroRemap);
3738 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3739 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3740 RemapBuilder SelectorRemap(F.SelectorRemap);
3741 RemapBuilder DeclRemap(F.DeclRemap);
3742 RemapBuilder TypeRemap(F.TypeRemap);
3743
3744 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003745 // FIXME: Looking up dependency modules by filename is horrible. Let's
3746 // start fixing this with prebuilt and explicit modules and see how it
3747 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003748 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003749 ModuleKind Kind = static_cast<ModuleKind>(
3750 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003751 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3752 StringRef Name = StringRef((const char*)Data, Len);
3753 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003754 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3755 ? ModuleMgr.lookupByModuleName(Name)
3756 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003757 if (!OM) {
3758 std::string Msg =
3759 "SourceLocation remap refers to unknown module, cannot find ";
3760 Msg.append(Name);
3761 Error(Msg);
3762 return;
3763 }
3764
3765 uint32_t SLocOffset =
3766 endian::readNext<uint32_t, little, unaligned>(Data);
3767 uint32_t IdentifierIDOffset =
3768 endian::readNext<uint32_t, little, unaligned>(Data);
3769 uint32_t MacroIDOffset =
3770 endian::readNext<uint32_t, little, unaligned>(Data);
3771 uint32_t PreprocessedEntityIDOffset =
3772 endian::readNext<uint32_t, little, unaligned>(Data);
3773 uint32_t SubmoduleIDOffset =
3774 endian::readNext<uint32_t, little, unaligned>(Data);
3775 uint32_t SelectorIDOffset =
3776 endian::readNext<uint32_t, little, unaligned>(Data);
3777 uint32_t DeclIDOffset =
3778 endian::readNext<uint32_t, little, unaligned>(Data);
3779 uint32_t TypeIndexOffset =
3780 endian::readNext<uint32_t, little, unaligned>(Data);
3781
3782 uint32_t None = std::numeric_limits<uint32_t>::max();
3783
3784 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3785 RemapBuilder &Remap) {
3786 if (Offset != None)
3787 Remap.insert(std::make_pair(Offset,
3788 static_cast<int>(BaseOffset - Offset)));
3789 };
3790 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3791 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3792 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3793 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3794 PreprocessedEntityRemap);
3795 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3796 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3797 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3798 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3799
3800 // Global -> local mappings.
3801 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3802 }
3803}
3804
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003805ASTReader::ASTReadResult
3806ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3807 const ModuleFile *ImportedBy,
3808 unsigned ClientLoadCapabilities) {
3809 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003810 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003811
3812 // Try to resolve ModuleName in the current header search context and
3813 // verify that it is found in the same module map file as we saved. If the
3814 // top-level AST file is a main file, skip this check because there is no
3815 // usable header search context.
3816 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003817 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003818 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003819 // An implicitly-loaded module file should have its module listed in some
3820 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003821 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003822 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3823 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003824 // Don't emit module relocation error if we have -fno-validate-pch
3825 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003826 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003827 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003828 // This module was defined by an imported (explicit) module.
3829 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3830 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003831 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003832 // This module was built with a different module map.
3833 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003834 << F.ModuleName << F.FileName
3835 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3836 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003837 // In case it was imported by a PCH, there's a chance the user is
3838 // just missing to include the search path to the directory containing
3839 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003840 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003841 Diag(diag::note_imported_by_pch_module_not_found)
3842 << llvm::sys::path::parent_path(F.ModuleMapPath);
3843 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003844 }
3845 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003846 }
3847
Richard Smithe842a472014-10-22 02:05:46 +00003848 assert(M->Name == F.ModuleName && "found module with different name");
3849
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003850 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003851 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3852 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003853 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003854 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3855 "top-level import should be verified");
3856 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003857 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3858 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003859 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3860 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003861 return OutOfDate;
3862 }
3863
3864 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3865 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3866 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003867 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003868 auto F = FileMgr.getFile(Filename, false, false);
3869 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003870 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3871 Error("could not find file '" + Filename +"' referenced by AST file");
3872 return OutOfDate;
3873 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003874 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003875 }
3876
3877 // Check any additional module map files (e.g. module.private.modulemap)
3878 // that are not in the pcm.
3879 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003880 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003881 // Remove files that match
3882 // Note: SmallPtrSet::erase is really remove
3883 if (!AdditionalStoredMaps.erase(ModMap)) {
3884 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3885 Diag(diag::err_module_different_modmap)
3886 << F.ModuleName << /*new*/0 << ModMap->getName();
3887 return OutOfDate;
3888 }
3889 }
3890 }
3891
3892 // Check any additional module map files that are in the pcm, but not
3893 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003894 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003895 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3896 Diag(diag::err_module_different_modmap)
3897 << F.ModuleName << /*not new*/1 << ModMap->getName();
3898 return OutOfDate;
3899 }
3900 }
3901
3902 if (Listener)
3903 Listener->ReadModuleMapFile(F.ModuleMapPath);
3904 return Success;
3905}
3906
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003907/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003908static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3909 // Find the entry for this selector in the method pool.
3910 Sema::GlobalMethodPool::iterator Known
3911 = S.MethodPool.find(Method->getSelector());
3912 if (Known == S.MethodPool.end())
3913 return;
3914
3915 // Retrieve the appropriate method list.
3916 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3917 : Known->second.second;
3918 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003919 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003920 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003921 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003922 Found = true;
3923 } else {
3924 // Keep searching.
3925 continue;
3926 }
3927 }
3928
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003929 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003930 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003931 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003932 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003933 }
3934}
3935
Richard Smithde711422015-04-23 21:20:19 +00003936void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003937 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003938 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003939 bool wasHidden = D->isHidden();
3940 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003941
Vedant Kumar48b4f762018-04-14 01:40:48 +00003942 if (wasHidden && SemaObj) {
3943 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003944 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003945 }
3946 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 }
3948}
3949
Richard Smith49f906a2014-03-01 00:08:04 +00003950void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003951 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003952 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003954 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003955 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003957 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003958
3959 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003960 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // there is nothing more to do.
3962 continue;
3963 }
Richard Smith49f906a2014-03-01 00:08:04 +00003964
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 if (!Mod->isAvailable()) {
3966 // Modules that aren't available cannot be made visible.
3967 continue;
3968 }
3969
3970 // Update the module's name visibility.
3971 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003972
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 // If we've already deserialized any names from this module,
3974 // mark them as visible.
3975 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3976 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003977 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003979 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003980 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3981 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003983
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003985 SmallVector<Module *, 16> Exports;
3986 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003987 for (SmallVectorImpl<Module *>::iterator
3988 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3989 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003990 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003991 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003992 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 }
3994}
3995
Richard Smith6561f922016-09-12 21:06:40 +00003996/// We've merged the definition \p MergedDef into the existing definition
3997/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3998/// visible.
3999void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4000 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004001 if (Def->isHidden()) {
4002 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004003 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004004 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004005 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004006 getContext().mergeDefinitionIntoModule(
4007 Def, MergedDef->getImportedOwningModule(),
4008 /*NotifyListeners*/ false);
4009 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004010 }
Richard Smith6561f922016-09-12 21:06:40 +00004011 }
4012}
4013
Douglas Gregore060e572013-01-25 01:03:03 +00004014bool ASTReader::loadGlobalIndex() {
4015 if (GlobalIndex)
4016 return false;
4017
4018 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004019 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004020 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004021
Douglas Gregore060e572013-01-25 01:03:03 +00004022 // Try to load the global index.
4023 TriedLoadingGlobalIndex = true;
4024 StringRef ModuleCachePath
4025 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004026 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4027 GlobalModuleIndex::readIndex(ModuleCachePath);
4028 if (llvm::Error Err = std::move(Result.second)) {
4029 assert(!Result.first);
4030 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004031 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004032 }
Douglas Gregore060e572013-01-25 01:03:03 +00004033
4034 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004035 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004036 return false;
4037}
4038
4039bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004040 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004041 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4042}
4043
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004044static void updateModuleTimestamp(ModuleFile &MF) {
4045 // Overwrite the timestamp file contents so that file's mtime changes.
4046 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004047 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004048 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004049 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004050 return;
4051 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004052 OS.close();
4053 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004054}
4055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004056/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004057/// cursor into the start of the given block ID, returning false on success and
4058/// true on failure.
4059static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004060 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004061 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4062 if (!MaybeEntry) {
4063 // FIXME this drops errors on the floor.
4064 consumeError(MaybeEntry.takeError());
4065 return true;
4066 }
4067 llvm::BitstreamEntry Entry = MaybeEntry.get();
4068
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004069 switch (Entry.Kind) {
4070 case llvm::BitstreamEntry::Error:
4071 case llvm::BitstreamEntry::EndBlock:
4072 return true;
4073
4074 case llvm::BitstreamEntry::Record:
4075 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004076 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4077 break;
4078 else {
4079 // FIXME this drops errors on the floor.
4080 consumeError(Skipped.takeError());
4081 return true;
4082 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004083
4084 case llvm::BitstreamEntry::SubBlock:
4085 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004086 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4087 // FIXME this drops the error on the floor.
4088 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004089 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004090 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004091 // Found it!
4092 return false;
4093 }
4094
JF Bastien0e828952019-06-26 19:50:12 +00004095 if (llvm::Error Err = Cursor.SkipBlock()) {
4096 // FIXME this drops the error on the floor.
4097 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004098 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004099 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004100 }
4101 }
4102}
4103
Benjamin Kramer0772c422016-02-13 13:42:54 +00004104ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 ModuleKind Type,
4106 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004107 unsigned ClientLoadCapabilities,
4108 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004109 llvm::SaveAndRestore<SourceLocation>
4110 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4111
Richard Smithd1c46742014-04-30 02:24:17 +00004112 // Defer any pending actions until we get to the end of reading the AST file.
4113 Deserializing AnASTFile(this);
4114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004116 unsigned PreviousGeneration = 0;
4117 if (ContextObj)
4118 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004119
4120 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004121 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004122 switch (ASTReadResult ReadResult =
4123 ReadASTCore(FileName, Type, ImportLoc,
4124 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4125 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00004127 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 case OutOfDate:
4129 case VersionMismatch:
4130 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00004131 case HadErrors: {
4132 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004133 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00004134 LoadedSet.insert(IM.Mod);
4135
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004136 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004137 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004138 ? &PP.getHeaderSearchInfo().getModuleMap()
4139 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004140
4141 // If we find that any modules are unusable, the global index is going
4142 // to be out-of-date. Just remove it.
4143 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004144 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00004146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 case Success:
4148 break;
4149 }
4150
4151 // Here comes stuff that we only do once the entire chain is loaded.
4152
4153 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004154 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4155 MEnd = Loaded.end();
4156 M != MEnd; ++M) {
4157 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004158
4159 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004160 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4161 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004162
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004163 // Read the extension blocks.
4164 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4165 if (ASTReadResult Result = ReadExtensionBlock(F))
4166 return Result;
4167 }
4168
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004169 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 // bits of all files we've seen.
4171 F.GlobalBitOffset = TotalModulesSizeInBits;
4172 TotalModulesSizeInBits += F.SizeInBits;
4173 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004174
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004176 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4177 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 // Load it through the SourceManager and don't call ReadSLocEntry()
4179 // directly because the entry may have already been loaded in which case
4180 // calling ReadSLocEntry() directly would trigger an assertion in
4181 // SourceManager.
4182 SourceMgr.getLoadedSLocEntryByID(Index);
4183 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004184
Richard Smithea741482017-05-01 22:10:47 +00004185 // Map the original source file ID into the ID space of the current
4186 // compilation.
4187 if (F.OriginalSourceFileID.isValid()) {
4188 F.OriginalSourceFileID = FileID::get(
4189 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4190 }
4191
Richard Smith33e0f7e2015-07-22 02:08:40 +00004192 // Preload all the pending interesting identifiers by marking them out of
4193 // date.
4194 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004195 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004196 F.IdentifierTableData + Offset);
4197
4198 ASTIdentifierLookupTrait Trait(*this, F);
4199 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4200 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004201 auto &II = PP.getIdentifierTable().getOwn(Key);
4202 II.setOutOfDate(true);
4203
4204 // Mark this identifier as being from an AST file so that we can track
4205 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004206 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004207
4208 // Associate the ID with the identifier so that the writer can reuse it.
4209 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4210 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 }
4213
Douglas Gregor603cd862013-03-22 18:50:14 +00004214 // Setup the import locations and notify the module manager that we've
4215 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004216 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4217 MEnd = Loaded.end();
4218 M != MEnd; ++M) {
4219 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004220
4221 ModuleMgr.moduleFileAccepted(&F);
4222
4223 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004224 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004225 // FIXME: We assume that locations from PCH / preamble do not need
4226 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004227 if (!M->ImportedBy)
4228 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00004230 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 }
4232
Richard Smithdbafb6c2017-06-29 23:23:46 +00004233 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004234 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4235 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004236 // Mark all of the identifiers in the identifier table as being out of date,
4237 // so that various accessors know to check the loaded modules when the
4238 // identifier is used.
4239 //
4240 // For C++ modules, we don't need information on many identifiers (just
4241 // those that provide macros or are poisoned), so we mark all of
4242 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004243 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4244 IdEnd = PP.getIdentifierTable().end();
4245 Id != IdEnd; ++Id)
4246 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004247 }
Manman Rena0f31a02016-04-29 19:04:05 +00004248 // Mark selectors as out of date.
4249 for (auto Sel : SelectorGeneration)
4250 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004251
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004253 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4254 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4256 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004257
4258 switch (Unresolved.Kind) {
4259 case UnresolvedModuleRef::Conflict:
4260 if (ResolvedMod) {
4261 Module::Conflict Conflict;
4262 Conflict.Other = ResolvedMod;
4263 Conflict.Message = Unresolved.String.str();
4264 Unresolved.Mod->Conflicts.push_back(Conflict);
4265 }
4266 continue;
4267
4268 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004270 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272
Douglas Gregorfb912652013-03-20 21:10:35 +00004273 case UnresolvedModuleRef::Export:
4274 if (ResolvedMod || Unresolved.IsWildcard)
4275 Unresolved.Mod->Exports.push_back(
4276 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4277 continue;
4278 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004280 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004281
Graydon Hoaree7196af2016-12-09 21:45:49 +00004282 if (Imported)
4283 Imported->append(ImportedModules.begin(),
4284 ImportedModules.end());
4285
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004286 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4287 // Might be unnecessary as use declarations are only used to build the
4288 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004289
Richard Smithdbafb6c2017-06-29 23:23:46 +00004290 if (ContextObj)
4291 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004292
Richard Smith3d8e97e2013-10-18 06:54:39 +00004293 if (SemaObj)
4294 UpdateSema();
4295
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 if (DeserializationListener)
4297 DeserializationListener->ReaderInitialized(this);
4298
4299 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004300 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 // If this AST file is a precompiled preamble, then set the
4302 // preamble file ID of the source manager to the file source file
4303 // from which the preamble was built.
4304 if (Type == MK_Preamble) {
4305 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4306 } else if (Type == MK_MainFile) {
4307 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4308 }
4309 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004310
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 // For any Objective-C class definitions we have already loaded, make sure
4312 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004313 if (ContextObj) {
4314 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4315 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4316 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004317 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004318 }
4319 }
Douglas Gregore060e572013-01-25 01:03:03 +00004320
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004321 if (PP.getHeaderSearchInfo()
4322 .getHeaderSearchOpts()
4323 .ModulesValidateOncePerBuildSession) {
4324 // Now we are certain that the module and all modules it depends on are
4325 // up to date. Create or update timestamp files for modules that are
4326 // located in the module cache (not for PCH files that could be anywhere
4327 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004328 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4329 ImportedModule &M = Loaded[I];
4330 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004331 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004332 }
4333 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004334 }
4335
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 return Success;
4337}
4338
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004339static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004340
JF Bastien0e828952019-06-26 19:50:12 +00004341/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4342static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4343 // FIXME checking magic headers is done in other places such as
4344 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4345 // always done the same. Unify it all with a helper.
4346 if (!Stream.canSkipToPos(4))
4347 return llvm::createStringError(std::errc::illegal_byte_sequence,
4348 "file too small to contain AST file magic");
4349 for (unsigned C : {'C', 'P', 'C', 'H'})
4350 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4351 if (Res.get() != C)
4352 return llvm::createStringError(
4353 std::errc::illegal_byte_sequence,
4354 "file doesn't start with AST file magic");
4355 } else
4356 return Res.takeError();
4357 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004358}
4359
Richard Smith0f99d6a2015-08-09 08:48:41 +00004360static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4361 switch (Kind) {
4362 case MK_PCH:
4363 return 0; // PCH
4364 case MK_ImplicitModule:
4365 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004366 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004367 return 1; // module
4368 case MK_MainFile:
4369 case MK_Preamble:
4370 return 2; // main source file
4371 }
4372 llvm_unreachable("unknown module kind");
4373}
4374
Guy Benyei11169dd2012-12-18 14:30:41 +00004375ASTReader::ASTReadResult
4376ASTReader::ReadASTCore(StringRef FileName,
4377 ModuleKind Type,
4378 SourceLocation ImportLoc,
4379 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004380 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004381 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004382 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 unsigned ClientLoadCapabilities) {
4384 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004386 ModuleManager::AddModuleResult AddResult
4387 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004388 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004389 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004390 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004391
Douglas Gregor7029ce12013-03-19 00:28:20 +00004392 switch (AddResult) {
4393 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004394 Diag(diag::remark_module_import)
4395 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4396 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004397 return Success;
4398
4399 case ModuleManager::NewlyLoaded:
4400 // Load module file below.
4401 break;
4402
4403 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004404 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004405 // it.
4406 if (ClientLoadCapabilities & ARR_Missing)
4407 return Missing;
4408
4409 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004410 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004411 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004412 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004413 return Failure;
4414
4415 case ModuleManager::OutOfDate:
4416 // We couldn't load the module file because it is out-of-date. If the
4417 // client can handle out-of-date, return it.
4418 if (ClientLoadCapabilities & ARR_OutOfDate)
4419 return OutOfDate;
4420
4421 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004422 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004423 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004424 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 return Failure;
4426 }
4427
Douglas Gregor7029ce12013-03-19 00:28:20 +00004428 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004429
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004430 bool ShouldFinalizePCM = false;
4431 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4432 auto &MC = getModuleManager().getModuleCache();
4433 if (ShouldFinalizePCM)
4434 MC.finalizePCM(FileName);
4435 else
4436 MC.tryToDropPCM(FileName);
4437 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004439 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004440 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004441 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004444 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4445 Diag(diag::err_module_file_invalid)
4446 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 return Failure;
4448 }
4449
4450 // This is used for compatibility with older PCH formats.
4451 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004452 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004453 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4454 if (!MaybeEntry) {
4455 Error(MaybeEntry.takeError());
4456 return Failure;
4457 }
4458 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004459
Chris Lattnerefa77172013-01-20 00:00:22 +00004460 switch (Entry.Kind) {
4461 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004462 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004463 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 Error("invalid record at top-level of AST file");
4465 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004466
Chris Lattnerefa77172013-01-20 00:00:22 +00004467 case llvm::BitstreamEntry::SubBlock:
4468 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 }
4470
Chris Lattnerefa77172013-01-20 00:00:22 +00004471 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 case CONTROL_BLOCK_ID:
4473 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004474 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004476 // Check that we didn't try to load a non-module AST file as a module.
4477 //
4478 // FIXME: Should we also perform the converse check? Loading a module as
4479 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004480 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4481 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004482 F.ModuleName.empty()) {
4483 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4484 if (Result != OutOfDate ||
4485 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4486 Diag(diag::err_module_file_not_module) << FileName;
4487 return Result;
4488 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 break;
4490
4491 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004492 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 case OutOfDate: return OutOfDate;
4494 case VersionMismatch: return VersionMismatch;
4495 case ConfigurationMismatch: return ConfigurationMismatch;
4496 case HadErrors: return HadErrors;
4497 }
4498 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004499
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 case AST_BLOCK_ID:
4501 if (!HaveReadControlBlock) {
4502 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004503 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 return VersionMismatch;
4505 }
4506
4507 // Record that we've loaded this module.
4508 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004509 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 return Success;
4511
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004512 case UNHASHED_CONTROL_BLOCK_ID:
4513 // This block is handled using look-ahead during ReadControlBlock. We
4514 // shouldn't get here!
4515 Error("malformed block record in AST file");
4516 return Failure;
4517
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 default:
JF Bastien0e828952019-06-26 19:50:12 +00004519 if (llvm::Error Err = Stream.SkipBlock()) {
4520 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 return Failure;
4522 }
4523 break;
4524 }
4525 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004526
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004527 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004528}
4529
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004530ASTReader::ASTReadResult
4531ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4532 unsigned ClientLoadCapabilities) {
4533 const HeaderSearchOptions &HSOpts =
4534 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4535 bool AllowCompatibleConfigurationMismatch =
4536 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4537
4538 ASTReadResult Result = readUnhashedControlBlockImpl(
4539 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4540 Listener.get(),
4541 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4542
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004543 // If F was directly imported by another module, it's implicitly validated by
4544 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004545 if (DisableValidation || WasImportedBy ||
4546 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4547 return Success;
4548
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004549 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004550 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004551 return Failure;
4552 }
4553
4554 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004555 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004556 // with it; we can only load a single version of each module.
4557 //
4558 // This can happen when a module is imported in two contexts: in one, as a
4559 // user module; in another, as a system module (due to an import from
4560 // another module marked with the [system] flag). It usually indicates a
4561 // bug in the module map: this module should also be marked with [system].
4562 //
4563 // If -Wno-system-headers (the default), and the first import is as a
4564 // system module, then validation will fail during the as-user import,
4565 // since -Werror flags won't have been validated. However, it's reasonable
4566 // to treat this consistently as a system module.
4567 //
4568 // If -Wsystem-headers, the PCM on disk was built with
4569 // -Wno-system-headers, and the first import is as a user module, then
4570 // validation will fail during the as-system import since the PCM on disk
4571 // doesn't guarantee that -Werror was respected. However, the -Werror
4572 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004573 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004574 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4575 return Success;
4576 }
4577 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004578
4579 return Result;
4580}
4581
4582ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4583 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4584 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4585 bool ValidateDiagnosticOptions) {
4586 // Initialize a stream.
4587 BitstreamCursor Stream(StreamData);
4588
4589 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004590 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4591 // FIXME this drops the error on the floor.
4592 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004593 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004594 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004595
4596 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4597 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4598 return Failure;
4599
4600 // Read all of the records in the options block.
4601 RecordData Record;
4602 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004603 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004604 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4605 if (!MaybeEntry) {
4606 // FIXME this drops the error on the floor.
4607 consumeError(MaybeEntry.takeError());
4608 return Failure;
4609 }
4610 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004611
4612 switch (Entry.Kind) {
4613 case llvm::BitstreamEntry::Error:
4614 case llvm::BitstreamEntry::SubBlock:
4615 return Failure;
4616
4617 case llvm::BitstreamEntry::EndBlock:
4618 return Result;
4619
4620 case llvm::BitstreamEntry::Record:
4621 // The interesting case.
4622 break;
4623 }
4624
4625 // Read and process a record.
4626 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004627 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4628 if (!MaybeRecordType) {
4629 // FIXME this drops the error.
4630 return Failure;
4631 }
4632 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004633 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004634 if (F)
4635 std::copy(Record.begin(), Record.end(), F->Signature.data());
4636 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004637 case DIAGNOSTIC_OPTIONS: {
4638 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4639 if (Listener && ValidateDiagnosticOptions &&
4640 !AllowCompatibleConfigurationMismatch &&
4641 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004642 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004643 break;
4644 }
4645 case DIAG_PRAGMA_MAPPINGS:
4646 if (!F)
4647 break;
4648 if (F->PragmaDiagMappings.empty())
4649 F->PragmaDiagMappings.swap(Record);
4650 else
4651 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4652 Record.begin(), Record.end());
4653 break;
4654 }
4655 }
4656}
4657
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004658/// Parse a record and blob containing module file extension metadata.
4659static bool parseModuleFileExtensionMetadata(
4660 const SmallVectorImpl<uint64_t> &Record,
4661 StringRef Blob,
4662 ModuleFileExtensionMetadata &Metadata) {
4663 if (Record.size() < 4) return true;
4664
4665 Metadata.MajorVersion = Record[0];
4666 Metadata.MinorVersion = Record[1];
4667
4668 unsigned BlockNameLen = Record[2];
4669 unsigned UserInfoLen = Record[3];
4670
4671 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4672
4673 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4674 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4675 Blob.data() + BlockNameLen + UserInfoLen);
4676 return false;
4677}
4678
4679ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4680 BitstreamCursor &Stream = F.Stream;
4681
4682 RecordData Record;
4683 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004684 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4685 if (!MaybeEntry) {
4686 Error(MaybeEntry.takeError());
4687 return Failure;
4688 }
4689 llvm::BitstreamEntry Entry = MaybeEntry.get();
4690
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004691 switch (Entry.Kind) {
4692 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004693 if (llvm::Error Err = Stream.SkipBlock()) {
4694 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004695 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004696 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004697 continue;
4698
4699 case llvm::BitstreamEntry::EndBlock:
4700 return Success;
4701
4702 case llvm::BitstreamEntry::Error:
4703 return HadErrors;
4704
4705 case llvm::BitstreamEntry::Record:
4706 break;
4707 }
4708
4709 Record.clear();
4710 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004711 Expected<unsigned> MaybeRecCode =
4712 Stream.readRecord(Entry.ID, Record, &Blob);
4713 if (!MaybeRecCode) {
4714 Error(MaybeRecCode.takeError());
4715 return Failure;
4716 }
4717 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004718 case EXTENSION_METADATA: {
4719 ModuleFileExtensionMetadata Metadata;
4720 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4721 return Failure;
4722
4723 // Find a module file extension with this block name.
4724 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4725 if (Known == ModuleFileExtensions.end()) break;
4726
4727 // Form a reader.
4728 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4729 F, Stream)) {
4730 F.ExtensionReaders.push_back(std::move(Reader));
4731 }
4732
4733 break;
4734 }
4735 }
4736 }
4737
4738 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004739}
4740
Richard Smitha7e2cc62015-05-01 01:53:09 +00004741void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004742 assert(ContextObj && "no context to initialize");
4743 ASTContext &Context = *ContextObj;
4744
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 // If there's a listener, notify them that we "read" the translation unit.
4746 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004747 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 Context.getTranslationUnitDecl());
4749
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 // FIXME: Find a better way to deal with collisions between these
4751 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004752
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 // Load the special types.
4754 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4755 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4756 if (!Context.CFConstantStringTypeDecl)
4757 Context.setCFConstantStringType(GetType(String));
4758 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004759
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4761 QualType FileType = GetType(File);
4762 if (FileType.isNull()) {
4763 Error("FILE type is NULL");
4764 return;
4765 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004766
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004768 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 Context.setFILEDecl(Typedef->getDecl());
4770 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004771 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 if (!Tag) {
4773 Error("Invalid FILE type in AST file");
4774 return;
4775 }
4776 Context.setFILEDecl(Tag->getDecl());
4777 }
4778 }
4779 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004780
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4782 QualType Jmp_bufType = GetType(Jmp_buf);
4783 if (Jmp_bufType.isNull()) {
4784 Error("jmp_buf type is NULL");
4785 return;
4786 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004787
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004789 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 Context.setjmp_bufDecl(Typedef->getDecl());
4791 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004792 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 if (!Tag) {
4794 Error("Invalid jmp_buf type in AST file");
4795 return;
4796 }
4797 Context.setjmp_bufDecl(Tag->getDecl());
4798 }
4799 }
4800 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004801
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4803 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4804 if (Sigjmp_bufType.isNull()) {
4805 Error("sigjmp_buf type is NULL");
4806 return;
4807 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004808
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004810 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 Context.setsigjmp_bufDecl(Typedef->getDecl());
4812 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004813 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 assert(Tag && "Invalid sigjmp_buf type in AST file");
4815 Context.setsigjmp_bufDecl(Tag->getDecl());
4816 }
4817 }
4818 }
4819
4820 if (unsigned ObjCIdRedef
4821 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4822 if (Context.ObjCIdRedefinitionType.isNull())
4823 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4824 }
4825
4826 if (unsigned ObjCClassRedef
4827 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4828 if (Context.ObjCClassRedefinitionType.isNull())
4829 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4830 }
4831
4832 if (unsigned ObjCSelRedef
4833 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4834 if (Context.ObjCSelRedefinitionType.isNull())
4835 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4836 }
4837
4838 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4839 QualType Ucontext_tType = GetType(Ucontext_t);
4840 if (Ucontext_tType.isNull()) {
4841 Error("ucontext_t type is NULL");
4842 return;
4843 }
4844
4845 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004846 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 Context.setucontext_tDecl(Typedef->getDecl());
4848 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004849 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 assert(Tag && "Invalid ucontext_t type in AST file");
4851 Context.setucontext_tDecl(Tag->getDecl());
4852 }
4853 }
4854 }
4855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004856
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4858
4859 // If there were any CUDA special declarations, deserialize them.
4860 if (!CUDASpecialDeclRefs.empty()) {
4861 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4862 Context.setcudaConfigureCallDecl(
4863 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4864 }
Richard Smith56be7542014-03-21 00:33:59 +00004865
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004867 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004868 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004869 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004870 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004871 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004872 if (Import.ImportLoc.isValid())
4873 PP.makeModuleVisible(Imported, Import.ImportLoc);
4874 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004875 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 }
4877 ImportedModules.clear();
4878}
4879
4880void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004881 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004882}
4883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004884/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004885/// else returns 0.
4886static ASTFileSignature readASTFileSignature(StringRef PCH) {
4887 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004888 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4889 // FIXME this drops the error on the floor.
4890 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004891 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004892 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004893
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004894 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4895 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004896 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004897
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004898 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004899 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004900 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004901 Expected<llvm::BitstreamEntry> MaybeEntry =
4902 Stream.advanceSkippingSubblocks();
4903 if (!MaybeEntry) {
4904 // FIXME this drops the error on the floor.
4905 consumeError(MaybeEntry.takeError());
4906 return ASTFileSignature();
4907 }
4908 llvm::BitstreamEntry Entry = MaybeEntry.get();
4909
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004910 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004911 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004912
4913 Record.clear();
4914 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004915 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4916 if (!MaybeRecord) {
4917 // FIXME this drops the error on the floor.
4918 consumeError(MaybeRecord.takeError());
4919 return ASTFileSignature();
4920 }
4921 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004922 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4923 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004924 }
4925}
4926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004927/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004928/// directly from the AST file, without actually loading the AST
4929/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004930std::string ASTReader::getOriginalSourceFile(
4931 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004932 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004934 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004936 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4937 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004938 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 }
4940
4941 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004942 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004943
4944 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004945 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4946 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004947 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004949
Chris Lattnere7b154b2013-01-19 21:39:22 +00004950 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004951 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004952 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004953 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004954 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004955
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004956 // Scan for ORIGINAL_FILE inside the control block.
4957 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004958 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004959 Expected<llvm::BitstreamEntry> MaybeEntry =
4960 Stream.advanceSkippingSubblocks();
4961 if (!MaybeEntry) {
4962 // FIXME this drops errors on the floor.
4963 consumeError(MaybeEntry.takeError());
4964 return std::string();
4965 }
4966 llvm::BitstreamEntry Entry = MaybeEntry.get();
4967
Chris Lattnere7b154b2013-01-19 21:39:22 +00004968 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004969 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004970
Chris Lattnere7b154b2013-01-19 21:39:22 +00004971 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4972 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004973 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004975
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004977 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004978 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4979 if (!MaybeRecord) {
4980 // FIXME this drops the errors on the floor.
4981 consumeError(MaybeRecord.takeError());
4982 return std::string();
4983 }
4984 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00004985 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004987}
4988
4989namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004990
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 class SimplePCHValidator : public ASTReaderListener {
4992 const LangOptions &ExistingLangOpts;
4993 const TargetOptions &ExistingTargetOpts;
4994 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004995 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004997
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 public:
4999 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5000 const TargetOptions &ExistingTargetOpts,
5001 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005002 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 FileManager &FileMgr)
5004 : ExistingLangOpts(ExistingLangOpts),
5005 ExistingTargetOpts(ExistingTargetOpts),
5006 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005007 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005008 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005009
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005010 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5011 bool AllowCompatibleDifferences) override {
5012 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5013 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005015
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005016 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5017 bool AllowCompatibleDifferences) override {
5018 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5019 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005021
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005022 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5023 StringRef SpecificModuleCachePath,
5024 bool Complain) override {
5025 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5026 ExistingModuleCachePath,
5027 nullptr, ExistingLangOpts);
5028 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005029
Craig Topper3e89dfe2014-03-13 02:13:41 +00005030 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5031 bool Complain,
5032 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005033 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005034 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 }
5036 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005037
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005038} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005039
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005040bool ASTReader::readASTFileControlBlock(
5041 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005042 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005043 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005044 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005046 // FIXME: This allows use of the VFS; we do not allow use of the
5047 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005048 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 if (!Buffer) {
5050 return true;
5051 }
5052
5053 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005054 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5055 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005056
5057 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005058 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5059 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005061 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005062
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005063 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005064 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005065 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005066
5067 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005068 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005069 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005070 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005071
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005073 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005074 bool DoneWithControlBlock = false;
5075 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005076 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5077 if (!MaybeEntry) {
5078 // FIXME this drops the error on the floor.
5079 consumeError(MaybeEntry.takeError());
5080 return true;
5081 }
5082 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005083
5084 switch (Entry.Kind) {
5085 case llvm::BitstreamEntry::SubBlock: {
5086 switch (Entry.ID) {
5087 case OPTIONS_BLOCK_ID: {
5088 std::string IgnoredSuggestedPredefines;
5089 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5090 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005091 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005092 return true;
5093 break;
5094 }
5095
5096 case INPUT_FILES_BLOCK_ID:
5097 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005098 if (llvm::Error Err = Stream.SkipBlock()) {
5099 // FIXME this drops the error on the floor.
5100 consumeError(std::move(Err));
5101 return true;
5102 }
5103 if (NeedsInputFiles &&
5104 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005105 return true;
5106 break;
5107
5108 default:
JF Bastien0e828952019-06-26 19:50:12 +00005109 if (llvm::Error Err = Stream.SkipBlock()) {
5110 // FIXME this drops the error on the floor.
5111 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005112 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005113 }
Richard Smith0516b182015-09-08 19:40:14 +00005114 break;
5115 }
5116
5117 continue;
5118 }
5119
5120 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005121 DoneWithControlBlock = true;
5122 break;
Richard Smith0516b182015-09-08 19:40:14 +00005123
5124 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005125 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005126
5127 case llvm::BitstreamEntry::Record:
5128 break;
5129 }
5130
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005131 if (DoneWithControlBlock) break;
5132
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005134 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005135 Expected<unsigned> MaybeRecCode =
5136 Stream.readRecord(Entry.ID, Record, &Blob);
5137 if (!MaybeRecCode) {
5138 // FIXME this drops the error.
5139 return Failure;
5140 }
5141 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005142 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005143 if (Record[0] != VERSION_MAJOR)
5144 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005145 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005146 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005147 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005148 case MODULE_NAME:
5149 Listener.ReadModuleName(Blob);
5150 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005151 case MODULE_DIRECTORY:
5152 ModuleDir = Blob;
5153 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005154 case MODULE_MAP_FILE: {
5155 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005156 auto Path = ReadString(Record, Idx);
5157 ResolveImportedPath(Path, ModuleDir);
5158 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005159 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005160 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005161 case INPUT_FILE_OFFSETS: {
5162 if (!NeedsInputFiles)
5163 break;
5164
5165 unsigned NumInputFiles = Record[0];
5166 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005167 const llvm::support::unaligned_uint64_t *InputFileOffs =
5168 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005169 for (unsigned I = 0; I != NumInputFiles; ++I) {
5170 // Go find this input file.
5171 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005172
5173 if (isSystemFile && !NeedsSystemInputFiles)
5174 break; // the rest are system input files
5175
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005176 BitstreamCursor &Cursor = InputFilesCursor;
5177 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005178 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5179 // FIXME this drops errors on the floor.
5180 consumeError(std::move(Err));
5181 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005182
JF Bastien0e828952019-06-26 19:50:12 +00005183 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5184 if (!MaybeCode) {
5185 // FIXME this drops errors on the floor.
5186 consumeError(MaybeCode.takeError());
5187 }
5188 unsigned Code = MaybeCode.get();
5189
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005190 RecordData Record;
5191 StringRef Blob;
5192 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005193 Expected<unsigned> MaybeRecordType =
5194 Cursor.readRecord(Code, Record, &Blob);
5195 if (!MaybeRecordType) {
5196 // FIXME this drops errors on the floor.
5197 consumeError(MaybeRecordType.takeError());
5198 }
5199 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005200 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005201 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005202 std::string Filename = Blob;
5203 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005204 shouldContinue = Listener.visitInputFile(
5205 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005206 break;
5207 }
5208 if (!shouldContinue)
5209 break;
5210 }
5211 break;
5212 }
5213
Richard Smithd4b230b2014-10-27 23:01:16 +00005214 case IMPORTS: {
5215 if (!NeedsImports)
5216 break;
5217
5218 unsigned Idx = 0, N = Record.size();
5219 while (Idx < N) {
5220 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005221 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5222 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005223 std::string Filename = ReadString(Record, Idx);
5224 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005225 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005226 }
5227 break;
5228 }
5229
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005230 default:
5231 // No other validation to perform.
5232 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 }
5234 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005235
5236 // Look for module file extension blocks, if requested.
5237 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005238 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005239 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5240 bool DoneWithExtensionBlock = false;
5241 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005242 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5243 if (!MaybeEntry) {
5244 // FIXME this drops the error.
5245 return true;
5246 }
5247 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005248
JF Bastien0e828952019-06-26 19:50:12 +00005249 switch (Entry.Kind) {
5250 case llvm::BitstreamEntry::SubBlock:
5251 if (llvm::Error Err = Stream.SkipBlock()) {
5252 // FIXME this drops the error on the floor.
5253 consumeError(std::move(Err));
5254 return true;
5255 }
5256 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005257
JF Bastien0e828952019-06-26 19:50:12 +00005258 case llvm::BitstreamEntry::EndBlock:
5259 DoneWithExtensionBlock = true;
5260 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005261
JF Bastien0e828952019-06-26 19:50:12 +00005262 case llvm::BitstreamEntry::Error:
5263 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005264
JF Bastien0e828952019-06-26 19:50:12 +00005265 case llvm::BitstreamEntry::Record:
5266 break;
5267 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005268
5269 Record.clear();
5270 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005271 Expected<unsigned> MaybeRecCode =
5272 Stream.readRecord(Entry.ID, Record, &Blob);
5273 if (!MaybeRecCode) {
5274 // FIXME this drops the error.
5275 return true;
5276 }
5277 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005278 case EXTENSION_METADATA: {
5279 ModuleFileExtensionMetadata Metadata;
5280 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5281 return true;
5282
5283 Listener.readModuleFileExtension(Metadata);
5284 break;
5285 }
5286 }
5287 }
5288 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005289 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005290 }
5291
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005292 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5293 if (readUnhashedControlBlockImpl(
5294 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5295 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5296 ValidateDiagnosticOptions) != Success)
5297 return true;
5298
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005299 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005300}
5301
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005302bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5303 const PCHContainerReader &PCHContainerRdr,
5304 const LangOptions &LangOpts,
5305 const TargetOptions &TargetOpts,
5306 const PreprocessorOptions &PPOpts,
5307 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005308 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5309 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005310 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005311 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005312 validator,
5313 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005314}
5315
Ben Langmuir2c9af442014-04-10 17:57:43 +00005316ASTReader::ASTReadResult
5317ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005319 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5320 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005321 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 }
5323
5324 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5325 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005326 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 RecordData Record;
5328 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005329 Expected<llvm::BitstreamEntry> MaybeEntry =
5330 F.Stream.advanceSkippingSubblocks();
5331 if (!MaybeEntry) {
5332 Error(MaybeEntry.takeError());
5333 return Failure;
5334 }
5335 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005336
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005337 switch (Entry.Kind) {
5338 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5339 case llvm::BitstreamEntry::Error:
5340 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005341 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005342 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005343 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005344 case llvm::BitstreamEntry::Record:
5345 // The interesting case.
5346 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005348
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005350 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005352 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5353 if (!MaybeKind) {
5354 Error(MaybeKind.takeError());
5355 return Failure;
5356 }
5357 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005358
5359 if ((Kind == SUBMODULE_METADATA) != First) {
5360 Error("submodule metadata record should be at beginning of block");
5361 return Failure;
5362 }
5363 First = false;
5364
5365 // Submodule information is only valid if we have a current module.
5366 // FIXME: Should we error on these cases?
5367 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5368 Kind != SUBMODULE_DEFINITION)
5369 continue;
5370
5371 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 default: // Default behavior: ignore.
5373 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005374
Richard Smith03478d92014-10-23 22:12:14 +00005375 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005376 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005378 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 }
Richard Smith03478d92014-10-23 22:12:14 +00005380
Chris Lattner0e6c9402013-01-20 02:38:54 +00005381 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005382 unsigned Idx = 0;
5383 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5384 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005385 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005386 bool IsFramework = Record[Idx++];
5387 bool IsExplicit = Record[Idx++];
5388 bool IsSystem = Record[Idx++];
5389 bool IsExternC = Record[Idx++];
5390 bool InferSubmodules = Record[Idx++];
5391 bool InferExplicitSubmodules = Record[Idx++];
5392 bool InferExportWildcard = Record[Idx++];
5393 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005394 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005395
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005396 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005397 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005398 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005399
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 // Retrieve this (sub)module from the module map, creating it if
5401 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005402 CurrentModule =
5403 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5404 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005405
5406 // FIXME: set the definition loc for CurrentModule, or call
5407 // ModMap.setInferredModuleAllowedBy()
5408
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5410 if (GlobalIndex >= SubmodulesLoaded.size() ||
5411 SubmodulesLoaded[GlobalIndex]) {
5412 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005413 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005415
Douglas Gregor7029ce12013-03-19 00:28:20 +00005416 if (!ParentModule) {
5417 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005418 // Don't emit module relocation error if we have -fno-validate-pch
5419 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5420 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005421 if (!Diags.isDiagnosticInFlight()) {
5422 Diag(diag::err_module_file_conflict)
5423 << CurrentModule->getTopLevelModuleName()
5424 << CurFile->getName()
5425 << F.File->getName();
5426 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005427 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005428 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005429 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005430
5431 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005432 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005433 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005434
Richard Smithdd8b5332017-09-04 05:37:53 +00005435 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005436 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 CurrentModule->IsFromModuleFile = true;
5438 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005439 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 CurrentModule->InferSubmodules = InferSubmodules;
5441 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5442 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005443 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005444 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 if (DeserializationListener)
5446 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005447
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005449
Richard Smith8a3e39a2016-03-28 21:31:09 +00005450 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005451 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005452 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005453 CurrentModule->UnresolvedConflicts.clear();
5454 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005455
5456 // The module is available unless it's missing a requirement; relevant
5457 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5458 // Missing headers that were present when the module was built do not
5459 // make it unavailable -- if we got this far, this must be an explicitly
5460 // imported module file.
5461 CurrentModule->Requirements.clear();
5462 CurrentModule->MissingHeaders.clear();
5463 CurrentModule->IsMissingRequirement =
5464 ParentModule && ParentModule->IsMissingRequirement;
5465 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 break;
5467 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005468
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005470 std::string Filename = Blob;
5471 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005472 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005474 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5475 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005476 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5477 Error("mismatched umbrella headers in submodule");
5478 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 }
5480 }
5481 break;
5482 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005483
Richard Smith202210b2014-10-24 20:23:01 +00005484 case SUBMODULE_HEADER:
5485 case SUBMODULE_EXCLUDED_HEADER:
5486 case SUBMODULE_PRIVATE_HEADER:
5487 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005488 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5489 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005490 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005491
Richard Smith202210b2014-10-24 20:23:01 +00005492 case SUBMODULE_TEXTUAL_HEADER:
5493 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5494 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5495 // them here.
5496 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005497
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005498 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005499 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005500 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005501
5502 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005503 std::string Dirname = Blob;
5504 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005505 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005507 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5508 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005509 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5510 Error("mismatched umbrella directories in submodule");
5511 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005512 }
5513 }
5514 break;
5515 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005516
Guy Benyei11169dd2012-12-18 14:30:41 +00005517 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 F.BaseSubmoduleID = getTotalNumSubmodules();
5519 F.LocalNumSubmodules = Record[0];
5520 unsigned LocalBaseSubmoduleID = Record[1];
5521 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005522 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 // module.
5524 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005525
5526 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 // module.
5528 F.SubmoduleRemap.insertOrReplace(
5529 std::make_pair(LocalBaseSubmoduleID,
5530 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005531
Ben Langmuir52ca6782014-10-20 16:27:32 +00005532 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 break;
5535 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005536
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005537 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005539 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 Unresolved.File = &F;
5541 Unresolved.Mod = CurrentModule;
5542 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005543 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005545 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 }
5547 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005548
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005549 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005551 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005552 Unresolved.File = &F;
5553 Unresolved.Mod = CurrentModule;
5554 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005555 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005556 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005557 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005559
5560 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005561 // the parsed, unresolved exports around.
5562 CurrentModule->UnresolvedExports.clear();
5563 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005564
5565 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005566 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5567 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005568 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005569
5570 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005571 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005572 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005573 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005574 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005575
5576 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005577 CurrentModule->ConfigMacros.push_back(Blob.str());
5578 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005579
5580 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005581 UnresolvedModuleRef Unresolved;
5582 Unresolved.File = &F;
5583 Unresolved.Mod = CurrentModule;
5584 Unresolved.ID = Record[0];
5585 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5586 Unresolved.IsWildcard = false;
5587 Unresolved.String = Blob;
5588 UnresolvedModuleRefs.push_back(Unresolved);
5589 break;
5590 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005591
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005592 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005593 if (!ContextObj)
5594 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005595 SmallVector<uint32_t, 16> Inits;
5596 for (auto &ID : Record)
5597 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005598 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005599 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005600 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005601
5602 case SUBMODULE_EXPORT_AS:
5603 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005604 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005605 break;
5606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 }
5608}
5609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005610/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005611/// structure.
5612///
5613/// This routine parses the language options from the AST file and then gives
5614/// them to the AST listener if one is set.
5615///
5616/// \returns true if the listener deems the file unacceptable, false otherwise.
5617bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5618 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005619 ASTReaderListener &Listener,
5620 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005621 LangOptions LangOpts;
5622 unsigned Idx = 0;
5623#define LANGOPT(Name, Bits, Default, Description) \
5624 LangOpts.Name = Record[Idx++];
5625#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5626 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5627#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005628#define SANITIZER(NAME, ID) \
5629 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005630#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005631
Ben Langmuircd98cb72015-06-23 18:20:18 +00005632 for (unsigned N = Record[Idx++]; N; --N)
5633 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5634
Vedant Kumar48b4f762018-04-14 01:40:48 +00005635 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5637 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005638
Ben Langmuird4a667a2015-06-23 18:20:23 +00005639 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005640
5641 // Comment options.
5642 for (unsigned N = Record[Idx++]; N; --N) {
5643 LangOpts.CommentOpts.BlockCommandNames.push_back(
5644 ReadString(Record, Idx));
5645 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005646 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005647
Samuel Antaoee8fb302016-01-06 13:42:12 +00005648 // OpenMP offloading options.
5649 for (unsigned N = Record[Idx++]; N; --N) {
5650 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5651 }
5652
5653 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5654
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005655 return Listener.ReadLanguageOptions(LangOpts, Complain,
5656 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005657}
5658
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005659bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5660 ASTReaderListener &Listener,
5661 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 unsigned Idx = 0;
5663 TargetOptions TargetOpts;
5664 TargetOpts.Triple = ReadString(Record, Idx);
5665 TargetOpts.CPU = ReadString(Record, Idx);
5666 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005667 for (unsigned N = Record[Idx++]; N; --N) {
5668 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5669 }
5670 for (unsigned N = Record[Idx++]; N; --N) {
5671 TargetOpts.Features.push_back(ReadString(Record, Idx));
5672 }
5673
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005674 return Listener.ReadTargetOptions(TargetOpts, Complain,
5675 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005676}
5677
5678bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5679 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005680 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005682#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005683#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005684 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005685#include "clang/Basic/DiagnosticOptions.def"
5686
Richard Smith3be1cb22014-08-07 00:24:21 +00005687 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005688 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005689 for (unsigned N = Record[Idx++]; N; --N)
5690 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005691
5692 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5693}
5694
5695bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5696 ASTReaderListener &Listener) {
5697 FileSystemOptions FSOpts;
5698 unsigned Idx = 0;
5699 FSOpts.WorkingDir = ReadString(Record, Idx);
5700 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5701}
5702
5703bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5704 bool Complain,
5705 ASTReaderListener &Listener) {
5706 HeaderSearchOptions HSOpts;
5707 unsigned Idx = 0;
5708 HSOpts.Sysroot = ReadString(Record, Idx);
5709
5710 // Include entries.
5711 for (unsigned N = Record[Idx++]; N; --N) {
5712 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005713 frontend::IncludeDirGroup Group
5714 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005715 bool IsFramework = Record[Idx++];
5716 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005717 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5718 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005719 }
5720
5721 // System header prefixes.
5722 for (unsigned N = Record[Idx++]; N; --N) {
5723 std::string Prefix = ReadString(Record, Idx);
5724 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005725 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005726 }
5727
5728 HSOpts.ResourceDir = ReadString(Record, Idx);
5729 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005730 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005731 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005732 HSOpts.ImplicitModuleMaps = Record[Idx++];
5733 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 HSOpts.UseBuiltinIncludes = Record[Idx++];
5735 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5736 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5737 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005738 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005740 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5741 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005742}
5743
5744bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5745 bool Complain,
5746 ASTReaderListener &Listener,
5747 std::string &SuggestedPredefines) {
5748 PreprocessorOptions PPOpts;
5749 unsigned Idx = 0;
5750
5751 // Macro definitions/undefs
5752 for (unsigned N = Record[Idx++]; N; --N) {
5753 std::string Macro = ReadString(Record, Idx);
5754 bool IsUndef = Record[Idx++];
5755 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5756 }
5757
5758 // Includes
5759 for (unsigned N = Record[Idx++]; N; --N) {
5760 PPOpts.Includes.push_back(ReadString(Record, Idx));
5761 }
5762
5763 // Macro Includes
5764 for (unsigned N = Record[Idx++]; N; --N) {
5765 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5766 }
5767
5768 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005769 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005771 PPOpts.ObjCXXARCStandardLibrary =
5772 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5773 SuggestedPredefines.clear();
5774 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5775 SuggestedPredefines);
5776}
5777
5778std::pair<ModuleFile *, unsigned>
5779ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5780 GlobalPreprocessedEntityMapType::iterator
5781 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005782 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 "Corrupted global preprocessed entity map");
5784 ModuleFile *M = I->second;
5785 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5786 return std::make_pair(M, LocalIndex);
5787}
5788
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005789llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005790ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5791 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5792 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5793 Mod.NumPreprocessedEntities);
5794
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005795 return llvm::make_range(PreprocessingRecord::iterator(),
5796 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005797}
5798
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005799llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005800ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005801 return llvm::make_range(
5802 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5803 ModuleDeclIterator(this, &Mod,
5804 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005805}
5806
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005807SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5808 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5809 assert(I != GlobalSkippedRangeMap.end() &&
5810 "Corrupted global skipped range map");
5811 ModuleFile *M = I->second;
5812 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5813 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5814 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5815 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5816 TranslateSourceLocation(*M, RawRange.getEnd()));
5817 assert(Range.isValid());
5818 return Range;
5819}
5820
Guy Benyei11169dd2012-12-18 14:30:41 +00005821PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5822 PreprocessedEntityID PPID = Index+1;
5823 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5824 ModuleFile &M = *PPInfo.first;
5825 unsigned LocalIndex = PPInfo.second;
5826 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5827
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 if (!PP.getPreprocessingRecord()) {
5829 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005830 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005832
5833 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005834 if (llvm::Error Err =
5835 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5836 Error(std::move(Err));
5837 return nullptr;
5838 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005839
JF Bastien0e828952019-06-26 19:50:12 +00005840 Expected<llvm::BitstreamEntry> MaybeEntry =
5841 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5842 if (!MaybeEntry) {
5843 Error(MaybeEntry.takeError());
5844 return nullptr;
5845 }
5846 llvm::BitstreamEntry Entry = MaybeEntry.get();
5847
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005848 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005849 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005850
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005852 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5853 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005854 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005855 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005857 Expected<unsigned> MaybeRecType =
5858 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5859 if (!MaybeRecType) {
5860 Error(MaybeRecType.takeError());
5861 return nullptr;
5862 }
5863 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 case PPD_MACRO_EXPANSION: {
5865 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005866 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005867 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 if (isBuiltin)
5869 Name = getLocalIdentifier(M, Record[1]);
5870 else {
Richard Smith66a81862015-05-04 02:25:31 +00005871 PreprocessedEntityID GlobalID =
5872 getGlobalPreprocessedEntityID(M, Record[1]);
5873 Def = cast<MacroDefinitionRecord>(
5874 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 }
5876
5877 MacroExpansion *ME;
5878 if (isBuiltin)
5879 ME = new (PPRec) MacroExpansion(Name, Range);
5880 else
5881 ME = new (PPRec) MacroExpansion(Def, Range);
5882
5883 return ME;
5884 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005885
Guy Benyei11169dd2012-12-18 14:30:41 +00005886 case PPD_MACRO_DEFINITION: {
5887 // Decode the identifier info and then check again; if the macro is
5888 // still defined and associated with the identifier,
5889 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005890 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005891
5892 if (DeserializationListener)
5893 DeserializationListener->MacroDefinitionRead(PPID, MD);
5894
5895 return MD;
5896 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005897
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005899 const char *FullFileNameStart = Blob.data() + Record[0];
5900 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005901 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005903 if (auto FE = PP.getFileManager().getFile(FullFileName))
5904 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005905
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005907 InclusionDirective::InclusionKind Kind
5908 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5909 InclusionDirective *ID
5910 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005911 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005912 Record[1], Record[3],
5913 File,
5914 Range);
5915 return ID;
5916 }
5917 }
5918
5919 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5920}
5921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005922/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005923/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005924///
5925/// \param SLocMapI points at a chunk of a module that contains no
5926/// preprocessed entities or the entities it contains are not the ones we are
5927/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005928PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5929 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5930 ++SLocMapI;
5931 for (GlobalSLocOffsetMapType::const_iterator
5932 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5933 ModuleFile &M = *SLocMapI->second;
5934 if (M.NumPreprocessedEntities)
5935 return M.BasePreprocessedEntityID;
5936 }
5937
5938 return getTotalNumPreprocessedEntities();
5939}
5940
5941namespace {
5942
Guy Benyei11169dd2012-12-18 14:30:41 +00005943struct PPEntityComp {
5944 const ASTReader &Reader;
5945 ModuleFile &M;
5946
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005947 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005948
5949 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5950 SourceLocation LHS = getLoc(L);
5951 SourceLocation RHS = getLoc(R);
5952 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5953 }
5954
5955 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5956 SourceLocation LHS = getLoc(L);
5957 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5958 }
5959
5960 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5961 SourceLocation RHS = getLoc(R);
5962 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5963 }
5964
5965 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005966 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 }
5968};
5969
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005970} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005971
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005972PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5973 bool EndsAfter) const {
5974 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 return getTotalNumPreprocessedEntities();
5976
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005977 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5978 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005979 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5980 "Corrupted global sloc offset map");
5981
5982 if (SLocMapI->second->NumPreprocessedEntities == 0)
5983 return findNextPreprocessedEntity(SLocMapI);
5984
5985 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005986
5987 using pp_iterator = const PPEntityOffset *;
5988
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5990 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5991
5992 size_t Count = M.NumPreprocessedEntities;
5993 size_t Half;
5994 pp_iterator First = pp_begin;
5995 pp_iterator PPI;
5996
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005997 if (EndsAfter) {
5998 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005999 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006000 } else {
6001 // Do a binary search manually instead of using std::lower_bound because
6002 // The end locations of entities may be unordered (when a macro expansion
6003 // is inside another macro argument), but for this case it is not important
6004 // whether we get the first macro expansion or its containing macro.
6005 while (Count > 0) {
6006 Half = Count / 2;
6007 PPI = First;
6008 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006009 if (SourceMgr.isBeforeInTranslationUnit(
6010 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006011 First = PPI;
6012 ++First;
6013 Count = Count - Half - 1;
6014 } else
6015 Count = Half;
6016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 }
6018
6019 if (PPI == pp_end)
6020 return findNextPreprocessedEntity(SLocMapI);
6021
6022 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6023}
6024
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006025/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006026/// preprocessed entities that \arg Range encompasses.
6027std::pair<unsigned, unsigned>
6028 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6029 if (Range.isInvalid())
6030 return std::make_pair(0,0);
6031 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6032
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006033 PreprocessedEntityID BeginID =
6034 findPreprocessedEntity(Range.getBegin(), false);
6035 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 return std::make_pair(BeginID, EndID);
6037}
6038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006039/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006040/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006041Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006042 FileID FID) {
6043 if (FID.isInvalid())
6044 return false;
6045
6046 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6047 ModuleFile &M = *PPInfo.first;
6048 unsigned LocalIndex = PPInfo.second;
6049 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006050
Richard Smithcb34bd32016-03-27 07:28:06 +00006051 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 if (Loc.isInvalid())
6053 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006054
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6056 return true;
6057 else
6058 return false;
6059}
6060
6061namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006063 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006066 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006067
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006069 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006070
6071 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006072 HeaderFileInfoLookupTable *Table
6073 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 if (!Table)
6075 return false;
6076
6077 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006078 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 if (Pos == Table->end())
6080 return false;
6081
Richard Smithbdf2d932015-07-30 03:37:16 +00006082 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 return true;
6084 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006085
David Blaikie05785d12013-02-20 22:23:23 +00006086 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006088
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006089} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006090
6091HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006092 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006093 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006094 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006096
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 return HeaderFileInfo();
6098}
6099
6100void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006101 using DiagState = DiagnosticsEngine::DiagState;
6102 SmallVector<DiagState *, 32> DiagStates;
6103
Vedant Kumar48b4f762018-04-14 01:40:48 +00006104 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006106 auto &Record = F.PragmaDiagMappings;
6107 if (Record.empty())
6108 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006109
Richard Smithd230de22017-01-26 01:01:01 +00006110 DiagStates.clear();
6111
6112 auto ReadDiagState =
6113 [&](const DiagState &BasedOn, SourceLocation Loc,
6114 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6115 unsigned BackrefID = Record[Idx++];
6116 if (BackrefID != 0)
6117 return DiagStates[BackrefID - 1];
6118
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006120 Diag.DiagStates.push_back(BasedOn);
6121 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006123 unsigned Size = Record[Idx++];
6124 assert(Idx + Size * 2 <= Record.size() &&
6125 "Invalid data, not enough diag/map pairs");
6126 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006127 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006128 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006129 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006130 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6131 continue;
6132
6133 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6134
6135 // If this mapping was specified as a warning but the severity was
6136 // upgraded due to diagnostic settings, simulate the current diagnostic
6137 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006138 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6139 NewMapping.setSeverity(diag::Severity::Warning);
6140 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006141 }
6142
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006143 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006144 }
Richard Smithd230de22017-01-26 01:01:01 +00006145 return NewState;
6146 };
6147
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006148 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006149 DiagState *FirstState;
6150 if (F.Kind == MK_ImplicitModule) {
6151 // Implicitly-built modules are reused with different diagnostic
6152 // settings. Use the initial diagnostic state from Diag to simulate this
6153 // compilation's diagnostic settings.
6154 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6155 DiagStates.push_back(FirstState);
6156
6157 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006158 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006159 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006160 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006161 assert(Idx < Record.size() &&
6162 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006163 } else if (F.isModule()) {
6164 // For an explicit module, preserve the flags from the module build
6165 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6166 // -Wblah flags.
6167 unsigned Flags = Record[Idx++];
6168 DiagState Initial;
6169 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6170 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6171 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6172 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6173 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6174 Initial.ExtBehavior = (diag::Severity)Flags;
6175 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006176
Richard Smith6c2b5a82018-02-09 01:15:13 +00006177 assert(F.OriginalSourceFileID.isValid());
6178
Richard Smithe37391c2017-05-03 00:28:49 +00006179 // Set up the root buffer of the module to start with the initial
6180 // diagnostic state of the module itself, to cover files that contain no
6181 // explicit transitions (for which we did not serialize anything).
6182 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6183 .StateTransitions.push_back({FirstState, 0});
6184 } else {
6185 // For prefix ASTs, start with whatever the user configured on the
6186 // command line.
6187 Idx++; // Skip flags.
6188 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6189 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006190 }
Richard Smithd230de22017-01-26 01:01:01 +00006191
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006192 // Read the state transitions.
6193 unsigned NumLocations = Record[Idx++];
6194 while (NumLocations--) {
6195 assert(Idx < Record.size() &&
6196 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006197 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6198 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006199 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006200 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6201 unsigned Transitions = Record[Idx++];
6202
6203 // Note that we don't need to set up Parent/ParentOffset here, because
6204 // we won't be changing the diagnostic state within imported FileIDs
6205 // (other than perhaps appending to the main source file, which has no
6206 // parent).
6207 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6208 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6209 for (unsigned I = 0; I != Transitions; ++I) {
6210 unsigned Offset = Record[Idx++];
6211 auto *State =
6212 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6213 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 }
6215 }
Richard Smithd230de22017-01-26 01:01:01 +00006216
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006217 // Read the final state.
6218 assert(Idx < Record.size() &&
6219 "Invalid data, missing final pragma diagnostic state");
6220 SourceLocation CurStateLoc =
6221 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6222 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6223
6224 if (!F.isModule()) {
6225 Diag.DiagStatesByLoc.CurDiagState = CurState;
6226 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6227
6228 // Preserve the property that the imaginary root file describes the
6229 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006230 FileID NullFile;
6231 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006232 if (T.empty())
6233 T.push_back({CurState, 0});
6234 else
6235 T[0].State = CurState;
6236 }
6237
Richard Smithd230de22017-01-26 01:01:01 +00006238 // Don't try to read these mappings again.
6239 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 }
6241}
6242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006243/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006244ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6245 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6246 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6247 ModuleFile *M = I->second;
6248 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6249}
6250
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006251/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006252///
6253/// The index is the type ID, shifted and minus the number of predefs. This
6254/// routine actually reads the record corresponding to the type at the given
6255/// location. It is a helper routine for GetType, which deals with reading type
6256/// IDs.
6257QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006258 assert(ContextObj && "reading type with no AST context");
6259 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006260 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006261 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006262
6263 // Keep track of where we are in the stream, then jump back there
6264 // after reading this type.
6265 SavedStreamPosition SavedPosition(DeclsCursor);
6266
6267 ReadingKindTracker ReadingKind(Read_Type, *this);
6268
6269 // Note that we are loading a type record.
6270 Deserializing AType(this);
6271
6272 unsigned Idx = 0;
JF Bastien0e828952019-06-26 19:50:12 +00006273 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6274 Error(std::move(Err));
6275 return QualType();
6276 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00006278 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
6279 if (!MaybeCode) {
6280 Error(MaybeCode.takeError());
6281 return QualType();
6282 }
6283 unsigned Code = MaybeCode.get();
6284
6285 Expected<unsigned> MaybeTypeCode = DeclsCursor.readRecord(Code, Record);
6286 if (!MaybeTypeCode) {
6287 Error(MaybeTypeCode.takeError());
6288 return QualType();
6289 }
6290 switch ((TypeCode)MaybeTypeCode.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 case TYPE_EXT_QUAL: {
6292 if (Record.size() != 2) {
6293 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006294 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006295 }
6296 QualType Base = readType(*Loc.F, Record, Idx);
6297 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
6298 return Context.getQualifiedType(Base, Quals);
6299 }
6300
6301 case TYPE_COMPLEX: {
6302 if (Record.size() != 1) {
6303 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006304 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 }
6306 QualType ElemType = readType(*Loc.F, Record, Idx);
6307 return Context.getComplexType(ElemType);
6308 }
6309
6310 case TYPE_POINTER: {
6311 if (Record.size() != 1) {
6312 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006313 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 }
6315 QualType PointeeType = readType(*Loc.F, Record, Idx);
6316 return Context.getPointerType(PointeeType);
6317 }
6318
Reid Kleckner8a365022013-06-24 17:51:48 +00006319 case TYPE_DECAYED: {
6320 if (Record.size() != 1) {
6321 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006322 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00006323 }
6324 QualType OriginalType = readType(*Loc.F, Record, Idx);
6325 QualType DT = Context.getAdjustedParameterType(OriginalType);
6326 if (!isa<DecayedType>(DT))
6327 Error("Decayed type does not decay");
6328 return DT;
6329 }
6330
Reid Kleckner0503a872013-12-05 01:23:43 +00006331 case TYPE_ADJUSTED: {
6332 if (Record.size() != 2) {
6333 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006334 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00006335 }
6336 QualType OriginalTy = readType(*Loc.F, Record, Idx);
6337 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
6338 return Context.getAdjustedType(OriginalTy, AdjustedTy);
6339 }
6340
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 case TYPE_BLOCK_POINTER: {
6342 if (Record.size() != 1) {
6343 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006344 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 }
6346 QualType PointeeType = readType(*Loc.F, Record, Idx);
6347 return Context.getBlockPointerType(PointeeType);
6348 }
6349
6350 case TYPE_LVALUE_REFERENCE: {
6351 if (Record.size() != 2) {
6352 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006353 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 }
6355 QualType PointeeType = readType(*Loc.F, Record, Idx);
6356 return Context.getLValueReferenceType(PointeeType, Record[1]);
6357 }
6358
6359 case TYPE_RVALUE_REFERENCE: {
6360 if (Record.size() != 1) {
6361 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006362 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 }
6364 QualType PointeeType = readType(*Loc.F, Record, Idx);
6365 return Context.getRValueReferenceType(PointeeType);
6366 }
6367
6368 case TYPE_MEMBER_POINTER: {
6369 if (Record.size() != 2) {
6370 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006371 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 }
6373 QualType PointeeType = readType(*Loc.F, Record, Idx);
6374 QualType ClassType = readType(*Loc.F, Record, Idx);
6375 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006376 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006377
Guy Benyei11169dd2012-12-18 14:30:41 +00006378 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
6379 }
6380
6381 case TYPE_CONSTANT_ARRAY: {
6382 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006383 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 unsigned IndexTypeQuals = Record[2];
6385 unsigned Idx = 3;
6386 llvm::APInt Size = ReadAPInt(Record, Idx);
6387 return Context.getConstantArrayType(ElementType, Size,
6388 ASM, IndexTypeQuals);
6389 }
6390
6391 case TYPE_INCOMPLETE_ARRAY: {
6392 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006393 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 unsigned IndexTypeQuals = Record[2];
6395 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6396 }
6397
6398 case TYPE_VARIABLE_ARRAY: {
6399 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006400 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 unsigned IndexTypeQuals = Record[2];
6402 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6403 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6404 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6405 ASM, IndexTypeQuals,
6406 SourceRange(LBLoc, RBLoc));
6407 }
6408
6409 case TYPE_VECTOR: {
6410 if (Record.size() != 3) {
6411 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006412 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 }
6414
6415 QualType ElementType = readType(*Loc.F, Record, Idx);
6416 unsigned NumElements = Record[1];
6417 unsigned VecKind = Record[2];
6418 return Context.getVectorType(ElementType, NumElements,
6419 (VectorType::VectorKind)VecKind);
6420 }
6421
6422 case TYPE_EXT_VECTOR: {
6423 if (Record.size() != 3) {
6424 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006425 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 }
6427
6428 QualType ElementType = readType(*Loc.F, Record, Idx);
6429 unsigned NumElements = Record[1];
6430 return Context.getExtVectorType(ElementType, NumElements);
6431 }
6432
6433 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006434 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006436 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 }
6438 QualType ResultType = readType(*Loc.F, Record, Idx);
6439 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006440 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006441 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 return Context.getFunctionNoProtoType(ResultType, Info);
6443 }
6444
6445 case TYPE_FUNCTION_PROTO: {
6446 QualType ResultType = readType(*Loc.F, Record, Idx);
6447
6448 FunctionProtoType::ExtProtoInfo EPI;
6449 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6450 /*hasregparm*/ Record[2],
6451 /*regparm*/ Record[3],
6452 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006453 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006454 /*nocallersavedregs*/ Record[6],
6455 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006456
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006457 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006458
6459 EPI.Variadic = Record[Idx++];
6460 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006461 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006463 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006464 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006465
6466 unsigned NumParams = Record[Idx++];
6467 SmallVector<QualType, 16> ParamTypes;
6468 for (unsigned I = 0; I != NumParams; ++I)
6469 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6470
John McCall18afab72016-03-01 00:49:02 +00006471 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6472 if (Idx != Record.size()) {
6473 for (unsigned I = 0; I != NumParams; ++I)
6474 ExtParameterInfos.push_back(
6475 FunctionProtoType::ExtParameterInfo
6476 ::getFromOpaqueValue(Record[Idx++]));
6477 EPI.ExtParameterInfos = ExtParameterInfos.data();
6478 }
6479
6480 assert(Idx == Record.size());
6481
Jordan Rose5c382722013-03-08 21:51:21 +00006482 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 }
6484
6485 case TYPE_UNRESOLVED_USING: {
6486 unsigned Idx = 0;
6487 return Context.getTypeDeclType(
6488 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6489 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006490
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 case TYPE_TYPEDEF: {
6492 if (Record.size() != 2) {
6493 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006494 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 }
6496 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006497 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006498 QualType Canonical = readType(*Loc.F, Record, Idx);
6499 if (!Canonical.isNull())
6500 Canonical = Context.getCanonicalType(Canonical);
6501 return Context.getTypedefType(Decl, Canonical);
6502 }
6503
6504 case TYPE_TYPEOF_EXPR:
6505 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6506
6507 case TYPE_TYPEOF: {
6508 if (Record.size() != 1) {
6509 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006510 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006511 }
6512 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6513 return Context.getTypeOfType(UnderlyingType);
6514 }
6515
6516 case TYPE_DECLTYPE: {
6517 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6518 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6519 }
6520
6521 case TYPE_UNARY_TRANSFORM: {
6522 QualType BaseType = readType(*Loc.F, Record, Idx);
6523 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006524 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6526 }
6527
Richard Smith74aeef52013-04-26 16:15:35 +00006528 case TYPE_AUTO: {
6529 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006530 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006531 bool IsDependent = false, IsPack = false;
6532 if (Deduced.isNull()) {
6533 IsDependent = Record[Idx] > 0;
6534 IsPack = Record[Idx] > 1;
6535 ++Idx;
6536 }
6537 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006538 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006539
Richard Smith600b5262017-01-26 20:40:47 +00006540 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6541 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6542 QualType Deduced = readType(*Loc.F, Record, Idx);
6543 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6544 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6545 IsDependent);
6546 }
6547
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 case TYPE_RECORD: {
6549 if (Record.size() != 2) {
6550 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006551 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 }
6553 unsigned Idx = 0;
6554 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006555 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6557 QualType T = Context.getRecordType(RD);
6558 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6559 return T;
6560 }
6561
6562 case TYPE_ENUM: {
6563 if (Record.size() != 2) {
6564 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006565 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 }
6567 unsigned Idx = 0;
6568 bool IsDependent = Record[Idx++];
6569 QualType T
6570 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6571 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6572 return T;
6573 }
6574
6575 case TYPE_ATTRIBUTED: {
6576 if (Record.size() != 3) {
6577 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006578 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 }
6580 QualType modifiedType = readType(*Loc.F, Record, Idx);
6581 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006582 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 return Context.getAttributedType(kind, modifiedType, equivalentType);
6584 }
6585
6586 case TYPE_PAREN: {
6587 if (Record.size() != 1) {
6588 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006589 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 }
6591 QualType InnerType = readType(*Loc.F, Record, Idx);
6592 return Context.getParenType(InnerType);
6593 }
6594
Leonard Chanc72aaf62019-05-07 03:20:17 +00006595 case TYPE_MACRO_QUALIFIED: {
6596 if (Record.size() != 2) {
6597 Error("incorrect encoding of macro defined type");
6598 return QualType();
6599 }
6600 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6601 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6602 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6603 }
6604
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 case TYPE_PACK_EXPANSION: {
6606 if (Record.size() != 2) {
6607 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006608 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 }
6610 QualType Pattern = readType(*Loc.F, Record, Idx);
6611 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006612 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006613 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 if (Record[1])
6615 NumExpansions = Record[1] - 1;
6616 return Context.getPackExpansionType(Pattern, NumExpansions);
6617 }
6618
6619 case TYPE_ELABORATED: {
6620 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006621 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6623 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006624 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6625 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 }
6627
6628 case TYPE_OBJC_INTERFACE: {
6629 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006630 ObjCInterfaceDecl *ItfD
6631 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6633 }
6634
Manman Rene6be26c2016-09-13 17:25:08 +00006635 case TYPE_OBJC_TYPE_PARAM: {
6636 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006637 ObjCTypeParamDecl *Decl
6638 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006639 unsigned NumProtos = Record[Idx++];
6640 SmallVector<ObjCProtocolDecl*, 4> Protos;
6641 for (unsigned I = 0; I != NumProtos; ++I)
6642 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6643 return Context.getObjCTypeParamType(Decl, Protos);
6644 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006645
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 case TYPE_OBJC_OBJECT: {
6647 unsigned Idx = 0;
6648 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006649 unsigned NumTypeArgs = Record[Idx++];
6650 SmallVector<QualType, 4> TypeArgs;
6651 for (unsigned I = 0; I != NumTypeArgs; ++I)
6652 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 unsigned NumProtos = Record[Idx++];
6654 SmallVector<ObjCProtocolDecl*, 4> Protos;
6655 for (unsigned I = 0; I != NumProtos; ++I)
6656 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006657 bool IsKindOf = Record[Idx++];
6658 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006659 }
6660
6661 case TYPE_OBJC_OBJECT_POINTER: {
6662 unsigned Idx = 0;
6663 QualType Pointee = readType(*Loc.F, Record, Idx);
6664 return Context.getObjCObjectPointerType(Pointee);
6665 }
6666
6667 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6668 unsigned Idx = 0;
6669 QualType Parm = readType(*Loc.F, Record, Idx);
6670 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006671 return Context.getSubstTemplateTypeParmType(
6672 cast<TemplateTypeParmType>(Parm),
6673 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 }
6675
6676 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6677 unsigned Idx = 0;
6678 QualType Parm = readType(*Loc.F, Record, Idx);
6679 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6680 return Context.getSubstTemplateTypeParmPackType(
6681 cast<TemplateTypeParmType>(Parm),
6682 ArgPack);
6683 }
6684
6685 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006686 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006687 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6688 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6689 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006690 const Type *T = nullptr;
6691 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6692 if (const Type *Existing = DI->getTypeForDecl()) {
6693 T = Existing;
6694 break;
6695 }
6696 }
6697 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006698 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006699 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6700 DI->setTypeForDecl(T);
6701 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006702 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 }
6704
6705 case TYPE_TEMPLATE_TYPE_PARM: {
6706 unsigned Idx = 0;
6707 unsigned Depth = Record[Idx++];
6708 unsigned Index = Record[Idx++];
6709 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006710 TemplateTypeParmDecl *D
6711 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6713 }
6714
6715 case TYPE_DEPENDENT_NAME: {
6716 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006717 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006719 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 QualType Canon = readType(*Loc.F, Record, Idx);
6721 if (!Canon.isNull())
6722 Canon = Context.getCanonicalType(Canon);
6723 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6724 }
6725
6726 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6727 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006728 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006730 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 unsigned NumArgs = Record[Idx++];
6732 SmallVector<TemplateArgument, 8> Args;
6733 Args.reserve(NumArgs);
6734 while (NumArgs--)
6735 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6736 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006737 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 }
6739
6740 case TYPE_DEPENDENT_SIZED_ARRAY: {
6741 unsigned Idx = 0;
6742
6743 // ArrayType
6744 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006745 ArrayType::ArraySizeModifier ASM
6746 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 unsigned IndexTypeQuals = Record[Idx++];
6748
6749 // DependentSizedArrayType
6750 Expr *NumElts = ReadExpr(*Loc.F);
6751 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6752
6753 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6754 IndexTypeQuals, Brackets);
6755 }
6756
6757 case TYPE_TEMPLATE_SPECIALIZATION: {
6758 unsigned Idx = 0;
6759 bool IsDependent = Record[Idx++];
6760 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6761 SmallVector<TemplateArgument, 8> Args;
6762 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6763 QualType Underlying = readType(*Loc.F, Record, Idx);
6764 QualType T;
6765 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006766 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006768 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006769 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6770 return T;
6771 }
6772
6773 case TYPE_ATOMIC: {
6774 if (Record.size() != 1) {
6775 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006776 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 }
6778 QualType ValueType = readType(*Loc.F, Record, Idx);
6779 return Context.getAtomicType(ValueType);
6780 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006781
Joey Goulye3c85de2016-12-01 11:30:49 +00006782 case TYPE_PIPE: {
6783 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006784 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006785 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006786 }
6787
6788 // Reading the pipe element type.
6789 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006790 unsigned ReadOnly = Record[1];
6791 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006792 }
6793
Erich Keanef702b022018-07-13 19:46:04 +00006794 case TYPE_DEPENDENT_SIZED_VECTOR: {
6795 unsigned Idx = 0;
6796 QualType ElementType = readType(*Loc.F, Record, Idx);
6797 Expr *SizeExpr = ReadExpr(*Loc.F);
6798 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6799 unsigned VecKind = Record[Idx];
6800
6801 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6802 (VectorType::VectorKind)VecKind);
6803 }
6804
Alex Lorenz00aee432017-03-22 10:04:48 +00006805 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6806 unsigned Idx = 0;
6807
6808 // DependentSizedExtVectorType
6809 QualType ElementType = readType(*Loc.F, Record, Idx);
6810 Expr *SizeExpr = ReadExpr(*Loc.F);
6811 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6812
6813 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6814 AttrLoc);
6815 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006816
6817 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6818 unsigned Idx = 0;
6819
6820 // DependentAddressSpaceType
6821 QualType PointeeType = readType(*Loc.F, Record, Idx);
6822 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6823 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6824
6825 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6826 AttrLoc);
6827 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006828 }
6829 llvm_unreachable("Invalid TypeCode!");
6830}
6831
Richard Smith564417a2014-03-20 21:47:22 +00006832void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6833 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006834 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006835 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006836 ExceptionSpecificationType EST =
6837 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006838 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006839 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006840 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006841 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006842 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006843 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006844 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006845 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006846 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6847 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006848 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006849 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006850 }
6851}
6852
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006853namespace clang {
6854
6855class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006856 ModuleFile *F;
6857 ASTReader *Reader;
6858 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 unsigned &Idx;
6860
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006861 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006862 return Reader->ReadSourceLocation(*F, Record, Idx);
6863 }
6864
6865 TypeSourceInfo *GetTypeSourceInfo() {
6866 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6867 }
6868
6869 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6870 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 }
6872
Richard Smithe43e2b32018-08-20 21:47:29 +00006873 Attr *ReadAttr() {
6874 return Reader->ReadAttr(*F, Record, Idx);
6875 }
6876
Guy Benyei11169dd2012-12-18 14:30:41 +00006877public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006878 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006880 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006881
6882 // We want compile-time assurance that we've enumerated all of
6883 // these, so unfortunately we have to declare them first, then
6884 // define them out-of-line.
6885#define ABSTRACT_TYPELOC(CLASS, PARENT)
6886#define TYPELOC(CLASS, PARENT) \
6887 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6888#include "clang/AST/TypeLocNodes.def"
6889
6890 void VisitFunctionTypeLoc(FunctionTypeLoc);
6891 void VisitArrayTypeLoc(ArrayTypeLoc);
6892};
6893
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006894} // namespace clang
6895
Guy Benyei11169dd2012-12-18 14:30:41 +00006896void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6897 // nothing to do
6898}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006899
Guy Benyei11169dd2012-12-18 14:30:41 +00006900void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006901 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006903 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6904 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6905 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6906 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 }
6908}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006909
Guy Benyei11169dd2012-12-18 14:30:41 +00006910void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006911 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006912}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006913
Guy Benyei11169dd2012-12-18 14:30:41 +00006914void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006915 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006916}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006917
Reid Kleckner8a365022013-06-24 17:51:48 +00006918void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6919 // nothing to do
6920}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006921
Reid Kleckner0503a872013-12-05 01:23:43 +00006922void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6923 // nothing to do
6924}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006925
Leonard Chanc72aaf62019-05-07 03:20:17 +00006926void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6927 TL.setExpansionLoc(ReadSourceLocation());
6928}
6929
Guy Benyei11169dd2012-12-18 14:30:41 +00006930void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006931 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006932}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006933
Guy Benyei11169dd2012-12-18 14:30:41 +00006934void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006935 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006936}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006937
Guy Benyei11169dd2012-12-18 14:30:41 +00006938void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006939 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006940}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006941
Guy Benyei11169dd2012-12-18 14:30:41 +00006942void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006943 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006944 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006945}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006946
Guy Benyei11169dd2012-12-18 14:30:41 +00006947void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006948 TL.setLBracketLoc(ReadSourceLocation());
6949 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006950 if (Record[Idx++])
6951 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 else
Craig Toppera13603a2014-05-22 05:54:18 +00006953 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006954}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006955
Guy Benyei11169dd2012-12-18 14:30:41 +00006956void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6957 VisitArrayTypeLoc(TL);
6958}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006959
Guy Benyei11169dd2012-12-18 14:30:41 +00006960void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6961 VisitArrayTypeLoc(TL);
6962}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006963
Guy Benyei11169dd2012-12-18 14:30:41 +00006964void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6965 VisitArrayTypeLoc(TL);
6966}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006967
Guy Benyei11169dd2012-12-18 14:30:41 +00006968void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6969 DependentSizedArrayTypeLoc TL) {
6970 VisitArrayTypeLoc(TL);
6971}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006972
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006973void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6974 DependentAddressSpaceTypeLoc TL) {
6975
6976 TL.setAttrNameLoc(ReadSourceLocation());
6977 SourceRange range;
6978 range.setBegin(ReadSourceLocation());
6979 range.setEnd(ReadSourceLocation());
6980 TL.setAttrOperandParensRange(range);
6981 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6982}
6983
Guy Benyei11169dd2012-12-18 14:30:41 +00006984void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6985 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006986 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006987}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006988
Guy Benyei11169dd2012-12-18 14:30:41 +00006989void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006990 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006991}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006992
Erich Keanef702b022018-07-13 19:46:04 +00006993void TypeLocReader::VisitDependentVectorTypeLoc(
6994 DependentVectorTypeLoc TL) {
6995 TL.setNameLoc(ReadSourceLocation());
6996}
6997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006999 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007000}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007003 TL.setLocalRangeBegin(ReadSourceLocation());
7004 TL.setLParenLoc(ReadSourceLocation());
7005 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00007006 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
7007 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007008 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007009 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007010 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 }
7012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007013
Guy Benyei11169dd2012-12-18 14:30:41 +00007014void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7015 VisitFunctionTypeLoc(TL);
7016}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7019 VisitFunctionTypeLoc(TL);
7020}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007021
Guy Benyei11169dd2012-12-18 14:30:41 +00007022void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007023 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007024}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007027 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007028}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007029
Guy Benyei11169dd2012-12-18 14:30:41 +00007030void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007031 TL.setTypeofLoc(ReadSourceLocation());
7032 TL.setLParenLoc(ReadSourceLocation());
7033 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007034}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007037 TL.setTypeofLoc(ReadSourceLocation());
7038 TL.setLParenLoc(ReadSourceLocation());
7039 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007040 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007041}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007042
Guy Benyei11169dd2012-12-18 14:30:41 +00007043void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007044 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007045}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007046
Guy Benyei11169dd2012-12-18 14:30:41 +00007047void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007048 TL.setKWLoc(ReadSourceLocation());
7049 TL.setLParenLoc(ReadSourceLocation());
7050 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007051 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007052}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007053
Guy Benyei11169dd2012-12-18 14:30:41 +00007054void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007055 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007056}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007057
Richard Smith600b5262017-01-26 20:40:47 +00007058void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7059 DeducedTemplateSpecializationTypeLoc TL) {
7060 TL.setTemplateNameLoc(ReadSourceLocation());
7061}
7062
Guy Benyei11169dd2012-12-18 14:30:41 +00007063void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007064 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007065}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007066
Guy Benyei11169dd2012-12-18 14:30:41 +00007067void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007068 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007069}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00007072 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00007073}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007074
Guy Benyei11169dd2012-12-18 14:30:41 +00007075void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007076 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007077}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007078
Guy Benyei11169dd2012-12-18 14:30:41 +00007079void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7080 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007081 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007082}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007083
Guy Benyei11169dd2012-12-18 14:30:41 +00007084void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7085 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007086 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007087}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007088
Guy Benyei11169dd2012-12-18 14:30:41 +00007089void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7090 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007091 TL.setTemplateKeywordLoc(ReadSourceLocation());
7092 TL.setTemplateNameLoc(ReadSourceLocation());
7093 TL.setLAngleLoc(ReadSourceLocation());
7094 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007095 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007096 TL.setArgLocInfo(
7097 i,
7098 Reader->GetTemplateArgumentLocInfo(
7099 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007100}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007101
Guy Benyei11169dd2012-12-18 14:30:41 +00007102void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007103 TL.setLParenLoc(ReadSourceLocation());
7104 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007105}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007106
Guy Benyei11169dd2012-12-18 14:30:41 +00007107void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007108 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007109 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007110}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007113 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007115
Guy Benyei11169dd2012-12-18 14:30:41 +00007116void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007117 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007118 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007119 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007120}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007121
Guy Benyei11169dd2012-12-18 14:30:41 +00007122void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7123 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007124 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007125 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007126 TL.setTemplateKeywordLoc(ReadSourceLocation());
7127 TL.setTemplateNameLoc(ReadSourceLocation());
7128 TL.setLAngleLoc(ReadSourceLocation());
7129 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007131 TL.setArgLocInfo(
7132 I,
7133 Reader->GetTemplateArgumentLocInfo(
7134 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007136
Guy Benyei11169dd2012-12-18 14:30:41 +00007137void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007138 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007139}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007142 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007143}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007144
Manman Rene6be26c2016-09-13 17:25:08 +00007145void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7146 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007147 TL.setProtocolLAngleLoc(ReadSourceLocation());
7148 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007149 }
7150 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007151 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007152}
7153
Guy Benyei11169dd2012-12-18 14:30:41 +00007154void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007155 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007156 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
7157 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00007158 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007159 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007160 TL.setProtocolLAngleLoc(ReadSourceLocation());
7161 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007163 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007165
Guy Benyei11169dd2012-12-18 14:30:41 +00007166void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007167 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007169
Guy Benyei11169dd2012-12-18 14:30:41 +00007170void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007171 TL.setKWLoc(ReadSourceLocation());
7172 TL.setLParenLoc(ReadSourceLocation());
7173 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007174}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007175
Xiuli Pan9c14e282016-01-09 12:53:17 +00007176void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007177 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00007178}
Guy Benyei11169dd2012-12-18 14:30:41 +00007179
Richard Smithc23d7342018-06-29 20:46:25 +00007180void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
7181 unsigned &Idx, TypeLoc TL) {
7182 TypeLocReader TLR(F, *this, Record, Idx);
7183 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7184 TLR.Visit(TL);
7185}
7186
David L. Jonesbe1557a2016-12-21 00:17:49 +00007187TypeSourceInfo *
7188ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
7189 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 QualType InfoTy = readType(F, Record, Idx);
7191 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00007192 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007193
7194 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00007195 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 return TInfo;
7197}
7198
7199QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007200 assert(ContextObj && "reading type with no AST context");
7201 ASTContext &Context = *ContextObj;
7202
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 unsigned FastQuals = ID & Qualifiers::FastMask;
7204 unsigned Index = ID >> Qualifiers::FastWidth;
7205
7206 if (Index < NUM_PREDEF_TYPE_IDS) {
7207 QualType T;
7208 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00007209 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00007210 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00007211 case PREDEF_TYPE_VOID_ID:
7212 T = Context.VoidTy;
7213 break;
7214 case PREDEF_TYPE_BOOL_ID:
7215 T = Context.BoolTy;
7216 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 case PREDEF_TYPE_CHAR_U_ID:
7218 case PREDEF_TYPE_CHAR_S_ID:
7219 // FIXME: Check that the signedness of CharTy is correct!
7220 T = Context.CharTy;
7221 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007222 case PREDEF_TYPE_UCHAR_ID:
7223 T = Context.UnsignedCharTy;
7224 break;
7225 case PREDEF_TYPE_USHORT_ID:
7226 T = Context.UnsignedShortTy;
7227 break;
7228 case PREDEF_TYPE_UINT_ID:
7229 T = Context.UnsignedIntTy;
7230 break;
7231 case PREDEF_TYPE_ULONG_ID:
7232 T = Context.UnsignedLongTy;
7233 break;
7234 case PREDEF_TYPE_ULONGLONG_ID:
7235 T = Context.UnsignedLongLongTy;
7236 break;
7237 case PREDEF_TYPE_UINT128_ID:
7238 T = Context.UnsignedInt128Ty;
7239 break;
7240 case PREDEF_TYPE_SCHAR_ID:
7241 T = Context.SignedCharTy;
7242 break;
7243 case PREDEF_TYPE_WCHAR_ID:
7244 T = Context.WCharTy;
7245 break;
7246 case PREDEF_TYPE_SHORT_ID:
7247 T = Context.ShortTy;
7248 break;
7249 case PREDEF_TYPE_INT_ID:
7250 T = Context.IntTy;
7251 break;
7252 case PREDEF_TYPE_LONG_ID:
7253 T = Context.LongTy;
7254 break;
7255 case PREDEF_TYPE_LONGLONG_ID:
7256 T = Context.LongLongTy;
7257 break;
7258 case PREDEF_TYPE_INT128_ID:
7259 T = Context.Int128Ty;
7260 break;
7261 case PREDEF_TYPE_HALF_ID:
7262 T = Context.HalfTy;
7263 break;
7264 case PREDEF_TYPE_FLOAT_ID:
7265 T = Context.FloatTy;
7266 break;
7267 case PREDEF_TYPE_DOUBLE_ID:
7268 T = Context.DoubleTy;
7269 break;
7270 case PREDEF_TYPE_LONGDOUBLE_ID:
7271 T = Context.LongDoubleTy;
7272 break;
Leonard Chanf921d852018-06-04 16:07:52 +00007273 case PREDEF_TYPE_SHORT_ACCUM_ID:
7274 T = Context.ShortAccumTy;
7275 break;
7276 case PREDEF_TYPE_ACCUM_ID:
7277 T = Context.AccumTy;
7278 break;
7279 case PREDEF_TYPE_LONG_ACCUM_ID:
7280 T = Context.LongAccumTy;
7281 break;
7282 case PREDEF_TYPE_USHORT_ACCUM_ID:
7283 T = Context.UnsignedShortAccumTy;
7284 break;
7285 case PREDEF_TYPE_UACCUM_ID:
7286 T = Context.UnsignedAccumTy;
7287 break;
7288 case PREDEF_TYPE_ULONG_ACCUM_ID:
7289 T = Context.UnsignedLongAccumTy;
7290 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00007291 case PREDEF_TYPE_SHORT_FRACT_ID:
7292 T = Context.ShortFractTy;
7293 break;
7294 case PREDEF_TYPE_FRACT_ID:
7295 T = Context.FractTy;
7296 break;
7297 case PREDEF_TYPE_LONG_FRACT_ID:
7298 T = Context.LongFractTy;
7299 break;
7300 case PREDEF_TYPE_USHORT_FRACT_ID:
7301 T = Context.UnsignedShortFractTy;
7302 break;
7303 case PREDEF_TYPE_UFRACT_ID:
7304 T = Context.UnsignedFractTy;
7305 break;
7306 case PREDEF_TYPE_ULONG_FRACT_ID:
7307 T = Context.UnsignedLongFractTy;
7308 break;
7309 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7310 T = Context.SatShortAccumTy;
7311 break;
7312 case PREDEF_TYPE_SAT_ACCUM_ID:
7313 T = Context.SatAccumTy;
7314 break;
7315 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7316 T = Context.SatLongAccumTy;
7317 break;
7318 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7319 T = Context.SatUnsignedShortAccumTy;
7320 break;
7321 case PREDEF_TYPE_SAT_UACCUM_ID:
7322 T = Context.SatUnsignedAccumTy;
7323 break;
7324 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7325 T = Context.SatUnsignedLongAccumTy;
7326 break;
7327 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7328 T = Context.SatShortFractTy;
7329 break;
7330 case PREDEF_TYPE_SAT_FRACT_ID:
7331 T = Context.SatFractTy;
7332 break;
7333 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7334 T = Context.SatLongFractTy;
7335 break;
7336 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7337 T = Context.SatUnsignedShortFractTy;
7338 break;
7339 case PREDEF_TYPE_SAT_UFRACT_ID:
7340 T = Context.SatUnsignedFractTy;
7341 break;
7342 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7343 T = Context.SatUnsignedLongFractTy;
7344 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00007345 case PREDEF_TYPE_FLOAT16_ID:
7346 T = Context.Float16Ty;
7347 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007348 case PREDEF_TYPE_FLOAT128_ID:
7349 T = Context.Float128Ty;
7350 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007351 case PREDEF_TYPE_OVERLOAD_ID:
7352 T = Context.OverloadTy;
7353 break;
7354 case PREDEF_TYPE_BOUND_MEMBER:
7355 T = Context.BoundMemberTy;
7356 break;
7357 case PREDEF_TYPE_PSEUDO_OBJECT:
7358 T = Context.PseudoObjectTy;
7359 break;
7360 case PREDEF_TYPE_DEPENDENT_ID:
7361 T = Context.DependentTy;
7362 break;
7363 case PREDEF_TYPE_UNKNOWN_ANY:
7364 T = Context.UnknownAnyTy;
7365 break;
7366 case PREDEF_TYPE_NULLPTR_ID:
7367 T = Context.NullPtrTy;
7368 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007369 case PREDEF_TYPE_CHAR8_ID:
7370 T = Context.Char8Ty;
7371 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007372 case PREDEF_TYPE_CHAR16_ID:
7373 T = Context.Char16Ty;
7374 break;
7375 case PREDEF_TYPE_CHAR32_ID:
7376 T = Context.Char32Ty;
7377 break;
7378 case PREDEF_TYPE_OBJC_ID:
7379 T = Context.ObjCBuiltinIdTy;
7380 break;
7381 case PREDEF_TYPE_OBJC_CLASS:
7382 T = Context.ObjCBuiltinClassTy;
7383 break;
7384 case PREDEF_TYPE_OBJC_SEL:
7385 T = Context.ObjCBuiltinSelTy;
7386 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007387#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7388 case PREDEF_TYPE_##Id##_ID: \
7389 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007390 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007391#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007392#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7393 case PREDEF_TYPE_##Id##_ID: \
7394 T = Context.Id##Ty; \
7395 break;
7396#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007397 case PREDEF_TYPE_SAMPLER_ID:
7398 T = Context.OCLSamplerTy;
7399 break;
7400 case PREDEF_TYPE_EVENT_ID:
7401 T = Context.OCLEventTy;
7402 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007403 case PREDEF_TYPE_CLK_EVENT_ID:
7404 T = Context.OCLClkEventTy;
7405 break;
7406 case PREDEF_TYPE_QUEUE_ID:
7407 T = Context.OCLQueueTy;
7408 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007409 case PREDEF_TYPE_RESERVE_ID_ID:
7410 T = Context.OCLReserveIDTy;
7411 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007412 case PREDEF_TYPE_AUTO_DEDUCT:
7413 T = Context.getAutoDeductType();
7414 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007415 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7416 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7419 T = Context.ARCUnbridgedCastTy;
7420 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 case PREDEF_TYPE_BUILTIN_FN:
7422 T = Context.BuiltinFnTy;
7423 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007424 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7425 T = Context.OMPArraySectionTy;
7426 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00007427#define SVE_TYPE(Name, Id, SingletonId) \
7428 case PREDEF_TYPE_##Id##_ID: \
7429 T = Context.SingletonId; \
7430 break;
7431#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 }
7433
7434 assert(!T.isNull() && "Unknown predefined type");
7435 return T.withFastQualifiers(FastQuals);
7436 }
7437
7438 Index -= NUM_PREDEF_TYPE_IDS;
7439 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7440 if (TypesLoaded[Index].isNull()) {
7441 TypesLoaded[Index] = readTypeRecord(Index);
7442 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007443 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007444
7445 TypesLoaded[Index]->setFromAST();
7446 if (DeserializationListener)
7447 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7448 TypesLoaded[Index]);
7449 }
7450
7451 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7452}
7453
7454QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7455 return GetType(getGlobalTypeID(F, LocalID));
7456}
7457
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007458serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007459ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7460 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7461 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007462
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7464 return LocalID;
7465
Richard Smith37a93df2017-02-18 00:32:02 +00007466 if (!F.ModuleOffsetMap.empty())
7467 ReadModuleOffsetMap(F);
7468
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7470 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7471 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007472
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 unsigned GlobalIndex = LocalIndex + I->second;
7474 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7475}
7476
7477TemplateArgumentLocInfo
7478ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7479 TemplateArgument::ArgKind Kind,
7480 const RecordData &Record,
7481 unsigned &Index) {
7482 switch (Kind) {
7483 case TemplateArgument::Expression:
7484 return ReadExpr(F);
7485 case TemplateArgument::Type:
7486 return GetTypeSourceInfo(F, Record, Index);
7487 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007488 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 Index);
7490 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7491 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7492 SourceLocation());
7493 }
7494 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007495 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 Index);
7497 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7498 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007499 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 EllipsisLoc);
7501 }
7502 case TemplateArgument::Null:
7503 case TemplateArgument::Integral:
7504 case TemplateArgument::Declaration:
7505 case TemplateArgument::NullPtr:
7506 case TemplateArgument::Pack:
7507 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007508 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 }
7510 llvm_unreachable("unexpected template argument loc");
7511}
7512
7513TemplateArgumentLoc
7514ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7515 const RecordData &Record, unsigned &Index) {
7516 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7517
7518 if (Arg.getKind() == TemplateArgument::Expression) {
7519 if (Record[Index++]) // bool InfoHasSameExpr.
7520 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7521 }
7522 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7523 Record, Index));
7524}
7525
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007526const ASTTemplateArgumentListInfo*
7527ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7528 const RecordData &Record,
7529 unsigned &Index) {
7530 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7531 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7532 unsigned NumArgsAsWritten = Record[Index++];
7533 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7534 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7535 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7536 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7537}
7538
Guy Benyei11169dd2012-12-18 14:30:41 +00007539Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7540 return GetDecl(ID);
7541}
7542
Richard Smith053f6c62014-05-16 23:01:30 +00007543void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007544 if (NumCurrentElementsDeserializing) {
7545 // We arrange to not care about the complete redeclaration chain while we're
7546 // deserializing. Just remember that the AST has marked this one as complete
7547 // but that it's not actually complete yet, so we know we still need to
7548 // complete it later.
7549 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7550 return;
7551 }
7552
Richard Smith053f6c62014-05-16 23:01:30 +00007553 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7554
Richard Smith053f6c62014-05-16 23:01:30 +00007555 // If this is a named declaration, complete it by looking it up
7556 // within its context.
7557 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007558 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007559 // all mergeable entities within it.
7560 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7561 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7562 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007563 if (!getContext().getLangOpts().CPlusPlus &&
7564 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007565 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007566 // the identifier instead. (For C++ modules, we don't store decls
7567 // in the serialized identifier table, so we do the lookup in the TU.)
7568 auto *II = Name.getAsIdentifierInfo();
7569 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007570 if (II->isOutOfDate())
7571 updateOutOfDateIdentifier(*II);
7572 } else
7573 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007574 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007575 // Find all declarations of this kind from the relevant context.
7576 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7577 auto *DC = cast<DeclContext>(DCDecl);
7578 SmallVector<Decl*, 8> Decls;
7579 FindExternalLexicalDecls(
7580 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7581 }
Richard Smith053f6c62014-05-16 23:01:30 +00007582 }
7583 }
Richard Smith50895422015-01-31 03:04:55 +00007584
7585 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7586 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7587 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7588 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7589 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7590 if (auto *Template = FD->getPrimaryTemplate())
7591 Template->LoadLazySpecializations();
7592 }
Richard Smith053f6c62014-05-16 23:01:30 +00007593}
7594
Richard Smithc2bb8182015-03-24 06:36:48 +00007595CXXCtorInitializer **
7596ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7597 RecordLocation Loc = getLocalBitOffset(Offset);
7598 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7599 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007600 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7601 Error(std::move(Err));
7602 return nullptr;
7603 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007604 ReadingKindTracker ReadingKind(Read_Decl, *this);
7605
7606 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007607 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7608 if (!MaybeCode) {
7609 Error(MaybeCode.takeError());
7610 return nullptr;
7611 }
7612 unsigned Code = MaybeCode.get();
7613
7614 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7615 if (!MaybeRecCode) {
7616 Error(MaybeRecCode.takeError());
7617 return nullptr;
7618 }
7619 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007620 Error("malformed AST file: missing C++ ctor initializers");
7621 return nullptr;
7622 }
7623
7624 unsigned Idx = 0;
7625 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7626}
7627
Guy Benyei11169dd2012-12-18 14:30:41 +00007628CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007629 assert(ContextObj && "reading base specifiers with no AST context");
7630 ASTContext &Context = *ContextObj;
7631
Guy Benyei11169dd2012-12-18 14:30:41 +00007632 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007633 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007635 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7636 Error(std::move(Err));
7637 return nullptr;
7638 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 ReadingKindTracker ReadingKind(Read_Decl, *this);
7640 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007641
7642 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7643 if (!MaybeCode) {
7644 Error(MaybeCode.takeError());
7645 return nullptr;
7646 }
7647 unsigned Code = MaybeCode.get();
7648
7649 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7650 if (!MaybeRecCode) {
7651 Error(MaybeCode.takeError());
7652 return nullptr;
7653 }
7654 unsigned RecCode = MaybeRecCode.get();
7655
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007657 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007658 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 }
7660
7661 unsigned Idx = 0;
7662 unsigned NumBases = Record[Idx++];
7663 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007664 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007665 for (unsigned I = 0; I != NumBases; ++I)
7666 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7667 return Bases;
7668}
7669
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007670serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007671ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7672 if (LocalID < NUM_PREDEF_DECL_IDS)
7673 return LocalID;
7674
Richard Smith37a93df2017-02-18 00:32:02 +00007675 if (!F.ModuleOffsetMap.empty())
7676 ReadModuleOffsetMap(F);
7677
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7679 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7680 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007681
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 return LocalID + I->second;
7683}
7684
7685bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7686 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007687 // Predefined decls aren't from any module.
7688 if (ID < NUM_PREDEF_DECL_IDS)
7689 return false;
7690
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007691 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007692 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007693}
7694
Douglas Gregor9f782892013-01-21 15:25:38 +00007695ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007697 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007698 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7699 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7700 return I->second;
7701}
7702
7703SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7704 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007705 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007706
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7708
7709 if (Index > DeclsLoaded.size()) {
7710 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007711 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007713
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 if (Decl *D = DeclsLoaded[Index])
7715 return D->getLocation();
7716
Richard Smithcb34bd32016-03-27 07:28:06 +00007717 SourceLocation Loc;
7718 DeclCursorForID(ID, Loc);
7719 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007720}
7721
Richard Smithfe620d22015-03-05 23:24:12 +00007722static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7723 switch (ID) {
7724 case PREDEF_DECL_NULL_ID:
7725 return nullptr;
7726
7727 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7728 return Context.getTranslationUnitDecl();
7729
7730 case PREDEF_DECL_OBJC_ID_ID:
7731 return Context.getObjCIdDecl();
7732
7733 case PREDEF_DECL_OBJC_SEL_ID:
7734 return Context.getObjCSelDecl();
7735
7736 case PREDEF_DECL_OBJC_CLASS_ID:
7737 return Context.getObjCClassDecl();
7738
7739 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7740 return Context.getObjCProtocolDecl();
7741
7742 case PREDEF_DECL_INT_128_ID:
7743 return Context.getInt128Decl();
7744
7745 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7746 return Context.getUInt128Decl();
7747
7748 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7749 return Context.getObjCInstanceTypeDecl();
7750
7751 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7752 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007753
Richard Smith9b88a4c2015-07-27 05:40:23 +00007754 case PREDEF_DECL_VA_LIST_TAG:
7755 return Context.getVaListTagDecl();
7756
Charles Davisc7d5c942015-09-17 20:55:33 +00007757 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7758 return Context.getBuiltinMSVaListDecl();
7759
Richard Smithf19e1272015-03-07 00:04:49 +00007760 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7761 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007762
7763 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7764 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007765
7766 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7767 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007768
7769 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7770 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007771
7772 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7773 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007774 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007775 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007776}
7777
Richard Smithcd45dbc2014-04-19 03:48:30 +00007778Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007779 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007780 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007781 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007782 if (D) {
7783 // Track that we have merged the declaration with ID \p ID into the
7784 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007785 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007786 if (Merged.empty())
7787 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 }
Richard Smithfe620d22015-03-05 23:24:12 +00007789 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007791
Guy Benyei11169dd2012-12-18 14:30:41 +00007792 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7793
7794 if (Index >= DeclsLoaded.size()) {
7795 assert(0 && "declaration ID out-of-range for AST file");
7796 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007797 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007799
7800 return DeclsLoaded[Index];
7801}
7802
7803Decl *ASTReader::GetDecl(DeclID ID) {
7804 if (ID < NUM_PREDEF_DECL_IDS)
7805 return GetExistingDecl(ID);
7806
7807 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7808
7809 if (Index >= DeclsLoaded.size()) {
7810 assert(0 && "declaration ID out-of-range for AST file");
7811 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007812 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007813 }
7814
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 if (!DeclsLoaded[Index]) {
7816 ReadDeclRecord(ID);
7817 if (DeserializationListener)
7818 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7819 }
7820
7821 return DeclsLoaded[Index];
7822}
7823
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007824DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 DeclID GlobalID) {
7826 if (GlobalID < NUM_PREDEF_DECL_IDS)
7827 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007828
Guy Benyei11169dd2012-12-18 14:30:41 +00007829 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7830 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7831 ModuleFile *Owner = I->second;
7832
7833 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7834 = M.GlobalToLocalDeclIDs.find(Owner);
7835 if (Pos == M.GlobalToLocalDeclIDs.end())
7836 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007837
Guy Benyei11169dd2012-12-18 14:30:41 +00007838 return GlobalID - Owner->BaseDeclID + Pos->second;
7839}
7840
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007841serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007842 const RecordData &Record,
7843 unsigned &Idx) {
7844 if (Idx >= Record.size()) {
7845 Error("Corrupted AST file");
7846 return 0;
7847 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007848
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 return getGlobalDeclID(F, Record[Idx++]);
7850}
7851
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007852/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007853///
7854/// This operation will read a new statement from the external
7855/// source each time it is called, and is meant to be used via a
7856/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7857Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7858 // Switch case IDs are per Decl.
7859 ClearSwitchCaseIDs();
7860
7861 // Offset here is a global offset across the entire chain.
7862 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007863 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7864 Error(std::move(Err));
7865 return nullptr;
7866 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007867 assert(NumCurrentElementsDeserializing == 0 &&
7868 "should not be called while already deserializing");
7869 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 return ReadStmtFromStream(*Loc.F);
7871}
7872
Richard Smith3cb15722015-08-05 22:41:45 +00007873void ASTReader::FindExternalLexicalDecls(
7874 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7875 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007876 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7877
Richard Smith9ccdd932015-08-06 22:14:12 +00007878 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007879 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7880 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7881 auto K = (Decl::Kind)+LexicalDecls[I];
7882 if (!IsKindWeWant(K))
7883 continue;
7884
7885 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7886
7887 // Don't add predefined declarations to the lexical context more
7888 // than once.
7889 if (ID < NUM_PREDEF_DECL_IDS) {
7890 if (PredefsVisited[ID])
7891 continue;
7892
7893 PredefsVisited[ID] = true;
7894 }
7895
7896 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007897 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007898 if (!DC->isDeclInLexicalTraversal(D))
7899 Decls.push_back(D);
7900 }
7901 }
7902 };
7903
7904 if (isa<TranslationUnitDecl>(DC)) {
7905 for (auto Lexical : TULexicalDecls)
7906 Visit(Lexical.first, Lexical.second);
7907 } else {
7908 auto I = LexicalDecls.find(DC);
7909 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007910 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007911 }
7912
Guy Benyei11169dd2012-12-18 14:30:41 +00007913 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007914}
7915
7916namespace {
7917
7918class DeclIDComp {
7919 ASTReader &Reader;
7920 ModuleFile &Mod;
7921
7922public:
7923 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7924
7925 bool operator()(LocalDeclID L, LocalDeclID R) const {
7926 SourceLocation LHS = getLocation(L);
7927 SourceLocation RHS = getLocation(R);
7928 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7929 }
7930
7931 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7932 SourceLocation RHS = getLocation(R);
7933 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7934 }
7935
7936 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7937 SourceLocation LHS = getLocation(L);
7938 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7939 }
7940
7941 SourceLocation getLocation(LocalDeclID ID) const {
7942 return Reader.getSourceManager().getFileLoc(
7943 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7944 }
7945};
7946
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007947} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007948
7949void ASTReader::FindFileRegionDecls(FileID File,
7950 unsigned Offset, unsigned Length,
7951 SmallVectorImpl<Decl *> &Decls) {
7952 SourceManager &SM = getSourceManager();
7953
7954 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7955 if (I == FileDeclIDs.end())
7956 return;
7957
7958 FileDeclsInfo &DInfo = I->second;
7959 if (DInfo.Decls.empty())
7960 return;
7961
7962 SourceLocation
7963 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7964 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7965
7966 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007967 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7968 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 if (BeginIt != DInfo.Decls.begin())
7970 --BeginIt;
7971
7972 // If we are pointing at a top-level decl inside an objc container, we need
7973 // to backtrack until we find it otherwise we will fail to report that the
7974 // region overlaps with an objc container.
7975 while (BeginIt != DInfo.Decls.begin() &&
7976 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7977 ->isTopLevelDeclInObjCContainer())
7978 --BeginIt;
7979
Fangrui Song7264a472019-07-03 08:13:17 +00007980 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7981 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 if (EndIt != DInfo.Decls.end())
7983 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007984
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 for (ArrayRef<serialization::LocalDeclID>::iterator
7986 DIt = BeginIt; DIt != EndIt; ++DIt)
7987 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7988}
7989
Richard Smith9ce12e32013-02-07 03:30:24 +00007990bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007991ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7992 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007993 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 "DeclContext has no visible decls in storage");
7995 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007996 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997
Richard Smithd88a7f12015-09-01 20:35:42 +00007998 auto It = Lookups.find(DC);
7999 if (It == Lookups.end())
8000 return false;
8001
Richard Smith8c913ec2014-08-14 02:21:01 +00008002 Deserializing LookupResults(this);
8003
Richard Smithd88a7f12015-09-01 20:35:42 +00008004 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008006 for (DeclID ID : It->second.Table.find(Name)) {
8007 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008008 if (ND->getDeclName() == Name)
8009 Decls.push_back(ND);
8010 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008011
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 ++NumVisibleDeclContextsRead;
8013 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00008014 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008015}
8016
Guy Benyei11169dd2012-12-18 14:30:41 +00008017void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8018 if (!DC->hasExternalVisibleStorage())
8019 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00008020
8021 auto It = Lookups.find(DC);
8022 assert(It != Lookups.end() &&
8023 "have external visible storage but no lookup tables");
8024
Craig Topper79be4cd2013-07-05 04:33:53 +00008025 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00008026
Vedant Kumar48b4f762018-04-14 01:40:48 +00008027 for (DeclID ID : It->second.Table.findAll()) {
8028 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008029 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 }
8031
Guy Benyei11169dd2012-12-18 14:30:41 +00008032 ++NumVisibleDeclContextsRead;
8033
Vedant Kumar48b4f762018-04-14 01:40:48 +00008034 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8035 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008037 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8038}
8039
Richard Smithd88a7f12015-09-01 20:35:42 +00008040const serialization::reader::DeclContextLookupTable *
8041ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8042 auto I = Lookups.find(Primary);
8043 return I == Lookups.end() ? nullptr : &I->second;
8044}
8045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008046/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00008047/// before receiving the implementation, and codegen depends on this.
8048/// We simulate this by deserializing and passing to consumer the methods of the
8049/// implementation before passing the deserialized implementation decl.
8050static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8051 ASTConsumer *Consumer) {
8052 assert(ImplD && Consumer);
8053
Aaron Ballmanaff18c02014-03-13 19:03:34 +00008054 for (auto *I : ImplD->methods())
8055 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00008056
8057 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8058}
8059
Guy Benyei11169dd2012-12-18 14:30:41 +00008060void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008061 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 PassObjCImplDeclToConsumer(ImplD, Consumer);
8063 else
8064 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8065}
8066
8067void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8068 this->Consumer = Consumer;
8069
Richard Smith9e2341d2015-03-23 03:25:59 +00008070 if (Consumer)
8071 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00008072
8073 if (DeserializationListener)
8074 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00008075}
8076
8077void ASTReader::PrintStats() {
8078 std::fprintf(stderr, "*** AST File Statistics:\n");
8079
8080 unsigned NumTypesLoaded
8081 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
8082 QualType());
8083 unsigned NumDeclsLoaded
8084 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008085 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 unsigned NumIdentifiersLoaded
8087 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
8088 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008089 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 unsigned NumMacrosLoaded
8091 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
8092 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008093 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 unsigned NumSelectorsLoaded
8095 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
8096 SelectorsLoaded.end(),
8097 Selector());
8098
8099 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8100 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8101 NumSLocEntriesRead, TotalNumSLocEntries,
8102 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8103 if (!TypesLoaded.empty())
8104 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8105 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8106 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8107 if (!DeclsLoaded.empty())
8108 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8109 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8110 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8111 if (!IdentifiersLoaded.empty())
8112 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8113 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8114 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8115 if (!MacrosLoaded.empty())
8116 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8117 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8118 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8119 if (!SelectorsLoaded.empty())
8120 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8121 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8122 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8123 if (TotalNumStatements)
8124 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8125 NumStatementsRead, TotalNumStatements,
8126 ((float)NumStatementsRead/TotalNumStatements * 100));
8127 if (TotalNumMacros)
8128 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8129 NumMacrosRead, TotalNumMacros,
8130 ((float)NumMacrosRead/TotalNumMacros * 100));
8131 if (TotalLexicalDeclContexts)
8132 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8133 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8134 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8135 * 100));
8136 if (TotalVisibleDeclContexts)
8137 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8138 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8139 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8140 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008141 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00008142 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8143 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8144 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8145 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008146 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008147 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8148 NumMethodPoolHits, NumMethodPoolLookups,
8149 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008150 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008151 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8152 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8153 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8154 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008155 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00008156 std::fprintf(stderr,
8157 " %u / %u identifier table lookups succeeded (%f%%)\n",
8158 NumIdentifierLookupHits, NumIdentifierLookups,
8159 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00008160
Douglas Gregore060e572013-01-25 01:03:03 +00008161 if (GlobalIndex) {
8162 std::fprintf(stderr, "\n");
8163 GlobalIndex->printStats();
8164 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008165
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 std::fprintf(stderr, "\n");
8167 dump();
8168 std::fprintf(stderr, "\n");
8169}
8170
8171template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00008172LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00008173dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008174 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 InitialCapacity> &Map) {
8176 if (Map.begin() == Map.end())
8177 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008178
Vedant Kumar48b4f762018-04-14 01:40:48 +00008179 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8180
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008182 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8183 I != IEnd; ++I) {
8184 llvm::errs() << " " << I->first << " -> " << I->second->FileName
8185 << "\n";
8186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008187}
8188
Yaron Kerencdae9412016-01-29 19:38:18 +00008189LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00008190 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8191 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8192 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8193 dumpModuleIDMap("Global type map", GlobalTypeMap);
8194 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8195 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8196 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8197 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8198 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008199 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008201
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008203 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00008204 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00008205}
8206
8207/// Return the amount of memory used by memory buffers, breaking down
8208/// by heap-backed versus mmap'ed memory.
8209void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008210 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00008211 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008212 size_t bytes = buf->getBufferSize();
8213 switch (buf->getBufferKind()) {
8214 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8215 sizes.malloc_bytes += bytes;
8216 break;
8217 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8218 sizes.mmap_bytes += bytes;
8219 break;
8220 }
8221 }
8222 }
8223}
8224
8225void ASTReader::InitializeSema(Sema &S) {
8226 SemaObj = &S;
8227 S.addExternalSource(this);
8228
8229 // Makes sure any declarations that were deserialized "too early"
8230 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008231 for (uint64_t ID : PreloadedDeclIDs) {
8232 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00008233 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008235 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008236
Richard Smith3d8e97e2013-10-18 06:54:39 +00008237 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 if (!FPPragmaOptions.empty()) {
8239 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00008240 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 }
8242
Yaxun Liu5b746652016-12-18 05:18:55 +00008243 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
8244 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
8245 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00008246
8247 UpdateSema();
8248}
8249
8250void ASTReader::UpdateSema() {
8251 assert(SemaObj && "no Sema to update");
8252
8253 // Load the offsets of the declarations that Sema references.
8254 // They will be lazily deserialized when needed.
8255 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00008256 assert(SemaDeclRefs.size() % 3 == 0);
8257 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00008258 if (!SemaObj->StdNamespace)
8259 SemaObj->StdNamespace = SemaDeclRefs[I];
8260 if (!SemaObj->StdBadAlloc)
8261 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00008262 if (!SemaObj->StdAlignValT)
8263 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00008264 }
8265 SemaDeclRefs.clear();
8266 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00008267
Nico Weber779355f2016-03-02 23:22:00 +00008268 // Update the state of pragmas. Use the same API as if we had encountered the
8269 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00008270 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00008271 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00008272 if (PragmaMSStructState != -1)
8273 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00008274 if (PointersToMembersPragmaLocation.isValid()) {
8275 SemaObj->ActOnPragmaMSPointersToMembers(
8276 (LangOptions::PragmaMSPointersToMembersKind)
8277 PragmaMSPointersToMembersState,
8278 PointersToMembersPragmaLocation);
8279 }
Justin Lebar67a78a62016-10-08 22:15:58 +00008280 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008281
8282 if (PragmaPackCurrentValue) {
8283 // The bottom of the stack might have a default value. It must be adjusted
8284 // to the current value to ensure that the packing state is preserved after
8285 // popping entries that were included/imported from a PCH/module.
8286 bool DropFirst = false;
8287 if (!PragmaPackStack.empty() &&
8288 PragmaPackStack.front().Location.isInvalid()) {
8289 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
8290 "Expected a default alignment value");
8291 SemaObj->PackStack.Stack.emplace_back(
8292 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00008293 SemaObj->PackStack.CurrentPragmaLocation,
8294 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008295 DropFirst = true;
8296 }
8297 for (const auto &Entry :
8298 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
8299 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00008300 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008301 if (PragmaPackCurrentLocation.isInvalid()) {
8302 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
8303 "Expected a default alignment value");
8304 // Keep the current values.
8305 } else {
8306 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
8307 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
8308 }
8309 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008310}
8311
Richard Smitha8d5b6a2015-07-17 19:51:03 +00008312IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008313 // Note that we are loading an identifier.
8314 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00008315
Douglas Gregor7211ac12013-01-25 23:32:03 +00008316 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00008317 NumIdentifierLookups,
8318 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008319
8320 // We don't need to do identifier table lookups in C++ modules (we preload
8321 // all interesting declarations, and don't need to use the scope for name
8322 // lookups). Perform the lookup in PCH files, though, since we don't build
8323 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00008324 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00008325 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008326 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00008327 break;
8328 } else {
8329 // If there is a global index, look there first to determine which modules
8330 // provably do not have any results for this identifier.
8331 GlobalModuleIndex::HitSet Hits;
8332 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8333 if (!loadGlobalIndex()) {
8334 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8335 HitsPtr = &Hits;
8336 }
8337 }
8338
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008339 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008340 }
8341
Guy Benyei11169dd2012-12-18 14:30:41 +00008342 IdentifierInfo *II = Visitor.getIdentifierInfo();
8343 markIdentifierUpToDate(II);
8344 return II;
8345}
8346
8347namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008349 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 /// identifiers stored within a set of AST files.
8351 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008352 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 const ASTReader &Reader;
8354
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008355 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 /// the AST reader.
8357 unsigned Index;
8358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008359 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 /// of the current AST file.
8361 ASTIdentifierLookupTable::key_iterator Current;
8362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008363 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 /// the current AST file.
8365 ASTIdentifierLookupTable::key_iterator End;
8366
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008367 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00008368 bool SkipModules;
8369
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00008371 explicit ASTIdentifierIterator(const ASTReader &Reader,
8372 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00008373
Craig Topper3e89dfe2014-03-13 02:13:41 +00008374 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008376
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008377} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008378
Ben Langmuir537c5b52016-05-04 00:53:13 +00008379ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8380 bool SkipModules)
8381 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008382}
8383
8384StringRef ASTIdentifierIterator::Next() {
8385 while (Current == End) {
8386 // If we have exhausted all of our AST files, we're done.
8387 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008388 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008389
8390 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008391 ModuleFile &F = Reader.ModuleMgr[Index];
8392 if (SkipModules && F.isModule())
8393 continue;
8394
Vedant Kumar48b4f762018-04-14 01:40:48 +00008395 ASTIdentifierLookupTable *IdTable =
8396 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 Current = IdTable->key_begin();
8398 End = IdTable->key_end();
8399 }
8400
8401 // We have any identifiers remaining in the current AST file; return
8402 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008403 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008404 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008405 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008406}
8407
Ben Langmuir537c5b52016-05-04 00:53:13 +00008408namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008409
Ben Langmuir537c5b52016-05-04 00:53:13 +00008410/// A utility for appending two IdentifierIterators.
8411class ChainedIdentifierIterator : public IdentifierIterator {
8412 std::unique_ptr<IdentifierIterator> Current;
8413 std::unique_ptr<IdentifierIterator> Queued;
8414
8415public:
8416 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8417 std::unique_ptr<IdentifierIterator> Second)
8418 : Current(std::move(First)), Queued(std::move(Second)) {}
8419
8420 StringRef Next() override {
8421 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008422 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008423
8424 StringRef result = Current->Next();
8425 if (!result.empty())
8426 return result;
8427
8428 // Try the queued iterator, which may itself be empty.
8429 Current.reset();
8430 std::swap(Current, Queued);
8431 return Next();
8432 }
8433};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008434
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008435} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008436
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008437IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008438 if (!loadGlobalIndex()) {
8439 std::unique_ptr<IdentifierIterator> ReaderIter(
8440 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8441 std::unique_ptr<IdentifierIterator> ModulesIter(
8442 GlobalIndex->createIdentifierIterator());
8443 return new ChainedIdentifierIterator(std::move(ReaderIter),
8444 std::move(ModulesIter));
8445 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008446
Guy Benyei11169dd2012-12-18 14:30:41 +00008447 return new ASTIdentifierIterator(*this);
8448}
8449
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008450namespace clang {
8451namespace serialization {
8452
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 class ReadMethodPoolVisitor {
8454 ASTReader &Reader;
8455 Selector Sel;
8456 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008457 unsigned InstanceBits = 0;
8458 unsigned FactoryBits = 0;
8459 bool InstanceHasMoreThanOneDecl = false;
8460 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008461 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8462 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008463
8464 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008465 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008467 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008468
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008469 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 if (!M.SelectorLookupTable)
8471 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008472
Guy Benyei11169dd2012-12-18 14:30:41 +00008473 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008474 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008475 return true;
8476
Richard Smithbdf2d932015-07-30 03:37:16 +00008477 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008478 ASTSelectorLookupTable *PoolTable
8479 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008480 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008481 if (Pos == PoolTable->end())
8482 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008483
Richard Smithbdf2d932015-07-30 03:37:16 +00008484 ++Reader.NumMethodPoolTableHits;
8485 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008486 // FIXME: Not quite happy with the statistics here. We probably should
8487 // disable this tracking when called via LoadSelector.
8488 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008489 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008491 if (Reader.DeserializationListener)
8492 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008493
Richard Smithbdf2d932015-07-30 03:37:16 +00008494 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8495 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8496 InstanceBits = Data.InstanceBits;
8497 FactoryBits = Data.FactoryBits;
8498 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8499 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 return true;
8501 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008503 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008504 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8505 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 }
8507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008508 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008509 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008510 return FactoryMethods;
8511 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008512
8513 unsigned getInstanceBits() const { return InstanceBits; }
8514 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008515
Nico Weberff4b35e2014-12-27 22:14:15 +00008516 bool instanceHasMoreThanOneDecl() const {
8517 return InstanceHasMoreThanOneDecl;
8518 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008519
Nico Weberff4b35e2014-12-27 22:14:15 +00008520 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008521 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008522
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008523} // namespace serialization
8524} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008526/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008527static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8528 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008529 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8530 S.addMethodToGlobalList(&List, Methods[I]);
8531 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008532}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008533
Guy Benyei11169dd2012-12-18 14:30:41 +00008534void ASTReader::ReadMethodPool(Selector Sel) {
8535 // Get the selector generation and update it to the current generation.
8536 unsigned &Generation = SelectorGeneration[Sel];
8537 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008538 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008539 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008540
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008542 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008543 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008544 ModuleMgr.visit(Visitor);
8545
Guy Benyei11169dd2012-12-18 14:30:41 +00008546 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008547 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008549
8550 ++NumMethodPoolHits;
8551
Guy Benyei11169dd2012-12-18 14:30:41 +00008552 if (!getSema())
8553 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008554
Guy Benyei11169dd2012-12-18 14:30:41 +00008555 Sema &S = *getSema();
8556 Sema::GlobalMethodPool::iterator Pos
8557 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008558
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008559 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008560 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008561 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008562 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008563
8564 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8565 // when building a module we keep every method individually and may need to
8566 // update hasMoreThanOneDecl as we add the methods.
8567 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8568 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008569}
8570
Manman Rena0f31a02016-04-29 19:04:05 +00008571void ASTReader::updateOutOfDateSelector(Selector Sel) {
8572 if (SelectorOutOfDate[Sel])
8573 ReadMethodPool(Sel);
8574}
8575
Guy Benyei11169dd2012-12-18 14:30:41 +00008576void ASTReader::ReadKnownNamespaces(
8577 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8578 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008579
Vedant Kumar48b4f762018-04-14 01:40:48 +00008580 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8581 if (NamespaceDecl *Namespace
8582 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008585}
8586
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008587void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008588 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008589 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008590 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008591 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008592 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008593 Undefined.insert(std::make_pair(D, Loc));
8594 }
8595}
Nick Lewycky8334af82013-01-26 00:35:08 +00008596
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008597void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8598 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8599 Exprs) {
8600 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008601 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008602 uint64_t Count = DelayedDeleteExprs[Idx++];
8603 for (uint64_t C = 0; C < Count; ++C) {
8604 SourceLocation DeleteLoc =
8605 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8606 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8607 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8608 }
8609 }
8610}
8611
Guy Benyei11169dd2012-12-18 14:30:41 +00008612void ASTReader::ReadTentativeDefinitions(
8613 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008614 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8615 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 if (Var)
8617 TentativeDefs.push_back(Var);
8618 }
8619 TentativeDefinitions.clear();
8620}
8621
8622void ASTReader::ReadUnusedFileScopedDecls(
8623 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008624 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8625 DeclaratorDecl *D
8626 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 if (D)
8628 Decls.push_back(D);
8629 }
8630 UnusedFileScopedDecls.clear();
8631}
8632
8633void ASTReader::ReadDelegatingConstructors(
8634 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008635 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8636 CXXConstructorDecl *D
8637 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008638 if (D)
8639 Decls.push_back(D);
8640 }
8641 DelegatingCtorDecls.clear();
8642}
8643
8644void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008645 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8646 TypedefNameDecl *D
8647 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008648 if (D)
8649 Decls.push_back(D);
8650 }
8651 ExtVectorDecls.clear();
8652}
8653
Nico Weber72889432014-09-06 01:25:55 +00008654void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8655 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008656 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8657 ++I) {
8658 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8659 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008660 if (D)
8661 Decls.insert(D);
8662 }
8663 UnusedLocalTypedefNameCandidates.clear();
8664}
8665
Guy Benyei11169dd2012-12-18 14:30:41 +00008666void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008667 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008668 if (ReferencedSelectorsData.empty())
8669 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008670
Guy Benyei11169dd2012-12-18 14:30:41 +00008671 // If there are @selector references added them to its pool. This is for
8672 // implementation of -Wselector.
8673 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8674 unsigned I = 0;
8675 while (I < DataSize) {
8676 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8677 SourceLocation SelLoc
8678 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8679 Sels.push_back(std::make_pair(Sel, SelLoc));
8680 }
8681 ReferencedSelectorsData.clear();
8682}
8683
8684void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008685 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008686 if (WeakUndeclaredIdentifiers.empty())
8687 return;
8688
8689 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008690 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008691 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008692 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008693 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8694 SourceLocation Loc
8695 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8696 bool Used = WeakUndeclaredIdentifiers[I++];
8697 WeakInfo WI(AliasId, Loc);
8698 WI.setUsed(Used);
8699 WeakIDs.push_back(std::make_pair(WeakId, WI));
8700 }
8701 WeakUndeclaredIdentifiers.clear();
8702}
8703
8704void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8705 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8706 ExternalVTableUse VT;
8707 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8708 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8709 VT.DefinitionRequired = VTableUses[Idx++];
8710 VTables.push_back(VT);
8711 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008712
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 VTableUses.clear();
8714}
8715
8716void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008717 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008718 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008719 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 SourceLocation Loc
8721 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8722
8723 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008724 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008725 PendingInstantiations.clear();
8726}
8727
Richard Smithe40f2ba2013-08-07 21:41:30 +00008728void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008729 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8730 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008731 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8732 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008733 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008734
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008735 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008736 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8737
8738 ModuleFile *F = getOwningModuleFile(LT->D);
8739 assert(F && "No module");
8740
8741 unsigned TokN = LateParsedTemplates[Idx++];
8742 LT->Toks.reserve(TokN);
8743 for (unsigned T = 0; T < TokN; ++T)
8744 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8745
Justin Lebar28f09c52016-10-10 16:26:08 +00008746 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008747 }
8748
8749 LateParsedTemplates.clear();
8750}
8751
Guy Benyei11169dd2012-12-18 14:30:41 +00008752void ASTReader::LoadSelector(Selector Sel) {
8753 // It would be complicated to avoid reading the methods anyway. So don't.
8754 ReadMethodPool(Sel);
8755}
8756
8757void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8758 assert(ID && "Non-zero identifier ID required");
8759 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8760 IdentifiersLoaded[ID - 1] = II;
8761 if (DeserializationListener)
8762 DeserializationListener->IdentifierRead(ID, II);
8763}
8764
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008765/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008766/// identifier.
8767///
8768/// If the AST reader is currently in a state where the given declaration IDs
8769/// cannot safely be resolved, they are queued until it is safe to resolve
8770/// them.
8771///
8772/// \param II an IdentifierInfo that refers to one or more globally-visible
8773/// declarations.
8774///
8775/// \param DeclIDs the set of declaration IDs with the name @p II that are
8776/// visible at global scope.
8777///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008778/// \param Decls if non-null, this vector will be populated with the set of
8779/// deserialized declarations. These declarations will not be pushed into
8780/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008781void
8782ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8783 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008784 SmallVectorImpl<Decl *> *Decls) {
8785 if (NumCurrentElementsDeserializing && !Decls) {
8786 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008787 return;
8788 }
8789
Vedant Kumar48b4f762018-04-14 01:40:48 +00008790 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008791 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008792 // Queue this declaration so that it will be added to the
8793 // translation unit scope and identifier's declaration chain
8794 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008795 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008796 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008797 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008798
Vedant Kumar48b4f762018-04-14 01:40:48 +00008799 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008800
8801 // If we're simply supposed to record the declarations, do so now.
8802 if (Decls) {
8803 Decls->push_back(D);
8804 continue;
8805 }
8806
8807 // Introduce this declaration into the translation-unit scope
8808 // and add it to the declaration chain for this identifier, so
8809 // that (unqualified) name lookup will find it.
8810 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 }
8812}
8813
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008814IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008815 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008816 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008817
8818 if (IdentifiersLoaded.empty()) {
8819 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008820 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008821 }
8822
8823 ID -= 1;
8824 if (!IdentifiersLoaded[ID]) {
8825 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8826 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8827 ModuleFile *M = I->second;
8828 unsigned Index = ID - M->BaseIdentifierID;
8829 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8830
8831 // All of the strings in the AST file are preceded by a 16-bit length.
8832 // Extract that 16-bit length to avoid having to execute strlen().
8833 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8834 // unsigned integers. This is important to avoid integer overflow when
8835 // we cast them to 'unsigned'.
8836 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8837 unsigned StrLen = (((unsigned) StrLenPtr[0])
8838 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008839 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8840 IdentifiersLoaded[ID] = &II;
8841 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008842 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008843 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008844 }
8845
8846 return IdentifiersLoaded[ID];
8847}
8848
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008849IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8850 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008851}
8852
8853IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8854 if (LocalID < NUM_PREDEF_IDENT_IDS)
8855 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008856
Richard Smith37a93df2017-02-18 00:32:02 +00008857 if (!M.ModuleOffsetMap.empty())
8858 ReadModuleOffsetMap(M);
8859
Guy Benyei11169dd2012-12-18 14:30:41 +00008860 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8861 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008862 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008863 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008864
Guy Benyei11169dd2012-12-18 14:30:41 +00008865 return LocalID + I->second;
8866}
8867
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008868MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008869 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008870 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008871
8872 if (MacrosLoaded.empty()) {
8873 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008874 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008875 }
8876
8877 ID -= NUM_PREDEF_MACRO_IDS;
8878 if (!MacrosLoaded[ID]) {
8879 GlobalMacroMapType::iterator I
8880 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8881 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8882 ModuleFile *M = I->second;
8883 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008884 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008885
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008886 if (DeserializationListener)
8887 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8888 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008889 }
8890
8891 return MacrosLoaded[ID];
8892}
8893
8894MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8895 if (LocalID < NUM_PREDEF_MACRO_IDS)
8896 return LocalID;
8897
Richard Smith37a93df2017-02-18 00:32:02 +00008898 if (!M.ModuleOffsetMap.empty())
8899 ReadModuleOffsetMap(M);
8900
Guy Benyei11169dd2012-12-18 14:30:41 +00008901 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8902 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8903 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8904
8905 return LocalID + I->second;
8906}
8907
8908serialization::SubmoduleID
8909ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8910 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8911 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008912
Richard Smith37a93df2017-02-18 00:32:02 +00008913 if (!M.ModuleOffsetMap.empty())
8914 ReadModuleOffsetMap(M);
8915
Guy Benyei11169dd2012-12-18 14:30:41 +00008916 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8917 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008918 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008919 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008920
Guy Benyei11169dd2012-12-18 14:30:41 +00008921 return LocalID + I->second;
8922}
8923
8924Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8925 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8926 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008927 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008928 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008929
Guy Benyei11169dd2012-12-18 14:30:41 +00008930 if (GlobalID > SubmodulesLoaded.size()) {
8931 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008932 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008933 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008934
Guy Benyei11169dd2012-12-18 14:30:41 +00008935 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8936}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008937
8938Module *ASTReader::getModule(unsigned ID) {
8939 return getSubmodule(ID);
8940}
8941
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008942bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8943 ModuleFile *MF = getOwningModuleFile(D);
8944 return MF && MF->PCHHasObjectFile;
8945}
8946
Richard Smithd88a7f12015-09-01 20:35:42 +00008947ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8948 if (ID & 1) {
8949 // It's a module, look it up by submodule ID.
8950 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8951 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8952 } else {
8953 // It's a prefix (preamble, PCH, ...). Look it up by index.
8954 unsigned IndexFromEnd = ID >> 1;
8955 assert(IndexFromEnd && "got reference to unknown module file");
8956 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8957 }
8958}
8959
8960unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8961 if (!F)
8962 return 1;
8963
8964 // For a file representing a module, use the submodule ID of the top-level
8965 // module as the file ID. For any other kind of file, the number of such
8966 // files loaded beforehand will be the same on reload.
8967 // FIXME: Is this true even if we have an explicit module file and a PCH?
8968 if (F->isModule())
8969 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8970
8971 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008972 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008973 assert(I != PCHModules.end() && "emitting reference to unknown file");
8974 return (I - PCHModules.end()) << 1;
8975}
8976
Adrian Prantl15bcf702015-06-30 17:39:43 +00008977llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8978ASTReader::getSourceDescriptor(unsigned ID) {
8979 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008980 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008981
8982 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008983 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008984 const auto &PCHChain = ModuleMgr.pch_modules();
8985 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008986 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008987 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008988 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8989 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8990 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008991 }
8992 return None;
8993}
8994
David Blaikie1ac9c982017-04-11 21:13:37 +00008995ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008996 auto I = DefinitionSource.find(FD);
8997 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008998 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008999 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00009000}
9001
Guy Benyei11169dd2012-12-18 14:30:41 +00009002Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
9003 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9004}
9005
9006Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9007 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009008 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009009
9010 if (ID > SelectorsLoaded.size()) {
9011 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009012 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009013 }
9014
Craig Toppera13603a2014-05-22 05:54:18 +00009015 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009016 // Load this selector from the selector table.
9017 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9018 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9019 ModuleFile &M = *I->second;
9020 ASTSelectorLookupTrait Trait(*this, M);
9021 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9022 SelectorsLoaded[ID - 1] =
9023 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9024 if (DeserializationListener)
9025 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9026 }
9027
9028 return SelectorsLoaded[ID - 1];
9029}
9030
9031Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9032 return DecodeSelector(ID);
9033}
9034
9035uint32_t ASTReader::GetNumExternalSelectors() {
9036 // ID 0 (the null selector) is considered an external selector.
9037 return getTotalNumSelectors() + 1;
9038}
9039
9040serialization::SelectorID
9041ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9042 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9043 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009044
Richard Smith37a93df2017-02-18 00:32:02 +00009045 if (!M.ModuleOffsetMap.empty())
9046 ReadModuleOffsetMap(M);
9047
Guy Benyei11169dd2012-12-18 14:30:41 +00009048 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9049 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009050 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00009051 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009052
Guy Benyei11169dd2012-12-18 14:30:41 +00009053 return LocalID + I->second;
9054}
9055
9056DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009057ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009058 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009059 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009060 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009061 switch (Kind) {
9062 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00009063 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009064
9065 case DeclarationName::ObjCZeroArgSelector:
9066 case DeclarationName::ObjCOneArgSelector:
9067 case DeclarationName::ObjCMultiArgSelector:
9068 return DeclarationName(ReadSelector(F, Record, Idx));
9069
9070 case DeclarationName::CXXConstructorName:
9071 return Context.DeclarationNames.getCXXConstructorName(
9072 Context.getCanonicalType(readType(F, Record, Idx)));
9073
9074 case DeclarationName::CXXDestructorName:
9075 return Context.DeclarationNames.getCXXDestructorName(
9076 Context.getCanonicalType(readType(F, Record, Idx)));
9077
Richard Smith35845152017-02-07 01:37:30 +00009078 case DeclarationName::CXXDeductionGuideName:
9079 return Context.DeclarationNames.getCXXDeductionGuideName(
9080 ReadDeclAs<TemplateDecl>(F, Record, Idx));
9081
Guy Benyei11169dd2012-12-18 14:30:41 +00009082 case DeclarationName::CXXConversionFunctionName:
9083 return Context.DeclarationNames.getCXXConversionFunctionName(
9084 Context.getCanonicalType(readType(F, Record, Idx)));
9085
9086 case DeclarationName::CXXOperatorName:
9087 return Context.DeclarationNames.getCXXOperatorName(
9088 (OverloadedOperatorKind)Record[Idx++]);
9089
9090 case DeclarationName::CXXLiteralOperatorName:
9091 return Context.DeclarationNames.getCXXLiteralOperatorName(
9092 GetIdentifierInfo(F, Record, Idx));
9093
9094 case DeclarationName::CXXUsingDirective:
9095 return DeclarationName::getUsingDirectiveName();
9096 }
9097
9098 llvm_unreachable("Invalid NameKind!");
9099}
9100
9101void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
9102 DeclarationNameLoc &DNLoc,
9103 DeclarationName Name,
9104 const RecordData &Record, unsigned &Idx) {
9105 switch (Name.getNameKind()) {
9106 case DeclarationName::CXXConstructorName:
9107 case DeclarationName::CXXDestructorName:
9108 case DeclarationName::CXXConversionFunctionName:
9109 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
9110 break;
9111
9112 case DeclarationName::CXXOperatorName:
9113 DNLoc.CXXOperatorName.BeginOpNameLoc
9114 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9115 DNLoc.CXXOperatorName.EndOpNameLoc
9116 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9117 break;
9118
9119 case DeclarationName::CXXLiteralOperatorName:
9120 DNLoc.CXXLiteralOperatorName.OpNameLoc
9121 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9122 break;
9123
9124 case DeclarationName::Identifier:
9125 case DeclarationName::ObjCZeroArgSelector:
9126 case DeclarationName::ObjCOneArgSelector:
9127 case DeclarationName::ObjCMultiArgSelector:
9128 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00009129 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00009130 break;
9131 }
9132}
9133
9134void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
9135 DeclarationNameInfo &NameInfo,
9136 const RecordData &Record, unsigned &Idx) {
9137 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
9138 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
9139 DeclarationNameLoc DNLoc;
9140 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
9141 NameInfo.setInfo(DNLoc);
9142}
9143
9144void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
9145 const RecordData &Record, unsigned &Idx) {
9146 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
9147 unsigned NumTPLists = Record[Idx++];
9148 Info.NumTemplParamLists = NumTPLists;
9149 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009150 Info.TemplParamLists =
9151 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00009152 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00009153 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
9154 }
9155}
9156
9157TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009158ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009159 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009160 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009161 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009162 switch (Kind) {
9163 case TemplateName::Template:
9164 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
9165
9166 case TemplateName::OverloadedTemplate: {
9167 unsigned size = Record[Idx++];
9168 UnresolvedSet<8> Decls;
9169 while (size--)
9170 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
9171
9172 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
9173 }
9174
Richard Smithb23c5e82019-05-09 03:31:27 +00009175 case TemplateName::AssumedTemplate: {
9176 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
9177 return Context.getAssumedTemplateName(Name);
9178 }
9179
Guy Benyei11169dd2012-12-18 14:30:41 +00009180 case TemplateName::QualifiedTemplate: {
9181 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9182 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009183 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009184 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
9185 }
9186
9187 case TemplateName::DependentTemplate: {
9188 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9189 if (Record[Idx++]) // isIdentifier
9190 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009191 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009192 Idx));
9193 return Context.getDependentTemplateName(NNS,
9194 (OverloadedOperatorKind)Record[Idx++]);
9195 }
9196
9197 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009198 TemplateTemplateParmDecl *param
9199 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
9200 if (!param) return TemplateName();
9201 TemplateName replacement = ReadTemplateName(F, Record, Idx);
9202 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00009203 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009204
Guy Benyei11169dd2012-12-18 14:30:41 +00009205 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009206 TemplateTemplateParmDecl *Param
9207 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009208 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009209 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009210
Guy Benyei11169dd2012-12-18 14:30:41 +00009211 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
9212 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009213 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009214
Guy Benyei11169dd2012-12-18 14:30:41 +00009215 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
9216 }
9217 }
9218
9219 llvm_unreachable("Unhandled template name kind!");
9220}
9221
Richard Smith2bb3c342015-08-09 01:05:31 +00009222TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
9223 const RecordData &Record,
9224 unsigned &Idx,
9225 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009226 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00009227 if (Canonicalize) {
9228 // The caller wants a canonical template argument. Sometimes the AST only
9229 // wants template arguments in canonical form (particularly as the template
9230 // argument lists of template specializations) so ensure we preserve that
9231 // canonical form across serialization.
9232 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
9233 return Context.getCanonicalTemplateArgument(Arg);
9234 }
9235
Vedant Kumar48b4f762018-04-14 01:40:48 +00009236 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009237 switch (Kind) {
9238 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00009239 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00009240 case TemplateArgument::Type:
9241 return TemplateArgument(readType(F, Record, Idx));
9242 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009243 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00009244 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009245 }
9246 case TemplateArgument::NullPtr:
9247 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
9248 case TemplateArgument::Integral: {
9249 llvm::APSInt Value = ReadAPSInt(Record, Idx);
9250 QualType T = readType(F, Record, Idx);
9251 return TemplateArgument(Context, Value, T);
9252 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009253 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00009254 return TemplateArgument(ReadTemplateName(F, Record, Idx));
9255 case TemplateArgument::TemplateExpansion: {
9256 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00009257 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00009258 if (unsigned NumExpansions = Record[Idx++])
9259 NumTemplateExpansions = NumExpansions - 1;
9260 return TemplateArgument(Name, NumTemplateExpansions);
9261 }
9262 case TemplateArgument::Expression:
9263 return TemplateArgument(ReadExpr(F));
9264 case TemplateArgument::Pack: {
9265 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009266 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00009267 for (unsigned I = 0; I != NumArgs; ++I)
9268 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00009269 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00009270 }
9271 }
9272
9273 llvm_unreachable("Unhandled template argument kind!");
9274}
9275
9276TemplateParameterList *
9277ASTReader::ReadTemplateParameterList(ModuleFile &F,
9278 const RecordData &Record, unsigned &Idx) {
9279 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
9280 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
9281 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
9282
9283 unsigned NumParams = Record[Idx++];
9284 SmallVector<NamedDecl *, 16> Params;
9285 Params.reserve(NumParams);
9286 while (NumParams--)
9287 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
9288
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00009289 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00009290 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
9291 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00009292 return TemplateParams;
9293}
9294
9295void
9296ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00009297ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00009298 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00009299 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009300 unsigned NumTemplateArgs = Record[Idx++];
9301 TemplArgs.reserve(NumTemplateArgs);
9302 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00009303 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00009304}
9305
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009306/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00009307void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00009308 const RecordData &Record, unsigned &Idx) {
9309 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009310 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00009311 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00009312 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009313 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009314 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00009315 }
9316}
9317
9318CXXBaseSpecifier
9319ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
9320 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009321 bool isVirtual = static_cast<bool>(Record[Idx++]);
9322 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
9323 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
9324 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009325 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
9326 SourceRange Range = ReadSourceRange(F, Record, Idx);
9327 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009328 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00009329 EllipsisLoc);
9330 Result.setInheritConstructors(inheritConstructors);
9331 return Result;
9332}
9333
Richard Smithc2bb8182015-03-24 06:36:48 +00009334CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00009335ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
9336 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009337 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009338 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009339 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009340 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00009341 for (unsigned i = 0; i != NumInitializers; ++i) {
9342 TypeSourceInfo *TInfo = nullptr;
9343 bool IsBaseVirtual = false;
9344 FieldDecl *Member = nullptr;
9345 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009346
Vedant Kumar48b4f762018-04-14 01:40:48 +00009347 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009348 switch (Type) {
9349 case CTOR_INITIALIZER_BASE:
9350 TInfo = GetTypeSourceInfo(F, Record, Idx);
9351 IsBaseVirtual = Record[Idx++];
9352 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009353
Richard Smithc2bb8182015-03-24 06:36:48 +00009354 case CTOR_INITIALIZER_DELEGATING:
9355 TInfo = GetTypeSourceInfo(F, Record, Idx);
9356 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009357
Richard Smithc2bb8182015-03-24 06:36:48 +00009358 case CTOR_INITIALIZER_MEMBER:
9359 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
9360 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009361
Richard Smithc2bb8182015-03-24 06:36:48 +00009362 case CTOR_INITIALIZER_INDIRECT_MEMBER:
9363 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
9364 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009365 }
Richard Smithc2bb8182015-03-24 06:36:48 +00009366
9367 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
9368 Expr *Init = ReadExpr(F);
9369 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
9370 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00009371
9372 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00009373 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00009374 BOMInit = new (Context)
9375 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9376 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009377 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00009378 BOMInit = new (Context)
9379 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009380 else if (Member)
9381 BOMInit = new (Context)
9382 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9383 Init, RParenLoc);
9384 else
9385 BOMInit = new (Context)
9386 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9387 LParenLoc, Init, RParenLoc);
9388
Richard Smith418ed822016-12-14 19:45:03 +00009389 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00009390 unsigned SourceOrder = Record[Idx++];
9391 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00009392 }
9393
Richard Smithc2bb8182015-03-24 06:36:48 +00009394 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00009395 }
9396
Richard Smithc2bb8182015-03-24 06:36:48 +00009397 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00009398}
9399
9400NestedNameSpecifier *
9401ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
9402 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009403 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009404 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00009405 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009406 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009407 NestedNameSpecifier::SpecifierKind Kind
9408 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009409 switch (Kind) {
9410 case NestedNameSpecifier::Identifier: {
9411 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
9412 NNS = NestedNameSpecifier::Create(Context, Prev, II);
9413 break;
9414 }
9415
9416 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009417 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009418 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
9419 break;
9420 }
9421
9422 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009423 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009424 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9425 break;
9426 }
9427
9428 case NestedNameSpecifier::TypeSpec:
9429 case NestedNameSpecifier::TypeSpecWithTemplate: {
9430 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9431 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009432 return nullptr;
9433
Guy Benyei11169dd2012-12-18 14:30:41 +00009434 bool Template = Record[Idx++];
9435 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9436 break;
9437 }
9438
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009439 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009440 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9441 // No associated value, and there can't be a prefix.
9442 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009443
9444 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009445 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009446 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9447 break;
9448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009449 }
9450 Prev = NNS;
9451 }
9452 return NNS;
9453}
9454
9455NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009456ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009457 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009458 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009459 unsigned N = Record[Idx++];
9460 NestedNameSpecifierLocBuilder Builder;
9461 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009462 NestedNameSpecifier::SpecifierKind Kind
9463 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009464 switch (Kind) {
9465 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009466 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009467 SourceRange Range = ReadSourceRange(F, Record, Idx);
9468 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9469 break;
9470 }
9471
9472 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009473 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009474 SourceRange Range = ReadSourceRange(F, Record, Idx);
9475 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9476 break;
9477 }
9478
9479 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009480 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009481 SourceRange Range = ReadSourceRange(F, Record, Idx);
9482 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9483 break;
9484 }
9485
9486 case NestedNameSpecifier::TypeSpec:
9487 case NestedNameSpecifier::TypeSpecWithTemplate: {
9488 bool Template = Record[Idx++];
9489 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9490 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009491 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009492 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9493
9494 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009495 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009496 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9497 T->getTypeLoc(), ColonColonLoc);
9498 break;
9499 }
9500
9501 case NestedNameSpecifier::Global: {
9502 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9503 Builder.MakeGlobal(Context, ColonColonLoc);
9504 break;
9505 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009506
9507 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009508 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009509 SourceRange Range = ReadSourceRange(F, Record, Idx);
9510 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9511 break;
9512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009513 }
9514 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009515
Guy Benyei11169dd2012-12-18 14:30:41 +00009516 return Builder.getWithLocInContext(Context);
9517}
9518
9519SourceRange
9520ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9521 unsigned &Idx) {
9522 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9523 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9524 return SourceRange(beg, end);
9525}
9526
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009527static FixedPointSemantics
9528ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9529 unsigned &Idx) {
9530 unsigned Width = Record[Idx++];
9531 unsigned Scale = Record[Idx++];
9532 uint64_t Tmp = Record[Idx++];
9533 bool IsSigned = Tmp & 0x1;
9534 bool IsSaturated = Tmp & 0x2;
9535 bool HasUnsignedPadding = Tmp & 0x4;
9536 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9537 HasUnsignedPadding);
9538}
9539
9540APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9541 unsigned Kind = Record[Idx++];
9542 switch (Kind) {
9543 case APValue::None:
9544 return APValue();
9545 case APValue::Indeterminate:
9546 return APValue::IndeterminateValue();
9547 case APValue::Int:
9548 return APValue(ReadAPSInt(Record, Idx));
9549 case APValue::Float: {
9550 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9551 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9552 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9553 }
9554 case APValue::FixedPoint: {
9555 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9556 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9557 }
9558 case APValue::ComplexInt: {
9559 llvm::APSInt First = ReadAPSInt(Record, Idx);
9560 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9561 }
9562 case APValue::ComplexFloat: {
9563 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9564 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9565 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9566 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9567 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9568 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9569 }
9570 case APValue::LValue:
9571 case APValue::Vector:
9572 case APValue::Array:
9573 case APValue::Struct:
9574 case APValue::Union:
9575 case APValue::MemberPointer:
9576 case APValue::AddrLabelDiff:
9577 // TODO : Handle all these APValue::ValueKind.
9578 return APValue();
9579 }
9580 llvm_unreachable("Invalid APValue::ValueKind");
9581}
9582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009583/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009584llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9585 unsigned BitWidth = Record[Idx++];
9586 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9587 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9588 Idx += NumWords;
9589 return Result;
9590}
9591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009592/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009593llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9594 bool isUnsigned = Record[Idx++];
9595 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9596}
9597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009598/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009599llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9600 const llvm::fltSemantics &Sem,
9601 unsigned &Idx) {
9602 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009603}
9604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009605// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009606std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9607 unsigned Len = Record[Idx++];
9608 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9609 Idx += Len;
9610 return Result;
9611}
9612
Richard Smith7ed1bc92014-12-05 22:42:13 +00009613std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9614 unsigned &Idx) {
9615 std::string Filename = ReadString(Record, Idx);
9616 ResolveImportedPath(F, Filename);
9617 return Filename;
9618}
9619
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009620std::string ASTReader::ReadPath(StringRef BaseDirectory,
9621 const RecordData &Record, unsigned &Idx) {
9622 std::string Filename = ReadString(Record, Idx);
9623 if (!BaseDirectory.empty())
9624 ResolveImportedPath(Filename, BaseDirectory);
9625 return Filename;
9626}
9627
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009628VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009629 unsigned &Idx) {
9630 unsigned Major = Record[Idx++];
9631 unsigned Minor = Record[Idx++];
9632 unsigned Subminor = Record[Idx++];
9633 if (Minor == 0)
9634 return VersionTuple(Major);
9635 if (Subminor == 0)
9636 return VersionTuple(Major, Minor - 1);
9637 return VersionTuple(Major, Minor - 1, Subminor - 1);
9638}
9639
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009640CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009641 const RecordData &Record,
9642 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009643 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009644 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009645}
9646
Richard Smith37a93df2017-02-18 00:32:02 +00009647DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009648 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009649}
9650
Richard Smith37a93df2017-02-18 00:32:02 +00009651DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009652 return Diags.Report(Loc, DiagID);
9653}
9654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009655/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009656/// preprocessor.
9657IdentifierTable &ASTReader::getIdentifierTable() {
9658 return PP.getIdentifierTable();
9659}
9660
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009661/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009662/// statement.
9663void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009664 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009665 "Already have a SwitchCase with this ID");
9666 (*CurrSwitchCaseStmts)[ID] = SC;
9667}
9668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009669/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009670SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009671 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009672 return (*CurrSwitchCaseStmts)[ID];
9673}
9674
9675void ASTReader::ClearSwitchCaseIDs() {
9676 CurrSwitchCaseStmts->clear();
9677}
9678
9679void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009680 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009681 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009682 for (SmallVectorImpl<std::pair<BitstreamCursor,
9683 serialization::ModuleFile *>>::iterator
9684 I = CommentsCursors.begin(),
9685 E = CommentsCursors.end();
9686 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009687 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009688 BitstreamCursor &Cursor = I->first;
9689 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009690 SavedStreamPosition SavedPosition(Cursor);
9691
9692 RecordData Record;
9693 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009694 Expected<llvm::BitstreamEntry> MaybeEntry =
9695 Cursor.advanceSkippingSubblocks(
9696 BitstreamCursor::AF_DontPopBlockAtEnd);
9697 if (!MaybeEntry) {
9698 Error(MaybeEntry.takeError());
9699 return;
9700 }
9701 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009702
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009703 switch (Entry.Kind) {
9704 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9705 case llvm::BitstreamEntry::Error:
9706 Error("malformed block record in AST file");
9707 return;
9708 case llvm::BitstreamEntry::EndBlock:
9709 goto NextCursor;
9710 case llvm::BitstreamEntry::Record:
9711 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009713 }
9714
9715 // Read a record.
9716 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009717 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9718 if (!MaybeComment) {
9719 Error(MaybeComment.takeError());
9720 return;
9721 }
9722 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009723 case COMMENTS_RAW_COMMENT: {
9724 unsigned Idx = 0;
9725 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009726 RawComment::CommentKind Kind =
9727 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009728 bool IsTrailingComment = Record[Idx++];
9729 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009730 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009731 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009732 break;
9733 }
9734 }
9735 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009736 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009737 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9738 FileToOffsetToComment;
9739 for (RawComment *C : Comments) {
9740 SourceLocation CommentLoc = C->getBeginLoc();
9741 if (CommentLoc.isValid()) {
9742 std::pair<FileID, unsigned> Loc =
9743 SourceMgr.getDecomposedLoc(CommentLoc);
9744 if (Loc.first.isValid())
9745 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9746 }
9747 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009748 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009749}
9750
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009751void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9752 bool IncludeSystem, bool Complain,
9753 llvm::function_ref<void(const serialization::InputFile &IF,
9754 bool isSystem)> Visitor) {
9755 unsigned NumUserInputs = MF.NumUserInputFiles;
9756 unsigned NumInputs = MF.InputFilesLoaded.size();
9757 assert(NumUserInputs <= NumInputs);
9758 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9759 for (unsigned I = 0; I < N; ++I) {
9760 bool IsSystem = I >= NumUserInputs;
9761 InputFile IF = getInputFile(MF, I+1, Complain);
9762 Visitor(IF, IsSystem);
9763 }
9764}
9765
Richard Smithf3f84612017-06-29 02:19:42 +00009766void ASTReader::visitTopLevelModuleMaps(
9767 serialization::ModuleFile &MF,
9768 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9769 unsigned NumInputs = MF.InputFilesLoaded.size();
9770 for (unsigned I = 0; I < NumInputs; ++I) {
9771 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9772 if (IFI.TopLevelModuleMap)
9773 // FIXME: This unnecessarily re-reads the InputFileInfo.
9774 if (auto *FE = getInputFile(MF, I + 1).getFile())
9775 Visitor(FE);
9776 }
9777}
9778
Richard Smithcd45dbc2014-04-19 03:48:30 +00009779std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9780 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009781 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009782 return M->getFullModuleName();
9783
9784 // Otherwise, use the name of the top-level module the decl is within.
9785 if (ModuleFile *M = getOwningModuleFile(D))
9786 return M->ModuleName;
9787
9788 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009789 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009790}
9791
Guy Benyei11169dd2012-12-18 14:30:41 +00009792void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009793 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009794 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009795 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009796 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009797 // If any identifiers with corresponding top-level declarations have
9798 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009799 using TopLevelDeclsMap =
9800 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009801 TopLevelDeclsMap TopLevelDecls;
9802
Guy Benyei11169dd2012-12-18 14:30:41 +00009803 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009804 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009805 SmallVector<uint32_t, 4> DeclIDs =
9806 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009807 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009808
9809 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009810 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009811
Richard Smitha62d1982018-08-03 01:00:01 +00009812 // Load each function type that we deferred loading because it was a
9813 // deduced type that might refer to a local type declared within itself.
9814 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9815 auto *FD = PendingFunctionTypes[I].first;
9816 FD->setType(GetType(PendingFunctionTypes[I].second));
9817
9818 // If we gave a function a deduced return type, remember that we need to
9819 // propagate that along the redeclaration chain.
9820 auto *DT = FD->getReturnType()->getContainedDeducedType();
9821 if (DT && DT->isDeduced())
9822 PendingDeducedTypeUpdates.insert(
9823 {FD->getCanonicalDecl(), FD->getReturnType()});
9824 }
9825 PendingFunctionTypes.clear();
9826
Richard Smith851072e2014-05-19 20:59:20 +00009827 // For each decl chain that we wanted to complete while deserializing, mark
9828 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009829 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9830 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9831 }
Richard Smith851072e2014-05-19 20:59:20 +00009832 PendingIncompleteDeclChains.clear();
9833
Guy Benyei11169dd2012-12-18 14:30:41 +00009834 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009835 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009836 loadPendingDeclChain(PendingDeclChains[I].first,
9837 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009838 PendingDeclChains.clear();
9839
Douglas Gregor6168bd22013-02-18 15:53:43 +00009840 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009841 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9842 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9843 IdentifierInfo *II = TLD->first;
9844 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9845 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009846 }
9847 }
9848
Guy Benyei11169dd2012-12-18 14:30:41 +00009849 // Load any pending macro definitions.
9850 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009851 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9852 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9853 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9854 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009855 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009856 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009857 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009858 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009859 resolvePendingMacro(II, Info);
9860 }
9861 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009862 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009863 ++IDIdx) {
9864 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009865 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009866 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009867 }
9868 }
9869 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009870
9871 // Wire up the DeclContexts for Decls that we delayed setting until
9872 // recursive loading is completed.
9873 while (!PendingDeclContextInfos.empty()) {
9874 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9875 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009876 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9877 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009878 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9879 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009880
Richard Smithd1c46742014-04-30 02:24:17 +00009881 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009882 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009883 auto Update = PendingUpdateRecords.pop_back_val();
9884 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009885 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009887 }
Richard Smith8a639892015-01-24 01:07:20 +00009888
9889 // At this point, all update records for loaded decls are in place, so any
9890 // fake class definitions should have become real.
9891 assert(PendingFakeDefinitionData.empty() &&
9892 "faked up a class definition but never saw the real one");
9893
Guy Benyei11169dd2012-12-18 14:30:41 +00009894 // If we deserialized any C++ or Objective-C class definitions, any
9895 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009896 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009897 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009898 for (Decl *D : PendingDefinitions) {
9899 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9900 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009901 // Make sure that the TagType points at the definition.
9902 const_cast<TagType*>(TagT)->decl = TD;
9903 }
Richard Smith8ce51082015-03-11 01:44:51 +00009904
Vedant Kumar48b4f762018-04-14 01:40:48 +00009905 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009906 for (auto *R = getMostRecentExistingDecl(RD); R;
9907 R = R->getPreviousDecl()) {
9908 assert((R == D) ==
9909 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009910 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009911 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009913 }
9914
9915 continue;
9916 }
Richard Smith8ce51082015-03-11 01:44:51 +00009917
Vedant Kumar48b4f762018-04-14 01:40:48 +00009918 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009919 // Make sure that the ObjCInterfaceType points at the definition.
9920 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9921 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009922
9923 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9924 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9925
Guy Benyei11169dd2012-12-18 14:30:41 +00009926 continue;
9927 }
Richard Smith8ce51082015-03-11 01:44:51 +00009928
Vedant Kumar48b4f762018-04-14 01:40:48 +00009929 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009930 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9931 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9932
Guy Benyei11169dd2012-12-18 14:30:41 +00009933 continue;
9934 }
Richard Smith8ce51082015-03-11 01:44:51 +00009935
Vedant Kumar48b4f762018-04-14 01:40:48 +00009936 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009937 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9938 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009939 }
9940 PendingDefinitions.clear();
9941
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009942 // Load the bodies of any functions or methods we've encountered. We do
9943 // this now (delayed) so that we can be sure that the declaration chains
9944 // have been fully wired up (hasBody relies on this).
9945 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009946 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9947 PBEnd = PendingBodies.end();
9948 PB != PBEnd; ++PB) {
9949 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009950 // For a function defined inline within a class template, force the
9951 // canonical definition to be the one inside the canonical definition of
9952 // the template. This ensures that we instantiate from a correct view
9953 // of the template.
9954 //
9955 // Sadly we can't do this more generally: we can't be sure that all
9956 // copies of an arbitrary class definition will have the same members
9957 // defined (eg, some member functions may not be instantiated, and some
9958 // special members may or may not have been implicitly defined).
9959 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9960 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9961 continue;
9962
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009963 // FIXME: Check for =delete/=default?
9964 // FIXME: Complain about ODR violations here?
9965 const FunctionDecl *Defn = nullptr;
9966 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009967 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009968 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009969 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009970 mergeDefinitionVisibility(NonConstDefn, FD);
9971
9972 if (!FD->isLateTemplateParsed() &&
9973 !NonConstDefn->isLateTemplateParsed() &&
9974 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009975 if (!isa<CXXMethodDecl>(FD)) {
9976 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9977 } else if (FD->getLexicalParent()->isFileContext() &&
9978 NonConstDefn->getLexicalParent()->isFileContext()) {
9979 // Only diagnose out-of-line method definitions. If they are
9980 // in class definitions, then an error will be generated when
9981 // processing the class bodies.
9982 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9983 }
Richard Trieue6caa262017-12-23 00:41:01 +00009984 }
9985 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009986 continue;
9987 }
9988
Vedant Kumar48b4f762018-04-14 01:40:48 +00009989 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009990 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009991 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009992 }
9993 PendingBodies.clear();
9994
Richard Smith42413142015-05-15 20:05:43 +00009995 // Do some cleanup.
9996 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9997 getContext().deduplicateMergedDefinitonsFor(ND);
9998 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009999}
10000
10001void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +000010002 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +000010003 PendingFunctionOdrMergeFailures.empty() &&
10004 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +000010005 return;
10006
Richard Smitha0ce9c42014-07-29 23:23:27 +000010007 // Trigger the import of the full definition of each class that had any
10008 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +000010009 // These updates may in turn find and diagnose some ODR failures, so take
10010 // ownership of the set first.
10011 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10012 PendingOdrMergeFailures.clear();
10013 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010014 Merge.first->buildLookup();
10015 Merge.first->decls_begin();
10016 Merge.first->bases_begin();
10017 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +000010018 for (auto &RecordPair : Merge.second) {
10019 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010020 RD->decls_begin();
10021 RD->bases_begin();
10022 RD->vbases_begin();
10023 }
10024 }
10025
Richard Trieue6caa262017-12-23 00:41:01 +000010026 // Trigger the import of functions.
10027 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10028 PendingFunctionOdrMergeFailures.clear();
10029 for (auto &Merge : FunctionOdrMergeFailures) {
10030 Merge.first->buildLookup();
10031 Merge.first->decls_begin();
10032 Merge.first->getBody();
10033 for (auto &FD : Merge.second) {
10034 FD->buildLookup();
10035 FD->decls_begin();
10036 FD->getBody();
10037 }
10038 }
10039
Richard Trieuab4d7302018-07-25 22:52:05 +000010040 // Trigger the import of enums.
10041 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10042 PendingEnumOdrMergeFailures.clear();
10043 for (auto &Merge : EnumOdrMergeFailures) {
10044 Merge.first->decls_begin();
10045 for (auto &Enum : Merge.second) {
10046 Enum->decls_begin();
10047 }
10048 }
10049
Richard Smitha0ce9c42014-07-29 23:23:27 +000010050 // For each declaration from a merged context, check that the canonical
10051 // definition of that context also contains a declaration of the same
10052 // entity.
10053 //
10054 // Caution: this loop does things that might invalidate iterators into
10055 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10056 while (!PendingOdrMergeChecks.empty()) {
10057 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10058
10059 // FIXME: Skip over implicit declarations for now. This matters for things
10060 // like implicitly-declared special member functions. This isn't entirely
10061 // correct; we can end up with multiple unmerged declarations of the same
10062 // implicit entity.
10063 if (D->isImplicit())
10064 continue;
10065
10066 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010067
10068 bool Found = false;
10069 const Decl *DCanon = D->getCanonicalDecl();
10070
Richard Smith01bdb7a2014-08-28 05:44:07 +000010071 for (auto RI : D->redecls()) {
10072 if (RI->getLexicalDeclContext() == CanonDef) {
10073 Found = true;
10074 break;
10075 }
10076 }
10077 if (Found)
10078 continue;
10079
Richard Smith0f4e2c42015-08-06 04:23:48 +000010080 // Quick check failed, time to do the slow thing. Note, we can't just
10081 // look up the name of D in CanonDef here, because the member that is
10082 // in CanonDef might not be found by name lookup (it might have been
10083 // replaced by a more recent declaration in the lookup table), and we
10084 // can't necessarily find it in the redeclaration chain because it might
10085 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010086 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +000010087 for (auto *CanonMember : CanonDef->decls()) {
10088 if (CanonMember->getCanonicalDecl() == DCanon) {
10089 // This can happen if the declaration is merely mergeable and not
10090 // actually redeclarable (we looked for redeclarations earlier).
10091 //
10092 // FIXME: We should be able to detect this more efficiently, without
10093 // pulling in all of the members of CanonDef.
10094 Found = true;
10095 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010096 }
Richard Smith0f4e2c42015-08-06 04:23:48 +000010097 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10098 if (ND->getDeclName() == D->getDeclName())
10099 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010100 }
10101
10102 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +000010103 // The AST doesn't like TagDecls becoming invalid after they've been
10104 // completed. We only really need to mark FieldDecls as invalid here.
10105 if (!isa<TagDecl>(D))
10106 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010107
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010108 // Ensure we don't accidentally recursively enter deserialization while
10109 // we're producing our diagnostic.
10110 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010111
10112 std::string CanonDefModule =
10113 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
10114 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10115 << D << getOwningModuleNameForDiagnostic(D)
10116 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10117
10118 if (Candidates.empty())
10119 Diag(cast<Decl>(CanonDef)->getLocation(),
10120 diag::note_module_odr_violation_no_possible_decls) << D;
10121 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010122 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10123 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +000010124 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +000010125 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +000010126 }
10127
10128 DiagnosedOdrMergeFailures.insert(CanonDef);
10129 }
10130 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010131
Richard Trieuab4d7302018-07-25 22:52:05 +000010132 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
10133 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010134 return;
10135
10136 // Ensure we don't accidentally recursively enter deserialization while
10137 // we're producing our diagnostics.
10138 Deserializing RecursionGuard(this);
10139
Richard Trieue6caa262017-12-23 00:41:01 +000010140 // Common code for hashing helpers.
10141 ODRHash Hash;
10142 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
10143 Hash.clear();
10144 Hash.AddQualType(Ty);
10145 return Hash.CalculateHash();
10146 };
10147
10148 auto ComputeODRHash = [&Hash](const Stmt *S) {
10149 assert(S);
10150 Hash.clear();
10151 Hash.AddStmt(S);
10152 return Hash.CalculateHash();
10153 };
10154
10155 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
10156 assert(D);
10157 Hash.clear();
10158 Hash.AddSubDecl(D);
10159 return Hash.CalculateHash();
10160 };
10161
Richard Trieu7282d322018-04-25 00:31:15 +000010162 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
10163 Hash.clear();
10164 Hash.AddTemplateArgument(TA);
10165 return Hash.CalculateHash();
10166 };
10167
Richard Trieu9359e8f2018-05-30 01:12:26 +000010168 auto ComputeTemplateParameterListODRHash =
10169 [&Hash](const TemplateParameterList *TPL) {
10170 assert(TPL);
10171 Hash.clear();
10172 Hash.AddTemplateParameterList(TPL);
10173 return Hash.CalculateHash();
10174 };
10175
Richard Smithcd45dbc2014-04-19 03:48:30 +000010176 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010177 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010178 // If we've already pointed out a specific problem with this class, don't
10179 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010180 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010181 continue;
10182
10183 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010184 CXXRecordDecl *FirstRecord = Merge.first;
10185 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010186 for (auto &RecordPair : Merge.second) {
10187 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010188 // Multiple different declarations got merged together; tell the user
10189 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010190 if (FirstRecord == SecondRecord)
10191 continue;
10192
10193 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010194
10195 auto *FirstDD = FirstRecord->DefinitionData;
10196 auto *SecondDD = RecordPair.second;
10197
10198 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10199
10200 // Diagnostics from DefinitionData are emitted here.
10201 if (FirstDD != SecondDD) {
10202 enum ODRDefinitionDataDifference {
10203 NumBases,
10204 NumVBases,
10205 BaseType,
10206 BaseVirtual,
10207 BaseAccess,
10208 };
10209 auto ODRDiagError = [FirstRecord, &FirstModule,
10210 this](SourceLocation Loc, SourceRange Range,
10211 ODRDefinitionDataDifference DiffType) {
10212 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10213 << FirstRecord << FirstModule.empty() << FirstModule << Range
10214 << DiffType;
10215 };
10216 auto ODRDiagNote = [&SecondModule,
10217 this](SourceLocation Loc, SourceRange Range,
10218 ODRDefinitionDataDifference DiffType) {
10219 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10220 << SecondModule << Range << DiffType;
10221 };
10222
Richard Trieue13eabe2017-09-30 02:19:17 +000010223 unsigned FirstNumBases = FirstDD->NumBases;
10224 unsigned FirstNumVBases = FirstDD->NumVBases;
10225 unsigned SecondNumBases = SecondDD->NumBases;
10226 unsigned SecondNumVBases = SecondDD->NumVBases;
10227
10228 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10229 unsigned NumBases = DD->NumBases;
10230 if (NumBases == 0) return SourceRange();
10231 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010232 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010233 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010234 };
10235
10236 if (FirstNumBases != SecondNumBases) {
10237 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10238 NumBases)
10239 << FirstNumBases;
10240 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10241 NumBases)
10242 << SecondNumBases;
10243 Diagnosed = true;
10244 break;
10245 }
10246
10247 if (FirstNumVBases != SecondNumVBases) {
10248 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10249 NumVBases)
10250 << FirstNumVBases;
10251 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10252 NumVBases)
10253 << SecondNumVBases;
10254 Diagnosed = true;
10255 break;
10256 }
10257
10258 auto FirstBases = FirstDD->bases();
10259 auto SecondBases = SecondDD->bases();
10260 unsigned i = 0;
10261 for (i = 0; i < FirstNumBases; ++i) {
10262 auto FirstBase = FirstBases[i];
10263 auto SecondBase = SecondBases[i];
10264 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10265 ComputeQualTypeODRHash(SecondBase.getType())) {
10266 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10267 BaseType)
10268 << (i + 1) << FirstBase.getType();
10269 ODRDiagNote(SecondRecord->getLocation(),
10270 SecondBase.getSourceRange(), BaseType)
10271 << (i + 1) << SecondBase.getType();
10272 break;
10273 }
10274
10275 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10276 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10277 BaseVirtual)
10278 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10279 ODRDiagNote(SecondRecord->getLocation(),
10280 SecondBase.getSourceRange(), BaseVirtual)
10281 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10282 break;
10283 }
10284
10285 if (FirstBase.getAccessSpecifierAsWritten() !=
10286 SecondBase.getAccessSpecifierAsWritten()) {
10287 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10288 BaseAccess)
10289 << (i + 1) << FirstBase.getType()
10290 << (int)FirstBase.getAccessSpecifierAsWritten();
10291 ODRDiagNote(SecondRecord->getLocation(),
10292 SecondBase.getSourceRange(), BaseAccess)
10293 << (i + 1) << SecondBase.getType()
10294 << (int)SecondBase.getAccessSpecifierAsWritten();
10295 break;
10296 }
10297 }
10298
10299 if (i != FirstNumBases) {
10300 Diagnosed = true;
10301 break;
10302 }
10303 }
10304
Richard Trieue7f7ed22017-02-22 01:11:25 +000010305 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +000010306
10307 const ClassTemplateDecl *FirstTemplate =
10308 FirstRecord->getDescribedClassTemplate();
10309 const ClassTemplateDecl *SecondTemplate =
10310 SecondRecord->getDescribedClassTemplate();
10311
10312 assert(!FirstTemplate == !SecondTemplate &&
10313 "Both pointers should be null or non-null");
10314
10315 enum ODRTemplateDifference {
10316 ParamEmptyName,
10317 ParamName,
10318 ParamSingleDefaultArgument,
10319 ParamDifferentDefaultArgument,
10320 };
10321
10322 if (FirstTemplate && SecondTemplate) {
10323 DeclHashes FirstTemplateHashes;
10324 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010325
10326 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010327 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10328 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010329 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010330 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010331 }
10332 };
10333
10334 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10335 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10336
10337 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10338 "Number of template parameters should be equal.");
10339
10340 auto FirstIt = FirstTemplateHashes.begin();
10341 auto FirstEnd = FirstTemplateHashes.end();
10342 auto SecondIt = SecondTemplateHashes.begin();
10343 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10344 if (FirstIt->second == SecondIt->second)
10345 continue;
10346
10347 auto ODRDiagError = [FirstRecord, &FirstModule,
10348 this](SourceLocation Loc, SourceRange Range,
10349 ODRTemplateDifference DiffType) {
10350 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10351 << FirstRecord << FirstModule.empty() << FirstModule << Range
10352 << DiffType;
10353 };
10354 auto ODRDiagNote = [&SecondModule,
10355 this](SourceLocation Loc, SourceRange Range,
10356 ODRTemplateDifference DiffType) {
10357 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10358 << SecondModule << Range << DiffType;
10359 };
10360
Vedant Kumar48b4f762018-04-14 01:40:48 +000010361 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10362 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010363
10364 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10365 "Parameter Decl's should be the same kind.");
10366
10367 DeclarationName FirstName = FirstDecl->getDeclName();
10368 DeclarationName SecondName = SecondDecl->getDeclName();
10369
10370 if (FirstName != SecondName) {
10371 const bool FirstNameEmpty =
10372 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10373 const bool SecondNameEmpty =
10374 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10375 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10376 "Both template parameters cannot be unnamed.");
10377 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10378 FirstNameEmpty ? ParamEmptyName : ParamName)
10379 << FirstName;
10380 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10381 SecondNameEmpty ? ParamEmptyName : ParamName)
10382 << SecondName;
10383 break;
10384 }
10385
10386 switch (FirstDecl->getKind()) {
10387 default:
10388 llvm_unreachable("Invalid template parameter type.");
10389 case Decl::TemplateTypeParm: {
10390 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10391 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10392 const bool HasFirstDefaultArgument =
10393 FirstParam->hasDefaultArgument() &&
10394 !FirstParam->defaultArgumentWasInherited();
10395 const bool HasSecondDefaultArgument =
10396 SecondParam->hasDefaultArgument() &&
10397 !SecondParam->defaultArgumentWasInherited();
10398
10399 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10400 ODRDiagError(FirstDecl->getLocation(),
10401 FirstDecl->getSourceRange(),
10402 ParamSingleDefaultArgument)
10403 << HasFirstDefaultArgument;
10404 ODRDiagNote(SecondDecl->getLocation(),
10405 SecondDecl->getSourceRange(),
10406 ParamSingleDefaultArgument)
10407 << HasSecondDefaultArgument;
10408 break;
10409 }
10410
10411 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10412 "Expecting default arguments.");
10413
10414 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10415 ParamDifferentDefaultArgument);
10416 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10417 ParamDifferentDefaultArgument);
10418
10419 break;
10420 }
10421 case Decl::NonTypeTemplateParm: {
10422 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10423 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10424 const bool HasFirstDefaultArgument =
10425 FirstParam->hasDefaultArgument() &&
10426 !FirstParam->defaultArgumentWasInherited();
10427 const bool HasSecondDefaultArgument =
10428 SecondParam->hasDefaultArgument() &&
10429 !SecondParam->defaultArgumentWasInherited();
10430
10431 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10432 ODRDiagError(FirstDecl->getLocation(),
10433 FirstDecl->getSourceRange(),
10434 ParamSingleDefaultArgument)
10435 << HasFirstDefaultArgument;
10436 ODRDiagNote(SecondDecl->getLocation(),
10437 SecondDecl->getSourceRange(),
10438 ParamSingleDefaultArgument)
10439 << HasSecondDefaultArgument;
10440 break;
10441 }
10442
10443 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10444 "Expecting default arguments.");
10445
10446 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10447 ParamDifferentDefaultArgument);
10448 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10449 ParamDifferentDefaultArgument);
10450
10451 break;
10452 }
10453 case Decl::TemplateTemplateParm: {
10454 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10455 const auto *SecondParam =
10456 cast<TemplateTemplateParmDecl>(SecondDecl);
10457 const bool HasFirstDefaultArgument =
10458 FirstParam->hasDefaultArgument() &&
10459 !FirstParam->defaultArgumentWasInherited();
10460 const bool HasSecondDefaultArgument =
10461 SecondParam->hasDefaultArgument() &&
10462 !SecondParam->defaultArgumentWasInherited();
10463
10464 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10465 ODRDiagError(FirstDecl->getLocation(),
10466 FirstDecl->getSourceRange(),
10467 ParamSingleDefaultArgument)
10468 << HasFirstDefaultArgument;
10469 ODRDiagNote(SecondDecl->getLocation(),
10470 SecondDecl->getSourceRange(),
10471 ParamSingleDefaultArgument)
10472 << HasSecondDefaultArgument;
10473 break;
10474 }
10475
10476 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10477 "Expecting default arguments.");
10478
10479 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10480 ParamDifferentDefaultArgument);
10481 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10482 ParamDifferentDefaultArgument);
10483
10484 break;
10485 }
10486 }
10487
10488 break;
10489 }
10490
10491 if (FirstIt != FirstEnd) {
10492 Diagnosed = true;
10493 break;
10494 }
10495 }
10496
Richard Trieue7f7ed22017-02-22 01:11:25 +000010497 DeclHashes FirstHashes;
10498 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010499
Richard Trieue6caa262017-12-23 00:41:01 +000010500 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10501 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010502 for (auto *D : Record->decls()) {
10503 // Due to decl merging, the first CXXRecordDecl is the parent of
10504 // Decls in both records.
10505 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10506 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010507 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010508 }
10509 };
10510 PopulateHashes(FirstHashes, FirstRecord);
10511 PopulateHashes(SecondHashes, SecondRecord);
10512
10513 // Used with err_module_odr_violation_mismatch_decl and
10514 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010515 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010516 enum {
10517 EndOfClass,
10518 PublicSpecifer,
10519 PrivateSpecifer,
10520 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010521 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010522 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010523 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010524 TypeAlias,
10525 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010526 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010527 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010528 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010529 Other
10530 } FirstDiffType = Other,
10531 SecondDiffType = Other;
10532
10533 auto DifferenceSelector = [](Decl *D) {
10534 assert(D && "valid Decl required");
10535 switch (D->getKind()) {
10536 default:
10537 return Other;
10538 case Decl::AccessSpec:
10539 switch (D->getAccess()) {
10540 case AS_public:
10541 return PublicSpecifer;
10542 case AS_private:
10543 return PrivateSpecifer;
10544 case AS_protected:
10545 return ProtectedSpecifer;
10546 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010547 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010548 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010549 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010550 case Decl::StaticAssert:
10551 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010552 case Decl::Field:
10553 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010554 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010555 case Decl::CXXConstructor:
10556 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010557 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010558 case Decl::TypeAlias:
10559 return TypeAlias;
10560 case Decl::Typedef:
10561 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010562 case Decl::Var:
10563 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010564 case Decl::Friend:
10565 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010566 case Decl::FunctionTemplate:
10567 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010568 }
10569 };
10570
10571 Decl *FirstDecl = nullptr;
10572 Decl *SecondDecl = nullptr;
10573 auto FirstIt = FirstHashes.begin();
10574 auto SecondIt = SecondHashes.begin();
10575
10576 // If there is a diagnoseable difference, FirstDiffType and
10577 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10578 // filled in if not EndOfClass.
10579 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010580 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10581 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010582 ++FirstIt;
10583 ++SecondIt;
10584 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010585 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010586
Richard Trieue7f7ed22017-02-22 01:11:25 +000010587 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10588 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10589
10590 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10591 SecondDiffType =
10592 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10593
10594 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010595 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010596
10597 if (FirstDiffType == Other || SecondDiffType == Other) {
10598 // Reaching this point means an unexpected Decl was encountered
10599 // or no difference was detected. This causes a generic error
10600 // message to be emitted.
10601 Diag(FirstRecord->getLocation(),
10602 diag::err_module_odr_violation_different_definitions)
10603 << FirstRecord << FirstModule.empty() << FirstModule;
10604
Richard Trieuca48d362017-06-21 01:43:13 +000010605 if (FirstDecl) {
10606 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10607 << FirstRecord << FirstDecl->getSourceRange();
10608 }
10609
Richard Trieue7f7ed22017-02-22 01:11:25 +000010610 Diag(SecondRecord->getLocation(),
10611 diag::note_module_odr_violation_different_definitions)
10612 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010613
10614 if (SecondDecl) {
10615 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10616 << SecondDecl->getSourceRange();
10617 }
10618
Richard Trieue7f7ed22017-02-22 01:11:25 +000010619 Diagnosed = true;
10620 break;
10621 }
10622
10623 if (FirstDiffType != SecondDiffType) {
10624 SourceLocation FirstLoc;
10625 SourceRange FirstRange;
10626 if (FirstDiffType == EndOfClass) {
10627 FirstLoc = FirstRecord->getBraceRange().getEnd();
10628 } else {
10629 FirstLoc = FirstIt->first->getLocation();
10630 FirstRange = FirstIt->first->getSourceRange();
10631 }
10632 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10633 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10634 << FirstDiffType;
10635
10636 SourceLocation SecondLoc;
10637 SourceRange SecondRange;
10638 if (SecondDiffType == EndOfClass) {
10639 SecondLoc = SecondRecord->getBraceRange().getEnd();
10640 } else {
10641 SecondLoc = SecondDecl->getLocation();
10642 SecondRange = SecondDecl->getSourceRange();
10643 }
10644 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10645 << SecondModule << SecondRange << SecondDiffType;
10646 Diagnosed = true;
10647 break;
10648 }
10649
Richard Trieu639d7b62017-02-22 22:22:42 +000010650 assert(FirstDiffType == SecondDiffType);
10651
10652 // Used with err_module_odr_violation_mismatch_decl_diff and
10653 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010654 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010655 StaticAssertCondition,
10656 StaticAssertMessage,
10657 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010658 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010659 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010660 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010661 FieldDifferentWidthBitField,
10662 FieldSingleMutable,
10663 FieldSingleInitializer,
10664 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010665 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010666 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010667 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010668 MethodVirtual,
10669 MethodStatic,
10670 MethodVolatile,
10671 MethodConst,
10672 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010673 MethodNumberParameters,
10674 MethodParameterType,
10675 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010676 MethodParameterSingleDefaultArgument,
10677 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010678 MethodNoTemplateArguments,
10679 MethodDifferentNumberTemplateArguments,
10680 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010681 MethodSingleBody,
10682 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010683 TypedefName,
10684 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010685 VarName,
10686 VarType,
10687 VarSingleInitializer,
10688 VarDifferentInitializer,
10689 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010690 FriendTypeFunction,
10691 FriendType,
10692 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010693 FunctionTemplateDifferentNumberParameters,
10694 FunctionTemplateParameterDifferentKind,
10695 FunctionTemplateParameterName,
10696 FunctionTemplateParameterSingleDefaultArgument,
10697 FunctionTemplateParameterDifferentDefaultArgument,
10698 FunctionTemplateParameterDifferentType,
10699 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010700 };
10701
10702 // These lambdas have the common portions of the ODR diagnostics. This
10703 // has the same return as Diag(), so addition parameters can be passed
10704 // in with operator<<
10705 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10706 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10707 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10708 << FirstRecord << FirstModule.empty() << FirstModule << Range
10709 << DiffType;
10710 };
10711 auto ODRDiagNote = [&SecondModule, this](
10712 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10713 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10714 << SecondModule << Range << DiffType;
10715 };
10716
Richard Trieu639d7b62017-02-22 22:22:42 +000010717 switch (FirstDiffType) {
10718 case Other:
10719 case EndOfClass:
10720 case PublicSpecifer:
10721 case PrivateSpecifer:
10722 case ProtectedSpecifer:
10723 llvm_unreachable("Invalid diff type");
10724
10725 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010726 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10727 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010728
10729 Expr *FirstExpr = FirstSA->getAssertExpr();
10730 Expr *SecondExpr = SecondSA->getAssertExpr();
10731 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10732 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10733 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010734 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010735 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010736 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10737 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010738 Diagnosed = true;
10739 break;
10740 }
10741
10742 StringLiteral *FirstStr = FirstSA->getMessage();
10743 StringLiteral *SecondStr = SecondSA->getMessage();
10744 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10745 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10746 SourceLocation FirstLoc, SecondLoc;
10747 SourceRange FirstRange, SecondRange;
10748 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010749 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010750 FirstRange = FirstStr->getSourceRange();
10751 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010752 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010753 FirstRange = FirstSA->getSourceRange();
10754 }
10755 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010756 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010757 SecondRange = SecondStr->getSourceRange();
10758 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010759 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010760 SecondRange = SecondSA->getSourceRange();
10761 }
10762 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10763 << (FirstStr == nullptr);
10764 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10765 << (SecondStr == nullptr);
10766 Diagnosed = true;
10767 break;
10768 }
10769
10770 if (FirstStr && SecondStr &&
10771 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010772 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010773 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010774 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010775 StaticAssertMessage);
10776 Diagnosed = true;
10777 break;
10778 }
10779 break;
10780 }
Richard Trieud0786092017-02-23 00:23:01 +000010781 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010782 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10783 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010784 IdentifierInfo *FirstII = FirstField->getIdentifier();
10785 IdentifierInfo *SecondII = SecondField->getIdentifier();
10786 if (FirstII->getName() != SecondII->getName()) {
10787 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10788 FieldName)
10789 << FirstII;
10790 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10791 FieldName)
10792 << SecondII;
10793
10794 Diagnosed = true;
10795 break;
10796 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010797
Richard Smithdbafb6c2017-06-29 23:23:46 +000010798 assert(getContext().hasSameType(FirstField->getType(),
10799 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010800
10801 QualType FirstType = FirstField->getType();
10802 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010803 if (ComputeQualTypeODRHash(FirstType) !=
10804 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010805 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10806 FieldTypeName)
10807 << FirstII << FirstType;
10808 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10809 FieldTypeName)
10810 << SecondII << SecondType;
10811
10812 Diagnosed = true;
10813 break;
10814 }
10815
Richard Trieu93772fc2017-02-24 20:59:28 +000010816 const bool IsFirstBitField = FirstField->isBitField();
10817 const bool IsSecondBitField = SecondField->isBitField();
10818 if (IsFirstBitField != IsSecondBitField) {
10819 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10820 FieldSingleBitField)
10821 << FirstII << IsFirstBitField;
10822 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10823 FieldSingleBitField)
10824 << SecondII << IsSecondBitField;
10825 Diagnosed = true;
10826 break;
10827 }
10828
10829 if (IsFirstBitField && IsSecondBitField) {
10830 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10831 FieldDifferentWidthBitField)
10832 << FirstII << FirstField->getBitWidth()->getSourceRange();
10833 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10834 FieldDifferentWidthBitField)
10835 << SecondII << SecondField->getBitWidth()->getSourceRange();
10836 Diagnosed = true;
10837 break;
10838 }
10839
Richard Trieu8d543e22017-02-24 23:35:37 +000010840 const bool IsFirstMutable = FirstField->isMutable();
10841 const bool IsSecondMutable = SecondField->isMutable();
10842 if (IsFirstMutable != IsSecondMutable) {
10843 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10844 FieldSingleMutable)
10845 << FirstII << IsFirstMutable;
10846 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10847 FieldSingleMutable)
10848 << SecondII << IsSecondMutable;
10849 Diagnosed = true;
10850 break;
10851 }
10852
10853 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10854 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10855 if ((!FirstInitializer && SecondInitializer) ||
10856 (FirstInitializer && !SecondInitializer)) {
10857 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10858 FieldSingleInitializer)
10859 << FirstII << (FirstInitializer != nullptr);
10860 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10861 FieldSingleInitializer)
10862 << SecondII << (SecondInitializer != nullptr);
10863 Diagnosed = true;
10864 break;
10865 }
10866
10867 if (FirstInitializer && SecondInitializer) {
10868 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10869 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10870 if (FirstInitHash != SecondInitHash) {
10871 ODRDiagError(FirstField->getLocation(),
10872 FirstField->getSourceRange(),
10873 FieldDifferentInitializers)
10874 << FirstII << FirstInitializer->getSourceRange();
10875 ODRDiagNote(SecondField->getLocation(),
10876 SecondField->getSourceRange(),
10877 FieldDifferentInitializers)
10878 << SecondII << SecondInitializer->getSourceRange();
10879 Diagnosed = true;
10880 break;
10881 }
10882 }
10883
Richard Trieud0786092017-02-23 00:23:01 +000010884 break;
10885 }
Richard Trieu48143742017-02-28 21:24:38 +000010886 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010887 enum {
10888 DiagMethod,
10889 DiagConstructor,
10890 DiagDestructor,
10891 } FirstMethodType,
10892 SecondMethodType;
10893 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10894 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10895 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10896 return DiagMethod;
10897 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010898 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10899 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010900 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10901 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010902 auto FirstName = FirstMethod->getDeclName();
10903 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010904 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010905 ODRDiagError(FirstMethod->getLocation(),
10906 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010907 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010908 ODRDiagNote(SecondMethod->getLocation(),
10909 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010910 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010911
10912 Diagnosed = true;
10913 break;
10914 }
10915
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010916 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10917 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010918 if (FirstDeleted != SecondDeleted) {
10919 ODRDiagError(FirstMethod->getLocation(),
10920 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010921 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010922
10923 ODRDiagNote(SecondMethod->getLocation(),
10924 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010925 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010926 Diagnosed = true;
10927 break;
10928 }
10929
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010930 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10931 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10932 if (FirstDefaulted != SecondDefaulted) {
10933 ODRDiagError(FirstMethod->getLocation(),
10934 FirstMethod->getSourceRange(), MethodDefaulted)
10935 << FirstMethodType << FirstName << FirstDefaulted;
10936
10937 ODRDiagNote(SecondMethod->getLocation(),
10938 SecondMethod->getSourceRange(), MethodDefaulted)
10939 << SecondMethodType << SecondName << SecondDefaulted;
10940 Diagnosed = true;
10941 break;
10942 }
10943
Richard Trieu583e2c12017-03-04 00:08:58 +000010944 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10945 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10946 const bool FirstPure = FirstMethod->isPure();
10947 const bool SecondPure = SecondMethod->isPure();
10948 if ((FirstVirtual || SecondVirtual) &&
10949 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10950 ODRDiagError(FirstMethod->getLocation(),
10951 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010952 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010953 ODRDiagNote(SecondMethod->getLocation(),
10954 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010955 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010956 Diagnosed = true;
10957 break;
10958 }
10959
10960 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10961 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10962 // class needs to be checked instead.
10963 const auto FirstStorage = FirstMethod->getStorageClass();
10964 const auto SecondStorage = SecondMethod->getStorageClass();
10965 const bool FirstStatic = FirstStorage == SC_Static;
10966 const bool SecondStatic = SecondStorage == SC_Static;
10967 if (FirstStatic != SecondStatic) {
10968 ODRDiagError(FirstMethod->getLocation(),
10969 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010970 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010971 ODRDiagNote(SecondMethod->getLocation(),
10972 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010973 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010974 Diagnosed = true;
10975 break;
10976 }
10977
10978 const bool FirstVolatile = FirstMethod->isVolatile();
10979 const bool SecondVolatile = SecondMethod->isVolatile();
10980 if (FirstVolatile != SecondVolatile) {
10981 ODRDiagError(FirstMethod->getLocation(),
10982 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010983 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010984 ODRDiagNote(SecondMethod->getLocation(),
10985 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010986 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010987 Diagnosed = true;
10988 break;
10989 }
10990
10991 const bool FirstConst = FirstMethod->isConst();
10992 const bool SecondConst = SecondMethod->isConst();
10993 if (FirstConst != SecondConst) {
10994 ODRDiagError(FirstMethod->getLocation(),
10995 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010996 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010997 ODRDiagNote(SecondMethod->getLocation(),
10998 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010999 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000011000 Diagnosed = true;
11001 break;
11002 }
11003
11004 const bool FirstInline = FirstMethod->isInlineSpecified();
11005 const bool SecondInline = SecondMethod->isInlineSpecified();
11006 if (FirstInline != SecondInline) {
11007 ODRDiagError(FirstMethod->getLocation(),
11008 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011009 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011010 ODRDiagNote(SecondMethod->getLocation(),
11011 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011012 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011013 Diagnosed = true;
11014 break;
11015 }
11016
Richard Trieu02552272017-05-02 23:58:52 +000011017 const unsigned FirstNumParameters = FirstMethod->param_size();
11018 const unsigned SecondNumParameters = SecondMethod->param_size();
11019 if (FirstNumParameters != SecondNumParameters) {
11020 ODRDiagError(FirstMethod->getLocation(),
11021 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011022 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011023 ODRDiagNote(SecondMethod->getLocation(),
11024 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011025 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011026 Diagnosed = true;
11027 break;
11028 }
11029
11030 // Need this status boolean to know when break out of the switch.
11031 bool ParameterMismatch = false;
11032 for (unsigned I = 0; I < FirstNumParameters; ++I) {
11033 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
11034 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
11035
11036 QualType FirstParamType = FirstParam->getType();
11037 QualType SecondParamType = SecondParam->getType();
11038 if (FirstParamType != SecondParamType &&
11039 ComputeQualTypeODRHash(FirstParamType) !=
11040 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011041 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011042 FirstParamType->getAs<DecayedType>()) {
11043 ODRDiagError(FirstMethod->getLocation(),
11044 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011045 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11046 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000011047 } else {
11048 ODRDiagError(FirstMethod->getLocation(),
11049 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011050 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11051 << false;
Richard Trieu02552272017-05-02 23:58:52 +000011052 }
11053
Vedant Kumar48b4f762018-04-14 01:40:48 +000011054 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011055 SecondParamType->getAs<DecayedType>()) {
11056 ODRDiagNote(SecondMethod->getLocation(),
11057 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011058 << SecondMethodType << SecondName << (I + 1)
11059 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000011060 << ParamDecayedType->getOriginalType();
11061 } else {
11062 ODRDiagNote(SecondMethod->getLocation(),
11063 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011064 << SecondMethodType << SecondName << (I + 1)
11065 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000011066 }
11067 ParameterMismatch = true;
11068 break;
11069 }
11070
11071 DeclarationName FirstParamName = FirstParam->getDeclName();
11072 DeclarationName SecondParamName = SecondParam->getDeclName();
11073 if (FirstParamName != SecondParamName) {
11074 ODRDiagError(FirstMethod->getLocation(),
11075 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011076 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011077 ODRDiagNote(SecondMethod->getLocation(),
11078 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011079 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011080 ParameterMismatch = true;
11081 break;
11082 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011083
11084 const Expr *FirstInit = FirstParam->getInit();
11085 const Expr *SecondInit = SecondParam->getInit();
11086 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11087 ODRDiagError(FirstMethod->getLocation(),
11088 FirstMethod->getSourceRange(),
11089 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011090 << FirstMethodType << FirstName << (I + 1)
11091 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011092 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11093 ODRDiagNote(SecondMethod->getLocation(),
11094 SecondMethod->getSourceRange(),
11095 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011096 << SecondMethodType << SecondName << (I + 1)
11097 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011098 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11099 ParameterMismatch = true;
11100 break;
11101 }
11102
11103 if (FirstInit && SecondInit &&
11104 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11105 ODRDiagError(FirstMethod->getLocation(),
11106 FirstMethod->getSourceRange(),
11107 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011108 << FirstMethodType << FirstName << (I + 1)
11109 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011110 ODRDiagNote(SecondMethod->getLocation(),
11111 SecondMethod->getSourceRange(),
11112 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011113 << SecondMethodType << SecondName << (I + 1)
11114 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011115 ParameterMismatch = true;
11116 break;
11117
11118 }
Richard Trieu02552272017-05-02 23:58:52 +000011119 }
11120
11121 if (ParameterMismatch) {
11122 Diagnosed = true;
11123 break;
11124 }
11125
Richard Trieu7282d322018-04-25 00:31:15 +000011126 const auto *FirstTemplateArgs =
11127 FirstMethod->getTemplateSpecializationArgs();
11128 const auto *SecondTemplateArgs =
11129 SecondMethod->getTemplateSpecializationArgs();
11130
11131 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
11132 (!FirstTemplateArgs && SecondTemplateArgs)) {
11133 ODRDiagError(FirstMethod->getLocation(),
11134 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
11135 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
11136 ODRDiagNote(SecondMethod->getLocation(),
11137 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
11138 << SecondMethodType << SecondName
11139 << (SecondTemplateArgs != nullptr);
11140
11141 Diagnosed = true;
11142 break;
11143 }
11144
11145 if (FirstTemplateArgs && SecondTemplateArgs) {
11146 // Remove pack expansions from argument list.
11147 auto ExpandTemplateArgumentList =
11148 [](const TemplateArgumentList *TAL) {
11149 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
11150 for (const TemplateArgument &TA : TAL->asArray()) {
11151 if (TA.getKind() != TemplateArgument::Pack) {
11152 ExpandedList.push_back(&TA);
11153 continue;
11154 }
11155 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
11156 ExpandedList.push_back(&PackTA);
11157 }
11158 }
11159 return ExpandedList;
11160 };
11161 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
11162 ExpandTemplateArgumentList(FirstTemplateArgs);
11163 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
11164 ExpandTemplateArgumentList(SecondTemplateArgs);
11165
11166 if (FirstExpandedList.size() != SecondExpandedList.size()) {
11167 ODRDiagError(FirstMethod->getLocation(),
11168 FirstMethod->getSourceRange(),
11169 MethodDifferentNumberTemplateArguments)
11170 << FirstMethodType << FirstName
11171 << (unsigned)FirstExpandedList.size();
11172 ODRDiagNote(SecondMethod->getLocation(),
11173 SecondMethod->getSourceRange(),
11174 MethodDifferentNumberTemplateArguments)
11175 << SecondMethodType << SecondName
11176 << (unsigned)SecondExpandedList.size();
11177
11178 Diagnosed = true;
11179 break;
11180 }
11181
11182 bool TemplateArgumentMismatch = false;
11183 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
11184 const TemplateArgument &FirstTA = *FirstExpandedList[i],
11185 &SecondTA = *SecondExpandedList[i];
11186 if (ComputeTemplateArgumentODRHash(FirstTA) ==
11187 ComputeTemplateArgumentODRHash(SecondTA)) {
11188 continue;
11189 }
11190
11191 ODRDiagError(FirstMethod->getLocation(),
11192 FirstMethod->getSourceRange(),
11193 MethodDifferentTemplateArgument)
11194 << FirstMethodType << FirstName << FirstTA << i + 1;
11195 ODRDiagNote(SecondMethod->getLocation(),
11196 SecondMethod->getSourceRange(),
11197 MethodDifferentTemplateArgument)
11198 << SecondMethodType << SecondName << SecondTA << i + 1;
11199
11200 TemplateArgumentMismatch = true;
11201 break;
11202 }
11203
11204 if (TemplateArgumentMismatch) {
11205 Diagnosed = true;
11206 break;
11207 }
11208 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000011209
11210 // Compute the hash of the method as if it has no body.
11211 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
11212 Hash.clear();
11213 Hash.AddFunctionDecl(D, true /*SkipBody*/);
11214 return Hash.CalculateHash();
11215 };
11216
11217 // Compare the hash generated to the hash stored. A difference means
11218 // that a body was present in the original source. Due to merging,
11219 // the stardard way of detecting a body will not work.
11220 const bool HasFirstBody =
11221 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
11222 const bool HasSecondBody =
11223 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
11224
11225 if (HasFirstBody != HasSecondBody) {
11226 ODRDiagError(FirstMethod->getLocation(),
11227 FirstMethod->getSourceRange(), MethodSingleBody)
11228 << FirstMethodType << FirstName << HasFirstBody;
11229 ODRDiagNote(SecondMethod->getLocation(),
11230 SecondMethod->getSourceRange(), MethodSingleBody)
11231 << SecondMethodType << SecondName << HasSecondBody;
11232 Diagnosed = true;
11233 break;
11234 }
11235
11236 if (HasFirstBody && HasSecondBody) {
11237 ODRDiagError(FirstMethod->getLocation(),
11238 FirstMethod->getSourceRange(), MethodDifferentBody)
11239 << FirstMethodType << FirstName;
11240 ODRDiagNote(SecondMethod->getLocation(),
11241 SecondMethod->getSourceRange(), MethodDifferentBody)
11242 << SecondMethodType << SecondName;
11243 Diagnosed = true;
11244 break;
11245 }
11246
Richard Trieu48143742017-02-28 21:24:38 +000011247 break;
11248 }
Richard Trieu11d566a2017-06-12 21:58:22 +000011249 case TypeAlias:
11250 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011251 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
11252 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000011253 auto FirstName = FirstTD->getDeclName();
11254 auto SecondName = SecondTD->getDeclName();
11255 if (FirstName != SecondName) {
11256 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11257 TypedefName)
11258 << (FirstDiffType == TypeAlias) << FirstName;
11259 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11260 TypedefName)
11261 << (FirstDiffType == TypeAlias) << SecondName;
11262 Diagnosed = true;
11263 break;
11264 }
11265
11266 QualType FirstType = FirstTD->getUnderlyingType();
11267 QualType SecondType = SecondTD->getUnderlyingType();
11268 if (ComputeQualTypeODRHash(FirstType) !=
11269 ComputeQualTypeODRHash(SecondType)) {
11270 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11271 TypedefType)
11272 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
11273 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11274 TypedefType)
11275 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
11276 Diagnosed = true;
11277 break;
11278 }
11279 break;
11280 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011281 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011282 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
11283 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000011284 auto FirstName = FirstVD->getDeclName();
11285 auto SecondName = SecondVD->getDeclName();
11286 if (FirstName != SecondName) {
11287 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11288 VarName)
11289 << FirstName;
11290 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11291 VarName)
11292 << SecondName;
11293 Diagnosed = true;
11294 break;
11295 }
11296
11297 QualType FirstType = FirstVD->getType();
11298 QualType SecondType = SecondVD->getType();
11299 if (ComputeQualTypeODRHash(FirstType) !=
11300 ComputeQualTypeODRHash(SecondType)) {
11301 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11302 VarType)
11303 << FirstName << FirstType;
11304 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11305 VarType)
11306 << SecondName << SecondType;
11307 Diagnosed = true;
11308 break;
11309 }
11310
11311 const Expr *FirstInit = FirstVD->getInit();
11312 const Expr *SecondInit = SecondVD->getInit();
11313 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11314 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11315 VarSingleInitializer)
11316 << FirstName << (FirstInit == nullptr)
11317 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
11318 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11319 VarSingleInitializer)
11320 << SecondName << (SecondInit == nullptr)
11321 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11322 Diagnosed = true;
11323 break;
11324 }
11325
11326 if (FirstInit && SecondInit &&
11327 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11328 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11329 VarDifferentInitializer)
11330 << FirstName << FirstInit->getSourceRange();
11331 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11332 VarDifferentInitializer)
11333 << SecondName << SecondInit->getSourceRange();
11334 Diagnosed = true;
11335 break;
11336 }
11337
11338 const bool FirstIsConstexpr = FirstVD->isConstexpr();
11339 const bool SecondIsConstexpr = SecondVD->isConstexpr();
11340 if (FirstIsConstexpr != SecondIsConstexpr) {
11341 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11342 VarConstexpr)
11343 << FirstName << FirstIsConstexpr;
11344 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11345 VarConstexpr)
11346 << SecondName << SecondIsConstexpr;
11347 Diagnosed = true;
11348 break;
11349 }
11350 break;
11351 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000011352 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011353 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
11354 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000011355
11356 NamedDecl *FirstND = FirstFriend->getFriendDecl();
11357 NamedDecl *SecondND = SecondFriend->getFriendDecl();
11358
11359 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
11360 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
11361
11362 if (FirstND && SecondND) {
11363 ODRDiagError(FirstFriend->getFriendLoc(),
11364 FirstFriend->getSourceRange(), FriendFunction)
11365 << FirstND;
11366 ODRDiagNote(SecondFriend->getFriendLoc(),
11367 SecondFriend->getSourceRange(), FriendFunction)
11368 << SecondND;
11369
11370 Diagnosed = true;
11371 break;
11372 }
11373
11374 if (FirstTSI && SecondTSI) {
11375 QualType FirstFriendType = FirstTSI->getType();
11376 QualType SecondFriendType = SecondTSI->getType();
11377 assert(ComputeQualTypeODRHash(FirstFriendType) !=
11378 ComputeQualTypeODRHash(SecondFriendType));
11379 ODRDiagError(FirstFriend->getFriendLoc(),
11380 FirstFriend->getSourceRange(), FriendType)
11381 << FirstFriendType;
11382 ODRDiagNote(SecondFriend->getFriendLoc(),
11383 SecondFriend->getSourceRange(), FriendType)
11384 << SecondFriendType;
11385 Diagnosed = true;
11386 break;
11387 }
11388
11389 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
11390 FriendTypeFunction)
11391 << (FirstTSI == nullptr);
11392 ODRDiagNote(SecondFriend->getFriendLoc(),
11393 SecondFriend->getSourceRange(), FriendTypeFunction)
11394 << (SecondTSI == nullptr);
11395
11396 Diagnosed = true;
11397 break;
11398 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000011399 case FunctionTemplate: {
11400 FunctionTemplateDecl *FirstTemplate =
11401 cast<FunctionTemplateDecl>(FirstDecl);
11402 FunctionTemplateDecl *SecondTemplate =
11403 cast<FunctionTemplateDecl>(SecondDecl);
11404
11405 TemplateParameterList *FirstTPL =
11406 FirstTemplate->getTemplateParameters();
11407 TemplateParameterList *SecondTPL =
11408 SecondTemplate->getTemplateParameters();
11409
11410 if (FirstTPL->size() != SecondTPL->size()) {
11411 ODRDiagError(FirstTemplate->getLocation(),
11412 FirstTemplate->getSourceRange(),
11413 FunctionTemplateDifferentNumberParameters)
11414 << FirstTemplate << FirstTPL->size();
11415 ODRDiagNote(SecondTemplate->getLocation(),
11416 SecondTemplate->getSourceRange(),
11417 FunctionTemplateDifferentNumberParameters)
11418 << SecondTemplate << SecondTPL->size();
11419
11420 Diagnosed = true;
11421 break;
11422 }
11423
11424 bool ParameterMismatch = false;
11425 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
11426 NamedDecl *FirstParam = FirstTPL->getParam(i);
11427 NamedDecl *SecondParam = SecondTPL->getParam(i);
11428
11429 if (FirstParam->getKind() != SecondParam->getKind()) {
11430 enum {
11431 TemplateTypeParameter,
11432 NonTypeTemplateParameter,
11433 TemplateTemplateParameter,
11434 };
11435 auto GetParamType = [](NamedDecl *D) {
11436 switch (D->getKind()) {
11437 default:
11438 llvm_unreachable("Unexpected template parameter type");
11439 case Decl::TemplateTypeParm:
11440 return TemplateTypeParameter;
11441 case Decl::NonTypeTemplateParm:
11442 return NonTypeTemplateParameter;
11443 case Decl::TemplateTemplateParm:
11444 return TemplateTemplateParameter;
11445 }
11446 };
11447
11448 ODRDiagError(FirstTemplate->getLocation(),
11449 FirstTemplate->getSourceRange(),
11450 FunctionTemplateParameterDifferentKind)
11451 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11452 ODRDiagNote(SecondTemplate->getLocation(),
11453 SecondTemplate->getSourceRange(),
11454 FunctionTemplateParameterDifferentKind)
11455 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11456
11457 ParameterMismatch = true;
11458 break;
11459 }
11460
11461 if (FirstParam->getName() != SecondParam->getName()) {
11462 ODRDiagError(FirstTemplate->getLocation(),
11463 FirstTemplate->getSourceRange(),
11464 FunctionTemplateParameterName)
11465 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11466 << FirstParam;
11467 ODRDiagNote(SecondTemplate->getLocation(),
11468 SecondTemplate->getSourceRange(),
11469 FunctionTemplateParameterName)
11470 << SecondTemplate << (i + 1)
11471 << (bool)SecondParam->getIdentifier() << SecondParam;
11472 ParameterMismatch = true;
11473 break;
11474 }
11475
11476 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11477 isa<TemplateTypeParmDecl>(SecondParam)) {
11478 TemplateTypeParmDecl *FirstTTPD =
11479 cast<TemplateTypeParmDecl>(FirstParam);
11480 TemplateTypeParmDecl *SecondTTPD =
11481 cast<TemplateTypeParmDecl>(SecondParam);
11482 bool HasFirstDefaultArgument =
11483 FirstTTPD->hasDefaultArgument() &&
11484 !FirstTTPD->defaultArgumentWasInherited();
11485 bool HasSecondDefaultArgument =
11486 SecondTTPD->hasDefaultArgument() &&
11487 !SecondTTPD->defaultArgumentWasInherited();
11488 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11489 ODRDiagError(FirstTemplate->getLocation(),
11490 FirstTemplate->getSourceRange(),
11491 FunctionTemplateParameterSingleDefaultArgument)
11492 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11493 ODRDiagNote(SecondTemplate->getLocation(),
11494 SecondTemplate->getSourceRange(),
11495 FunctionTemplateParameterSingleDefaultArgument)
11496 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11497 ParameterMismatch = true;
11498 break;
11499 }
11500
11501 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11502 QualType FirstType = FirstTTPD->getDefaultArgument();
11503 QualType SecondType = SecondTTPD->getDefaultArgument();
11504 if (ComputeQualTypeODRHash(FirstType) !=
11505 ComputeQualTypeODRHash(SecondType)) {
11506 ODRDiagError(FirstTemplate->getLocation(),
11507 FirstTemplate->getSourceRange(),
11508 FunctionTemplateParameterDifferentDefaultArgument)
11509 << FirstTemplate << (i + 1) << FirstType;
11510 ODRDiagNote(SecondTemplate->getLocation(),
11511 SecondTemplate->getSourceRange(),
11512 FunctionTemplateParameterDifferentDefaultArgument)
11513 << SecondTemplate << (i + 1) << SecondType;
11514 ParameterMismatch = true;
11515 break;
11516 }
11517 }
11518
11519 if (FirstTTPD->isParameterPack() !=
11520 SecondTTPD->isParameterPack()) {
11521 ODRDiagError(FirstTemplate->getLocation(),
11522 FirstTemplate->getSourceRange(),
11523 FunctionTemplatePackParameter)
11524 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11525 ODRDiagNote(SecondTemplate->getLocation(),
11526 SecondTemplate->getSourceRange(),
11527 FunctionTemplatePackParameter)
11528 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11529 ParameterMismatch = true;
11530 break;
11531 }
11532 }
11533
11534 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11535 isa<TemplateTemplateParmDecl>(SecondParam)) {
11536 TemplateTemplateParmDecl *FirstTTPD =
11537 cast<TemplateTemplateParmDecl>(FirstParam);
11538 TemplateTemplateParmDecl *SecondTTPD =
11539 cast<TemplateTemplateParmDecl>(SecondParam);
11540
11541 TemplateParameterList *FirstTPL =
11542 FirstTTPD->getTemplateParameters();
11543 TemplateParameterList *SecondTPL =
11544 SecondTTPD->getTemplateParameters();
11545
11546 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11547 ComputeTemplateParameterListODRHash(SecondTPL)) {
11548 ODRDiagError(FirstTemplate->getLocation(),
11549 FirstTemplate->getSourceRange(),
11550 FunctionTemplateParameterDifferentType)
11551 << FirstTemplate << (i + 1);
11552 ODRDiagNote(SecondTemplate->getLocation(),
11553 SecondTemplate->getSourceRange(),
11554 FunctionTemplateParameterDifferentType)
11555 << SecondTemplate << (i + 1);
11556 ParameterMismatch = true;
11557 break;
11558 }
11559
11560 bool HasFirstDefaultArgument =
11561 FirstTTPD->hasDefaultArgument() &&
11562 !FirstTTPD->defaultArgumentWasInherited();
11563 bool HasSecondDefaultArgument =
11564 SecondTTPD->hasDefaultArgument() &&
11565 !SecondTTPD->defaultArgumentWasInherited();
11566 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11567 ODRDiagError(FirstTemplate->getLocation(),
11568 FirstTemplate->getSourceRange(),
11569 FunctionTemplateParameterSingleDefaultArgument)
11570 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11571 ODRDiagNote(SecondTemplate->getLocation(),
11572 SecondTemplate->getSourceRange(),
11573 FunctionTemplateParameterSingleDefaultArgument)
11574 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11575 ParameterMismatch = true;
11576 break;
11577 }
11578
11579 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11580 TemplateArgument FirstTA =
11581 FirstTTPD->getDefaultArgument().getArgument();
11582 TemplateArgument SecondTA =
11583 SecondTTPD->getDefaultArgument().getArgument();
11584 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11585 ComputeTemplateArgumentODRHash(SecondTA)) {
11586 ODRDiagError(FirstTemplate->getLocation(),
11587 FirstTemplate->getSourceRange(),
11588 FunctionTemplateParameterDifferentDefaultArgument)
11589 << FirstTemplate << (i + 1) << FirstTA;
11590 ODRDiagNote(SecondTemplate->getLocation(),
11591 SecondTemplate->getSourceRange(),
11592 FunctionTemplateParameterDifferentDefaultArgument)
11593 << SecondTemplate << (i + 1) << SecondTA;
11594 ParameterMismatch = true;
11595 break;
11596 }
11597 }
11598
11599 if (FirstTTPD->isParameterPack() !=
11600 SecondTTPD->isParameterPack()) {
11601 ODRDiagError(FirstTemplate->getLocation(),
11602 FirstTemplate->getSourceRange(),
11603 FunctionTemplatePackParameter)
11604 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11605 ODRDiagNote(SecondTemplate->getLocation(),
11606 SecondTemplate->getSourceRange(),
11607 FunctionTemplatePackParameter)
11608 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11609 ParameterMismatch = true;
11610 break;
11611 }
11612 }
11613
11614 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11615 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11616 NonTypeTemplateParmDecl *FirstNTTPD =
11617 cast<NonTypeTemplateParmDecl>(FirstParam);
11618 NonTypeTemplateParmDecl *SecondNTTPD =
11619 cast<NonTypeTemplateParmDecl>(SecondParam);
11620
11621 QualType FirstType = FirstNTTPD->getType();
11622 QualType SecondType = SecondNTTPD->getType();
11623 if (ComputeQualTypeODRHash(FirstType) !=
11624 ComputeQualTypeODRHash(SecondType)) {
11625 ODRDiagError(FirstTemplate->getLocation(),
11626 FirstTemplate->getSourceRange(),
11627 FunctionTemplateParameterDifferentType)
11628 << FirstTemplate << (i + 1);
11629 ODRDiagNote(SecondTemplate->getLocation(),
11630 SecondTemplate->getSourceRange(),
11631 FunctionTemplateParameterDifferentType)
11632 << SecondTemplate << (i + 1);
11633 ParameterMismatch = true;
11634 break;
11635 }
11636
11637 bool HasFirstDefaultArgument =
11638 FirstNTTPD->hasDefaultArgument() &&
11639 !FirstNTTPD->defaultArgumentWasInherited();
11640 bool HasSecondDefaultArgument =
11641 SecondNTTPD->hasDefaultArgument() &&
11642 !SecondNTTPD->defaultArgumentWasInherited();
11643 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11644 ODRDiagError(FirstTemplate->getLocation(),
11645 FirstTemplate->getSourceRange(),
11646 FunctionTemplateParameterSingleDefaultArgument)
11647 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11648 ODRDiagNote(SecondTemplate->getLocation(),
11649 SecondTemplate->getSourceRange(),
11650 FunctionTemplateParameterSingleDefaultArgument)
11651 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11652 ParameterMismatch = true;
11653 break;
11654 }
11655
11656 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11657 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11658 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11659 if (ComputeODRHash(FirstDefaultArgument) !=
11660 ComputeODRHash(SecondDefaultArgument)) {
11661 ODRDiagError(FirstTemplate->getLocation(),
11662 FirstTemplate->getSourceRange(),
11663 FunctionTemplateParameterDifferentDefaultArgument)
11664 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11665 ODRDiagNote(SecondTemplate->getLocation(),
11666 SecondTemplate->getSourceRange(),
11667 FunctionTemplateParameterDifferentDefaultArgument)
11668 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11669 ParameterMismatch = true;
11670 break;
11671 }
11672 }
11673
11674 if (FirstNTTPD->isParameterPack() !=
11675 SecondNTTPD->isParameterPack()) {
11676 ODRDiagError(FirstTemplate->getLocation(),
11677 FirstTemplate->getSourceRange(),
11678 FunctionTemplatePackParameter)
11679 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11680 ODRDiagNote(SecondTemplate->getLocation(),
11681 SecondTemplate->getSourceRange(),
11682 FunctionTemplatePackParameter)
11683 << SecondTemplate << (i + 1)
11684 << SecondNTTPD->isParameterPack();
11685 ParameterMismatch = true;
11686 break;
11687 }
11688 }
11689 }
11690
11691 if (ParameterMismatch) {
11692 Diagnosed = true;
11693 break;
11694 }
11695
11696 break;
11697 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011698 }
11699
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011700 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011701 continue;
11702
Richard Trieu708859a2017-06-08 00:56:21 +000011703 Diag(FirstDecl->getLocation(),
11704 diag::err_module_odr_violation_mismatch_decl_unknown)
11705 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11706 << FirstDecl->getSourceRange();
11707 Diag(SecondDecl->getLocation(),
11708 diag::note_module_odr_violation_mismatch_decl_unknown)
11709 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011710 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011711 }
11712
11713 if (!Diagnosed) {
11714 // All definitions are updates to the same declaration. This happens if a
11715 // module instantiates the declaration of a class template specialization
11716 // and two or more other modules instantiate its definition.
11717 //
11718 // FIXME: Indicate which modules had instantiations of this definition.
11719 // FIXME: How can this even happen?
11720 Diag(Merge.first->getLocation(),
11721 diag::err_module_odr_violation_different_instantiations)
11722 << Merge.first;
11723 }
11724 }
Richard Trieue6caa262017-12-23 00:41:01 +000011725
11726 // Issue ODR failures diagnostics for functions.
11727 for (auto &Merge : FunctionOdrMergeFailures) {
11728 enum ODRFunctionDifference {
11729 ReturnType,
11730 ParameterName,
11731 ParameterType,
11732 ParameterSingleDefaultArgument,
11733 ParameterDifferentDefaultArgument,
11734 FunctionBody,
11735 };
11736
11737 FunctionDecl *FirstFunction = Merge.first;
11738 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11739
11740 bool Diagnosed = false;
11741 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011742
Richard Trieue6caa262017-12-23 00:41:01 +000011743 if (FirstFunction == SecondFunction)
11744 continue;
11745
11746 std::string SecondModule =
11747 getOwningModuleNameForDiagnostic(SecondFunction);
11748
11749 auto ODRDiagError = [FirstFunction, &FirstModule,
11750 this](SourceLocation Loc, SourceRange Range,
11751 ODRFunctionDifference DiffType) {
11752 return Diag(Loc, diag::err_module_odr_violation_function)
11753 << FirstFunction << FirstModule.empty() << FirstModule << Range
11754 << DiffType;
11755 };
11756 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11757 SourceRange Range,
11758 ODRFunctionDifference DiffType) {
11759 return Diag(Loc, diag::note_module_odr_violation_function)
11760 << SecondModule << Range << DiffType;
11761 };
11762
11763 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11764 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11765 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11766 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11767 << FirstFunction->getReturnType();
11768 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11769 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11770 << SecondFunction->getReturnType();
11771 Diagnosed = true;
11772 break;
11773 }
11774
11775 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11776 "Merged functions with different number of parameters");
11777
11778 auto ParamSize = FirstFunction->param_size();
11779 bool ParameterMismatch = false;
11780 for (unsigned I = 0; I < ParamSize; ++I) {
11781 auto *FirstParam = FirstFunction->getParamDecl(I);
11782 auto *SecondParam = SecondFunction->getParamDecl(I);
11783
11784 assert(getContext().hasSameType(FirstParam->getType(),
11785 SecondParam->getType()) &&
11786 "Merged function has different parameter types.");
11787
11788 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11789 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11790 ParameterName)
11791 << I + 1 << FirstParam->getDeclName();
11792 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11793 ParameterName)
11794 << I + 1 << SecondParam->getDeclName();
11795 ParameterMismatch = true;
11796 break;
11797 };
11798
11799 QualType FirstParamType = FirstParam->getType();
11800 QualType SecondParamType = SecondParam->getType();
11801 if (FirstParamType != SecondParamType &&
11802 ComputeQualTypeODRHash(FirstParamType) !=
11803 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011804 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011805 FirstParamType->getAs<DecayedType>()) {
11806 ODRDiagError(FirstParam->getLocation(),
11807 FirstParam->getSourceRange(), ParameterType)
11808 << (I + 1) << FirstParamType << true
11809 << ParamDecayedType->getOriginalType();
11810 } else {
11811 ODRDiagError(FirstParam->getLocation(),
11812 FirstParam->getSourceRange(), ParameterType)
11813 << (I + 1) << FirstParamType << false;
11814 }
11815
Vedant Kumar48b4f762018-04-14 01:40:48 +000011816 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011817 SecondParamType->getAs<DecayedType>()) {
11818 ODRDiagNote(SecondParam->getLocation(),
11819 SecondParam->getSourceRange(), ParameterType)
11820 << (I + 1) << SecondParamType << true
11821 << ParamDecayedType->getOriginalType();
11822 } else {
11823 ODRDiagNote(SecondParam->getLocation(),
11824 SecondParam->getSourceRange(), ParameterType)
11825 << (I + 1) << SecondParamType << false;
11826 }
11827 ParameterMismatch = true;
11828 break;
11829 }
11830
11831 const Expr *FirstInit = FirstParam->getInit();
11832 const Expr *SecondInit = SecondParam->getInit();
11833 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11834 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11835 ParameterSingleDefaultArgument)
11836 << (I + 1) << (FirstInit == nullptr)
11837 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11838 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11839 ParameterSingleDefaultArgument)
11840 << (I + 1) << (SecondInit == nullptr)
11841 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11842 ParameterMismatch = true;
11843 break;
11844 }
11845
11846 if (FirstInit && SecondInit &&
11847 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11848 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11849 ParameterDifferentDefaultArgument)
11850 << (I + 1) << FirstInit->getSourceRange();
11851 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11852 ParameterDifferentDefaultArgument)
11853 << (I + 1) << SecondInit->getSourceRange();
11854 ParameterMismatch = true;
11855 break;
11856 }
11857
11858 assert(ComputeSubDeclODRHash(FirstParam) ==
11859 ComputeSubDeclODRHash(SecondParam) &&
11860 "Undiagnosed parameter difference.");
11861 }
11862
11863 if (ParameterMismatch) {
11864 Diagnosed = true;
11865 break;
11866 }
11867
11868 // If no error has been generated before now, assume the problem is in
11869 // the body and generate a message.
11870 ODRDiagError(FirstFunction->getLocation(),
11871 FirstFunction->getSourceRange(), FunctionBody);
11872 ODRDiagNote(SecondFunction->getLocation(),
11873 SecondFunction->getSourceRange(), FunctionBody);
11874 Diagnosed = true;
11875 break;
11876 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011877 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011878 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11879 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011880
11881 // Issue ODR failures diagnostics for enums.
11882 for (auto &Merge : EnumOdrMergeFailures) {
11883 enum ODREnumDifference {
11884 SingleScopedEnum,
11885 EnumTagKeywordMismatch,
11886 SingleSpecifiedType,
11887 DifferentSpecifiedTypes,
11888 DifferentNumberEnumConstants,
11889 EnumConstantName,
11890 EnumConstantSingleInitilizer,
11891 EnumConstantDifferentInitilizer,
11892 };
11893
11894 // If we've already pointed out a specific problem with this enum, don't
11895 // bother issuing a general "something's different" diagnostic.
11896 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11897 continue;
11898
11899 EnumDecl *FirstEnum = Merge.first;
11900 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11901
11902 using DeclHashes =
11903 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11904 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11905 DeclHashes &Hashes, EnumDecl *Enum) {
11906 for (auto *D : Enum->decls()) {
11907 // Due to decl merging, the first EnumDecl is the parent of
11908 // Decls in both records.
11909 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11910 continue;
11911 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11912 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11913 ComputeSubDeclODRHash(D));
11914 }
11915 };
11916 DeclHashes FirstHashes;
11917 PopulateHashes(FirstHashes, FirstEnum);
11918 bool Diagnosed = false;
11919 for (auto &SecondEnum : Merge.second) {
11920
11921 if (FirstEnum == SecondEnum)
11922 continue;
11923
11924 std::string SecondModule =
11925 getOwningModuleNameForDiagnostic(SecondEnum);
11926
11927 auto ODRDiagError = [FirstEnum, &FirstModule,
11928 this](SourceLocation Loc, SourceRange Range,
11929 ODREnumDifference DiffType) {
11930 return Diag(Loc, diag::err_module_odr_violation_enum)
11931 << FirstEnum << FirstModule.empty() << FirstModule << Range
11932 << DiffType;
11933 };
11934 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11935 SourceRange Range,
11936 ODREnumDifference DiffType) {
11937 return Diag(Loc, diag::note_module_odr_violation_enum)
11938 << SecondModule << Range << DiffType;
11939 };
11940
11941 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11942 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11943 SingleScopedEnum)
11944 << FirstEnum->isScoped();
11945 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11946 SingleScopedEnum)
11947 << SecondEnum->isScoped();
11948 Diagnosed = true;
11949 continue;
11950 }
11951
11952 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11953 if (FirstEnum->isScopedUsingClassTag() !=
11954 SecondEnum->isScopedUsingClassTag()) {
11955 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11956 EnumTagKeywordMismatch)
11957 << FirstEnum->isScopedUsingClassTag();
11958 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11959 EnumTagKeywordMismatch)
11960 << SecondEnum->isScopedUsingClassTag();
11961 Diagnosed = true;
11962 continue;
11963 }
11964 }
11965
11966 QualType FirstUnderlyingType =
11967 FirstEnum->getIntegerTypeSourceInfo()
11968 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11969 : QualType();
11970 QualType SecondUnderlyingType =
11971 SecondEnum->getIntegerTypeSourceInfo()
11972 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11973 : QualType();
11974 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11975 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11976 SingleSpecifiedType)
11977 << !FirstUnderlyingType.isNull();
11978 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11979 SingleSpecifiedType)
11980 << !SecondUnderlyingType.isNull();
11981 Diagnosed = true;
11982 continue;
11983 }
11984
11985 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11986 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11987 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11988 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11989 DifferentSpecifiedTypes)
11990 << FirstUnderlyingType;
11991 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11992 DifferentSpecifiedTypes)
11993 << SecondUnderlyingType;
11994 Diagnosed = true;
11995 continue;
11996 }
11997 }
11998
11999 DeclHashes SecondHashes;
12000 PopulateHashes(SecondHashes, SecondEnum);
12001
12002 if (FirstHashes.size() != SecondHashes.size()) {
12003 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12004 DifferentNumberEnumConstants)
12005 << (int)FirstHashes.size();
12006 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12007 DifferentNumberEnumConstants)
12008 << (int)SecondHashes.size();
12009 Diagnosed = true;
12010 continue;
12011 }
12012
12013 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
12014 if (FirstHashes[I].second == SecondHashes[I].second)
12015 continue;
12016 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
12017 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
12018
12019 if (FirstEnumConstant->getDeclName() !=
12020 SecondEnumConstant->getDeclName()) {
12021
12022 ODRDiagError(FirstEnumConstant->getLocation(),
12023 FirstEnumConstant->getSourceRange(), EnumConstantName)
12024 << I + 1 << FirstEnumConstant;
12025 ODRDiagNote(SecondEnumConstant->getLocation(),
12026 SecondEnumConstant->getSourceRange(), EnumConstantName)
12027 << I + 1 << SecondEnumConstant;
12028 Diagnosed = true;
12029 break;
12030 }
12031
12032 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
12033 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
12034 if (!FirstInit && !SecondInit)
12035 continue;
12036
12037 if (!FirstInit || !SecondInit) {
12038 ODRDiagError(FirstEnumConstant->getLocation(),
12039 FirstEnumConstant->getSourceRange(),
12040 EnumConstantSingleInitilizer)
12041 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
12042 ODRDiagNote(SecondEnumConstant->getLocation(),
12043 SecondEnumConstant->getSourceRange(),
12044 EnumConstantSingleInitilizer)
12045 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
12046 Diagnosed = true;
12047 break;
12048 }
12049
12050 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
12051 ODRDiagError(FirstEnumConstant->getLocation(),
12052 FirstEnumConstant->getSourceRange(),
12053 EnumConstantDifferentInitilizer)
12054 << I + 1 << FirstEnumConstant;
12055 ODRDiagNote(SecondEnumConstant->getLocation(),
12056 SecondEnumConstant->getSourceRange(),
12057 EnumConstantDifferentInitilizer)
12058 << I + 1 << SecondEnumConstant;
12059 Diagnosed = true;
12060 break;
12061 }
12062 }
12063 }
12064
12065 (void)Diagnosed;
12066 assert(Diagnosed && "Unable to emit ODR diagnostic.");
12067 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012068}
12069
Richard Smithce18a182015-07-14 00:26:00 +000012070void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000012071 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000012072 ReadTimer->startTimer();
12073}
12074
Guy Benyei11169dd2012-12-18 14:30:41 +000012075void ASTReader::FinishedDeserializing() {
12076 assert(NumCurrentElementsDeserializing &&
12077 "FinishedDeserializing not paired with StartedDeserializing");
12078 if (NumCurrentElementsDeserializing == 1) {
12079 // We decrease NumCurrentElementsDeserializing only after pending actions
12080 // are finished, to avoid recursively re-calling finishPendingActions().
12081 finishPendingActions();
12082 }
12083 --NumCurrentElementsDeserializing;
12084
Richard Smitha0ce9c42014-07-29 23:23:27 +000012085 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000012086 // Propagate exception specification and deduced type updates along
12087 // redeclaration chains.
12088 //
12089 // We do this now rather than in finishPendingActions because we want to
12090 // be able to walk the complete redeclaration chains of the updated decls.
12091 while (!PendingExceptionSpecUpdates.empty() ||
12092 !PendingDeducedTypeUpdates.empty()) {
12093 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000012094 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000012095 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000012096 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000012097 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000012098 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000012099 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000012100 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000012101 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000012102 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000012103 }
Richard Smitha62d1982018-08-03 01:00:01 +000012104
12105 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
12106 PendingDeducedTypeUpdates.clear();
12107 for (auto Update : DTUpdates) {
12108 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
12109 // FIXME: If the return type is already deduced, check that it matches.
12110 getContext().adjustDeducedFunctionResultType(Update.first,
12111 Update.second);
12112 }
Richard Smith9e2341d2015-03-23 03:25:59 +000012113 }
12114
Richard Smithce18a182015-07-14 00:26:00 +000012115 if (ReadTimer)
12116 ReadTimer->stopTimer();
12117
Richard Smith0f4e2c42015-08-06 04:23:48 +000012118 diagnoseOdrViolations();
12119
Richard Smith04d05b52014-03-23 00:27:18 +000012120 // We are not in recursive loading, so it's safe to pass the "interesting"
12121 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000012122 if (Consumer)
12123 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000012124 }
12125}
12126
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012127void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000012128 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
12129 // Remove any fake results before adding any real ones.
12130 auto It = PendingFakeLookupResults.find(II);
12131 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000012132 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000012133 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000012134 // FIXME: this works around module+PCH performance issue.
12135 // Rather than erase the result from the map, which is O(n), just clear
12136 // the vector of NamedDecls.
12137 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000012138 }
12139 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012140
12141 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
12142 SemaObj->TUScope->AddDecl(D);
12143 } else if (SemaObj->TUScope) {
12144 // Adding the decl to IdResolver may have failed because it was already in
12145 // (even though it was not added in scope). If it is already in, make sure
12146 // it gets in the scope as well.
12147 if (std::find(SemaObj->IdResolver.begin(Name),
12148 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
12149 SemaObj->TUScope->AddDecl(D);
12150 }
12151}
12152
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012153ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
12154 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000012155 const PCHContainerReader &PCHContainerRdr,
12156 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
12157 StringRef isysroot, bool DisableValidation,
12158 bool AllowASTWithCompilerErrors,
12159 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
12160 bool UseGlobalIndex,
12161 std::unique_ptr<llvm::Timer> ReadTimer)
12162 : Listener(DisableValidation
12163 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
12164 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000012165 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012166 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012167 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
12168 PCHContainerRdr, PP.getHeaderSearchInfo()),
12169 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000012170 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000012171 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
12172 AllowConfigurationMismatch(AllowConfigurationMismatch),
12173 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012174 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000012175 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000012176
12177 for (const auto &Ext : Extensions) {
12178 auto BlockName = Ext->getExtensionMetadata().BlockName;
12179 auto Known = ModuleFileExtensions.find(BlockName);
12180 if (Known != ModuleFileExtensions.end()) {
12181 Diags.Report(diag::warn_duplicate_module_file_extension)
12182 << BlockName;
12183 continue;
12184 }
12185
12186 ModuleFileExtensions.insert({BlockName, Ext});
12187 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012188}
12189
12190ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000012191 if (OwnsDeserializationListener)
12192 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000012193}
Richard Smith10379092016-05-06 23:14:07 +000012194
12195IdentifierResolver &ASTReader::getIdResolver() {
12196 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
12197}
David L. Jonesbe1557a2016-12-21 00:17:49 +000012198
JF Bastien0e828952019-06-26 19:50:12 +000012199Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
12200 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000012201 Idx = 0;
12202 Record.clear();
12203 return Cursor.readRecord(AbbrevID, Record);
12204}
Kelvin Libe286f52018-09-15 13:54:15 +000012205//===----------------------------------------------------------------------===//
12206//// OMPClauseReader implementation
12207////===----------------------------------------------------------------------===//
12208
12209OMPClause *OMPClauseReader::readClause() {
12210 OMPClause *C;
12211 switch (Record.readInt()) {
12212 case OMPC_if:
12213 C = new (Context) OMPIfClause();
12214 break;
12215 case OMPC_final:
12216 C = new (Context) OMPFinalClause();
12217 break;
12218 case OMPC_num_threads:
12219 C = new (Context) OMPNumThreadsClause();
12220 break;
12221 case OMPC_safelen:
12222 C = new (Context) OMPSafelenClause();
12223 break;
12224 case OMPC_simdlen:
12225 C = new (Context) OMPSimdlenClause();
12226 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012227 case OMPC_allocator:
12228 C = new (Context) OMPAllocatorClause();
12229 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012230 case OMPC_collapse:
12231 C = new (Context) OMPCollapseClause();
12232 break;
12233 case OMPC_default:
12234 C = new (Context) OMPDefaultClause();
12235 break;
12236 case OMPC_proc_bind:
12237 C = new (Context) OMPProcBindClause();
12238 break;
12239 case OMPC_schedule:
12240 C = new (Context) OMPScheduleClause();
12241 break;
12242 case OMPC_ordered:
12243 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
12244 break;
12245 case OMPC_nowait:
12246 C = new (Context) OMPNowaitClause();
12247 break;
12248 case OMPC_untied:
12249 C = new (Context) OMPUntiedClause();
12250 break;
12251 case OMPC_mergeable:
12252 C = new (Context) OMPMergeableClause();
12253 break;
12254 case OMPC_read:
12255 C = new (Context) OMPReadClause();
12256 break;
12257 case OMPC_write:
12258 C = new (Context) OMPWriteClause();
12259 break;
12260 case OMPC_update:
12261 C = new (Context) OMPUpdateClause();
12262 break;
12263 case OMPC_capture:
12264 C = new (Context) OMPCaptureClause();
12265 break;
12266 case OMPC_seq_cst:
12267 C = new (Context) OMPSeqCstClause();
12268 break;
12269 case OMPC_threads:
12270 C = new (Context) OMPThreadsClause();
12271 break;
12272 case OMPC_simd:
12273 C = new (Context) OMPSIMDClause();
12274 break;
12275 case OMPC_nogroup:
12276 C = new (Context) OMPNogroupClause();
12277 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012278 case OMPC_unified_address:
12279 C = new (Context) OMPUnifiedAddressClause();
12280 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012281 case OMPC_unified_shared_memory:
12282 C = new (Context) OMPUnifiedSharedMemoryClause();
12283 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012284 case OMPC_reverse_offload:
12285 C = new (Context) OMPReverseOffloadClause();
12286 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012287 case OMPC_dynamic_allocators:
12288 C = new (Context) OMPDynamicAllocatorsClause();
12289 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012290 case OMPC_atomic_default_mem_order:
12291 C = new (Context) OMPAtomicDefaultMemOrderClause();
12292 break;
12293 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000012294 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
12295 break;
12296 case OMPC_firstprivate:
12297 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
12298 break;
12299 case OMPC_lastprivate:
12300 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
12301 break;
12302 case OMPC_shared:
12303 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
12304 break;
12305 case OMPC_reduction:
12306 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
12307 break;
12308 case OMPC_task_reduction:
12309 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
12310 break;
12311 case OMPC_in_reduction:
12312 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
12313 break;
12314 case OMPC_linear:
12315 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
12316 break;
12317 case OMPC_aligned:
12318 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
12319 break;
12320 case OMPC_copyin:
12321 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
12322 break;
12323 case OMPC_copyprivate:
12324 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
12325 break;
12326 case OMPC_flush:
12327 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
12328 break;
12329 case OMPC_depend: {
12330 unsigned NumVars = Record.readInt();
12331 unsigned NumLoops = Record.readInt();
12332 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
12333 break;
12334 }
12335 case OMPC_device:
12336 C = new (Context) OMPDeviceClause();
12337 break;
12338 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012339 OMPMappableExprListSizeTy Sizes;
12340 Sizes.NumVars = Record.readInt();
12341 Sizes.NumUniqueDeclarations = Record.readInt();
12342 Sizes.NumComponentLists = Record.readInt();
12343 Sizes.NumComponents = Record.readInt();
12344 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012345 break;
12346 }
12347 case OMPC_num_teams:
12348 C = new (Context) OMPNumTeamsClause();
12349 break;
12350 case OMPC_thread_limit:
12351 C = new (Context) OMPThreadLimitClause();
12352 break;
12353 case OMPC_priority:
12354 C = new (Context) OMPPriorityClause();
12355 break;
12356 case OMPC_grainsize:
12357 C = new (Context) OMPGrainsizeClause();
12358 break;
12359 case OMPC_num_tasks:
12360 C = new (Context) OMPNumTasksClause();
12361 break;
12362 case OMPC_hint:
12363 C = new (Context) OMPHintClause();
12364 break;
12365 case OMPC_dist_schedule:
12366 C = new (Context) OMPDistScheduleClause();
12367 break;
12368 case OMPC_defaultmap:
12369 C = new (Context) OMPDefaultmapClause();
12370 break;
12371 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012372 OMPMappableExprListSizeTy Sizes;
12373 Sizes.NumVars = Record.readInt();
12374 Sizes.NumUniqueDeclarations = Record.readInt();
12375 Sizes.NumComponentLists = Record.readInt();
12376 Sizes.NumComponents = Record.readInt();
12377 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012378 break;
12379 }
12380 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012381 OMPMappableExprListSizeTy Sizes;
12382 Sizes.NumVars = Record.readInt();
12383 Sizes.NumUniqueDeclarations = Record.readInt();
12384 Sizes.NumComponentLists = Record.readInt();
12385 Sizes.NumComponents = Record.readInt();
12386 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012387 break;
12388 }
12389 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012390 OMPMappableExprListSizeTy Sizes;
12391 Sizes.NumVars = Record.readInt();
12392 Sizes.NumUniqueDeclarations = Record.readInt();
12393 Sizes.NumComponentLists = Record.readInt();
12394 Sizes.NumComponents = Record.readInt();
12395 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012396 break;
12397 }
12398 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012399 OMPMappableExprListSizeTy Sizes;
12400 Sizes.NumVars = Record.readInt();
12401 Sizes.NumUniqueDeclarations = Record.readInt();
12402 Sizes.NumComponentLists = Record.readInt();
12403 Sizes.NumComponents = Record.readInt();
12404 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012405 break;
12406 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000012407 case OMPC_allocate:
12408 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
12409 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012410 }
12411 Visit(C);
12412 C->setLocStart(Record.readSourceLocation());
12413 C->setLocEnd(Record.readSourceLocation());
12414
12415 return C;
12416}
12417
12418void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12419 C->setPreInitStmt(Record.readSubStmt(),
12420 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12421}
12422
12423void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12424 VisitOMPClauseWithPreInit(C);
12425 C->setPostUpdateExpr(Record.readSubExpr());
12426}
12427
12428void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12429 VisitOMPClauseWithPreInit(C);
12430 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12431 C->setNameModifierLoc(Record.readSourceLocation());
12432 C->setColonLoc(Record.readSourceLocation());
12433 C->setCondition(Record.readSubExpr());
12434 C->setLParenLoc(Record.readSourceLocation());
12435}
12436
12437void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12438 C->setCondition(Record.readSubExpr());
12439 C->setLParenLoc(Record.readSourceLocation());
12440}
12441
12442void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12443 VisitOMPClauseWithPreInit(C);
12444 C->setNumThreads(Record.readSubExpr());
12445 C->setLParenLoc(Record.readSourceLocation());
12446}
12447
12448void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12449 C->setSafelen(Record.readSubExpr());
12450 C->setLParenLoc(Record.readSourceLocation());
12451}
12452
12453void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12454 C->setSimdlen(Record.readSubExpr());
12455 C->setLParenLoc(Record.readSourceLocation());
12456}
12457
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012458void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12459 C->setAllocator(Record.readExpr());
12460 C->setLParenLoc(Record.readSourceLocation());
12461}
12462
Kelvin Libe286f52018-09-15 13:54:15 +000012463void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12464 C->setNumForLoops(Record.readSubExpr());
12465 C->setLParenLoc(Record.readSourceLocation());
12466}
12467
12468void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12469 C->setDefaultKind(
12470 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12471 C->setLParenLoc(Record.readSourceLocation());
12472 C->setDefaultKindKwLoc(Record.readSourceLocation());
12473}
12474
12475void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12476 C->setProcBindKind(
12477 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12478 C->setLParenLoc(Record.readSourceLocation());
12479 C->setProcBindKindKwLoc(Record.readSourceLocation());
12480}
12481
12482void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12483 VisitOMPClauseWithPreInit(C);
12484 C->setScheduleKind(
12485 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12486 C->setFirstScheduleModifier(
12487 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12488 C->setSecondScheduleModifier(
12489 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12490 C->setChunkSize(Record.readSubExpr());
12491 C->setLParenLoc(Record.readSourceLocation());
12492 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12493 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12494 C->setScheduleKindLoc(Record.readSourceLocation());
12495 C->setCommaLoc(Record.readSourceLocation());
12496}
12497
12498void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12499 C->setNumForLoops(Record.readSubExpr());
12500 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12501 C->setLoopNumIterations(I, Record.readSubExpr());
12502 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12503 C->setLoopCounter(I, Record.readSubExpr());
12504 C->setLParenLoc(Record.readSourceLocation());
12505}
12506
12507void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12508
12509void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12510
12511void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12512
12513void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12514
12515void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12516
12517void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12518
12519void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12520
12521void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12522
12523void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12524
12525void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12526
12527void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12528
Kelvin Li1408f912018-09-26 04:28:39 +000012529void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12530
Patrick Lyster4a370b92018-10-01 13:47:43 +000012531void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12532 OMPUnifiedSharedMemoryClause *) {}
12533
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012534void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12535
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012536void
12537OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12538}
12539
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012540void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12541 OMPAtomicDefaultMemOrderClause *C) {
12542 C->setAtomicDefaultMemOrderKind(
12543 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12544 C->setLParenLoc(Record.readSourceLocation());
12545 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12546}
12547
Kelvin Libe286f52018-09-15 13:54:15 +000012548void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12549 C->setLParenLoc(Record.readSourceLocation());
12550 unsigned NumVars = C->varlist_size();
12551 SmallVector<Expr *, 16> Vars;
12552 Vars.reserve(NumVars);
12553 for (unsigned i = 0; i != NumVars; ++i)
12554 Vars.push_back(Record.readSubExpr());
12555 C->setVarRefs(Vars);
12556 Vars.clear();
12557 for (unsigned i = 0; i != NumVars; ++i)
12558 Vars.push_back(Record.readSubExpr());
12559 C->setPrivateCopies(Vars);
12560}
12561
12562void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12563 VisitOMPClauseWithPreInit(C);
12564 C->setLParenLoc(Record.readSourceLocation());
12565 unsigned NumVars = C->varlist_size();
12566 SmallVector<Expr *, 16> Vars;
12567 Vars.reserve(NumVars);
12568 for (unsigned i = 0; i != NumVars; ++i)
12569 Vars.push_back(Record.readSubExpr());
12570 C->setVarRefs(Vars);
12571 Vars.clear();
12572 for (unsigned i = 0; i != NumVars; ++i)
12573 Vars.push_back(Record.readSubExpr());
12574 C->setPrivateCopies(Vars);
12575 Vars.clear();
12576 for (unsigned i = 0; i != NumVars; ++i)
12577 Vars.push_back(Record.readSubExpr());
12578 C->setInits(Vars);
12579}
12580
12581void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12582 VisitOMPClauseWithPostUpdate(C);
12583 C->setLParenLoc(Record.readSourceLocation());
12584 unsigned NumVars = C->varlist_size();
12585 SmallVector<Expr *, 16> Vars;
12586 Vars.reserve(NumVars);
12587 for (unsigned i = 0; i != NumVars; ++i)
12588 Vars.push_back(Record.readSubExpr());
12589 C->setVarRefs(Vars);
12590 Vars.clear();
12591 for (unsigned i = 0; i != NumVars; ++i)
12592 Vars.push_back(Record.readSubExpr());
12593 C->setPrivateCopies(Vars);
12594 Vars.clear();
12595 for (unsigned i = 0; i != NumVars; ++i)
12596 Vars.push_back(Record.readSubExpr());
12597 C->setSourceExprs(Vars);
12598 Vars.clear();
12599 for (unsigned i = 0; i != NumVars; ++i)
12600 Vars.push_back(Record.readSubExpr());
12601 C->setDestinationExprs(Vars);
12602 Vars.clear();
12603 for (unsigned i = 0; i != NumVars; ++i)
12604 Vars.push_back(Record.readSubExpr());
12605 C->setAssignmentOps(Vars);
12606}
12607
12608void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12609 C->setLParenLoc(Record.readSourceLocation());
12610 unsigned NumVars = C->varlist_size();
12611 SmallVector<Expr *, 16> Vars;
12612 Vars.reserve(NumVars);
12613 for (unsigned i = 0; i != NumVars; ++i)
12614 Vars.push_back(Record.readSubExpr());
12615 C->setVarRefs(Vars);
12616}
12617
12618void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12619 VisitOMPClauseWithPostUpdate(C);
12620 C->setLParenLoc(Record.readSourceLocation());
12621 C->setColonLoc(Record.readSourceLocation());
12622 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12623 DeclarationNameInfo DNI;
12624 Record.readDeclarationNameInfo(DNI);
12625 C->setQualifierLoc(NNSL);
12626 C->setNameInfo(DNI);
12627
12628 unsigned NumVars = C->varlist_size();
12629 SmallVector<Expr *, 16> Vars;
12630 Vars.reserve(NumVars);
12631 for (unsigned i = 0; i != NumVars; ++i)
12632 Vars.push_back(Record.readSubExpr());
12633 C->setVarRefs(Vars);
12634 Vars.clear();
12635 for (unsigned i = 0; i != NumVars; ++i)
12636 Vars.push_back(Record.readSubExpr());
12637 C->setPrivates(Vars);
12638 Vars.clear();
12639 for (unsigned i = 0; i != NumVars; ++i)
12640 Vars.push_back(Record.readSubExpr());
12641 C->setLHSExprs(Vars);
12642 Vars.clear();
12643 for (unsigned i = 0; i != NumVars; ++i)
12644 Vars.push_back(Record.readSubExpr());
12645 C->setRHSExprs(Vars);
12646 Vars.clear();
12647 for (unsigned i = 0; i != NumVars; ++i)
12648 Vars.push_back(Record.readSubExpr());
12649 C->setReductionOps(Vars);
12650}
12651
12652void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12653 VisitOMPClauseWithPostUpdate(C);
12654 C->setLParenLoc(Record.readSourceLocation());
12655 C->setColonLoc(Record.readSourceLocation());
12656 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12657 DeclarationNameInfo DNI;
12658 Record.readDeclarationNameInfo(DNI);
12659 C->setQualifierLoc(NNSL);
12660 C->setNameInfo(DNI);
12661
12662 unsigned NumVars = C->varlist_size();
12663 SmallVector<Expr *, 16> Vars;
12664 Vars.reserve(NumVars);
12665 for (unsigned I = 0; I != NumVars; ++I)
12666 Vars.push_back(Record.readSubExpr());
12667 C->setVarRefs(Vars);
12668 Vars.clear();
12669 for (unsigned I = 0; I != NumVars; ++I)
12670 Vars.push_back(Record.readSubExpr());
12671 C->setPrivates(Vars);
12672 Vars.clear();
12673 for (unsigned I = 0; I != NumVars; ++I)
12674 Vars.push_back(Record.readSubExpr());
12675 C->setLHSExprs(Vars);
12676 Vars.clear();
12677 for (unsigned I = 0; I != NumVars; ++I)
12678 Vars.push_back(Record.readSubExpr());
12679 C->setRHSExprs(Vars);
12680 Vars.clear();
12681 for (unsigned I = 0; I != NumVars; ++I)
12682 Vars.push_back(Record.readSubExpr());
12683 C->setReductionOps(Vars);
12684}
12685
12686void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12687 VisitOMPClauseWithPostUpdate(C);
12688 C->setLParenLoc(Record.readSourceLocation());
12689 C->setColonLoc(Record.readSourceLocation());
12690 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12691 DeclarationNameInfo DNI;
12692 Record.readDeclarationNameInfo(DNI);
12693 C->setQualifierLoc(NNSL);
12694 C->setNameInfo(DNI);
12695
12696 unsigned NumVars = C->varlist_size();
12697 SmallVector<Expr *, 16> Vars;
12698 Vars.reserve(NumVars);
12699 for (unsigned I = 0; I != NumVars; ++I)
12700 Vars.push_back(Record.readSubExpr());
12701 C->setVarRefs(Vars);
12702 Vars.clear();
12703 for (unsigned I = 0; I != NumVars; ++I)
12704 Vars.push_back(Record.readSubExpr());
12705 C->setPrivates(Vars);
12706 Vars.clear();
12707 for (unsigned I = 0; I != NumVars; ++I)
12708 Vars.push_back(Record.readSubExpr());
12709 C->setLHSExprs(Vars);
12710 Vars.clear();
12711 for (unsigned I = 0; I != NumVars; ++I)
12712 Vars.push_back(Record.readSubExpr());
12713 C->setRHSExprs(Vars);
12714 Vars.clear();
12715 for (unsigned I = 0; I != NumVars; ++I)
12716 Vars.push_back(Record.readSubExpr());
12717 C->setReductionOps(Vars);
12718 Vars.clear();
12719 for (unsigned I = 0; I != NumVars; ++I)
12720 Vars.push_back(Record.readSubExpr());
12721 C->setTaskgroupDescriptors(Vars);
12722}
12723
12724void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12725 VisitOMPClauseWithPostUpdate(C);
12726 C->setLParenLoc(Record.readSourceLocation());
12727 C->setColonLoc(Record.readSourceLocation());
12728 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12729 C->setModifierLoc(Record.readSourceLocation());
12730 unsigned NumVars = C->varlist_size();
12731 SmallVector<Expr *, 16> Vars;
12732 Vars.reserve(NumVars);
12733 for (unsigned i = 0; i != NumVars; ++i)
12734 Vars.push_back(Record.readSubExpr());
12735 C->setVarRefs(Vars);
12736 Vars.clear();
12737 for (unsigned i = 0; i != NumVars; ++i)
12738 Vars.push_back(Record.readSubExpr());
12739 C->setPrivates(Vars);
12740 Vars.clear();
12741 for (unsigned i = 0; i != NumVars; ++i)
12742 Vars.push_back(Record.readSubExpr());
12743 C->setInits(Vars);
12744 Vars.clear();
12745 for (unsigned i = 0; i != NumVars; ++i)
12746 Vars.push_back(Record.readSubExpr());
12747 C->setUpdates(Vars);
12748 Vars.clear();
12749 for (unsigned i = 0; i != NumVars; ++i)
12750 Vars.push_back(Record.readSubExpr());
12751 C->setFinals(Vars);
12752 C->setStep(Record.readSubExpr());
12753 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012754 Vars.clear();
12755 for (unsigned I = 0; I != NumVars + 1; ++I)
12756 Vars.push_back(Record.readSubExpr());
12757 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012758}
12759
12760void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12761 C->setLParenLoc(Record.readSourceLocation());
12762 C->setColonLoc(Record.readSourceLocation());
12763 unsigned NumVars = C->varlist_size();
12764 SmallVector<Expr *, 16> Vars;
12765 Vars.reserve(NumVars);
12766 for (unsigned i = 0; i != NumVars; ++i)
12767 Vars.push_back(Record.readSubExpr());
12768 C->setVarRefs(Vars);
12769 C->setAlignment(Record.readSubExpr());
12770}
12771
12772void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12773 C->setLParenLoc(Record.readSourceLocation());
12774 unsigned NumVars = C->varlist_size();
12775 SmallVector<Expr *, 16> Exprs;
12776 Exprs.reserve(NumVars);
12777 for (unsigned i = 0; i != NumVars; ++i)
12778 Exprs.push_back(Record.readSubExpr());
12779 C->setVarRefs(Exprs);
12780 Exprs.clear();
12781 for (unsigned i = 0; i != NumVars; ++i)
12782 Exprs.push_back(Record.readSubExpr());
12783 C->setSourceExprs(Exprs);
12784 Exprs.clear();
12785 for (unsigned i = 0; i != NumVars; ++i)
12786 Exprs.push_back(Record.readSubExpr());
12787 C->setDestinationExprs(Exprs);
12788 Exprs.clear();
12789 for (unsigned i = 0; i != NumVars; ++i)
12790 Exprs.push_back(Record.readSubExpr());
12791 C->setAssignmentOps(Exprs);
12792}
12793
12794void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12795 C->setLParenLoc(Record.readSourceLocation());
12796 unsigned NumVars = C->varlist_size();
12797 SmallVector<Expr *, 16> Exprs;
12798 Exprs.reserve(NumVars);
12799 for (unsigned i = 0; i != NumVars; ++i)
12800 Exprs.push_back(Record.readSubExpr());
12801 C->setVarRefs(Exprs);
12802 Exprs.clear();
12803 for (unsigned i = 0; i != NumVars; ++i)
12804 Exprs.push_back(Record.readSubExpr());
12805 C->setSourceExprs(Exprs);
12806 Exprs.clear();
12807 for (unsigned i = 0; i != NumVars; ++i)
12808 Exprs.push_back(Record.readSubExpr());
12809 C->setDestinationExprs(Exprs);
12810 Exprs.clear();
12811 for (unsigned i = 0; i != NumVars; ++i)
12812 Exprs.push_back(Record.readSubExpr());
12813 C->setAssignmentOps(Exprs);
12814}
12815
12816void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12817 C->setLParenLoc(Record.readSourceLocation());
12818 unsigned NumVars = C->varlist_size();
12819 SmallVector<Expr *, 16> Vars;
12820 Vars.reserve(NumVars);
12821 for (unsigned i = 0; i != NumVars; ++i)
12822 Vars.push_back(Record.readSubExpr());
12823 C->setVarRefs(Vars);
12824}
12825
12826void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12827 C->setLParenLoc(Record.readSourceLocation());
12828 C->setDependencyKind(
12829 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12830 C->setDependencyLoc(Record.readSourceLocation());
12831 C->setColonLoc(Record.readSourceLocation());
12832 unsigned NumVars = C->varlist_size();
12833 SmallVector<Expr *, 16> Vars;
12834 Vars.reserve(NumVars);
12835 for (unsigned I = 0; I != NumVars; ++I)
12836 Vars.push_back(Record.readSubExpr());
12837 C->setVarRefs(Vars);
12838 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12839 C->setLoopData(I, Record.readSubExpr());
12840}
12841
12842void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12843 VisitOMPClauseWithPreInit(C);
12844 C->setDevice(Record.readSubExpr());
12845 C->setLParenLoc(Record.readSourceLocation());
12846}
12847
12848void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12849 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012850 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12851 C->setMapTypeModifier(
12852 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12853 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12854 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012855 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12856 DeclarationNameInfo DNI;
12857 Record.readDeclarationNameInfo(DNI);
12858 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012859 C->setMapType(
12860 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12861 C->setMapLoc(Record.readSourceLocation());
12862 C->setColonLoc(Record.readSourceLocation());
12863 auto NumVars = C->varlist_size();
12864 auto UniqueDecls = C->getUniqueDeclarationsNum();
12865 auto TotalLists = C->getTotalComponentListNum();
12866 auto TotalComponents = C->getTotalComponentsNum();
12867
12868 SmallVector<Expr *, 16> Vars;
12869 Vars.reserve(NumVars);
12870 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012871 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012872 C->setVarRefs(Vars);
12873
Michael Kruse4304e9d2019-02-19 16:38:20 +000012874 SmallVector<Expr *, 16> UDMappers;
12875 UDMappers.reserve(NumVars);
12876 for (unsigned I = 0; I < NumVars; ++I)
12877 UDMappers.push_back(Record.readExpr());
12878 C->setUDMapperRefs(UDMappers);
12879
Kelvin Libe286f52018-09-15 13:54:15 +000012880 SmallVector<ValueDecl *, 16> Decls;
12881 Decls.reserve(UniqueDecls);
12882 for (unsigned i = 0; i < UniqueDecls; ++i)
12883 Decls.push_back(Record.readDeclAs<ValueDecl>());
12884 C->setUniqueDecls(Decls);
12885
12886 SmallVector<unsigned, 16> ListsPerDecl;
12887 ListsPerDecl.reserve(UniqueDecls);
12888 for (unsigned i = 0; i < UniqueDecls; ++i)
12889 ListsPerDecl.push_back(Record.readInt());
12890 C->setDeclNumLists(ListsPerDecl);
12891
12892 SmallVector<unsigned, 32> ListSizes;
12893 ListSizes.reserve(TotalLists);
12894 for (unsigned i = 0; i < TotalLists; ++i)
12895 ListSizes.push_back(Record.readInt());
12896 C->setComponentListSizes(ListSizes);
12897
12898 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12899 Components.reserve(TotalComponents);
12900 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012901 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012902 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12903 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12904 AssociatedExpr, AssociatedDecl));
12905 }
12906 C->setComponents(Components, ListSizes);
12907}
12908
Alexey Bataeve04483e2019-03-27 14:14:31 +000012909void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12910 C->setLParenLoc(Record.readSourceLocation());
12911 C->setColonLoc(Record.readSourceLocation());
12912 C->setAllocator(Record.readSubExpr());
12913 unsigned NumVars = C->varlist_size();
12914 SmallVector<Expr *, 16> Vars;
12915 Vars.reserve(NumVars);
12916 for (unsigned i = 0; i != NumVars; ++i)
12917 Vars.push_back(Record.readSubExpr());
12918 C->setVarRefs(Vars);
12919}
12920
Kelvin Libe286f52018-09-15 13:54:15 +000012921void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12922 VisitOMPClauseWithPreInit(C);
12923 C->setNumTeams(Record.readSubExpr());
12924 C->setLParenLoc(Record.readSourceLocation());
12925}
12926
12927void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12928 VisitOMPClauseWithPreInit(C);
12929 C->setThreadLimit(Record.readSubExpr());
12930 C->setLParenLoc(Record.readSourceLocation());
12931}
12932
12933void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12934 C->setPriority(Record.readSubExpr());
12935 C->setLParenLoc(Record.readSourceLocation());
12936}
12937
12938void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12939 C->setGrainsize(Record.readSubExpr());
12940 C->setLParenLoc(Record.readSourceLocation());
12941}
12942
12943void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12944 C->setNumTasks(Record.readSubExpr());
12945 C->setLParenLoc(Record.readSourceLocation());
12946}
12947
12948void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12949 C->setHint(Record.readSubExpr());
12950 C->setLParenLoc(Record.readSourceLocation());
12951}
12952
12953void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12954 VisitOMPClauseWithPreInit(C);
12955 C->setDistScheduleKind(
12956 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12957 C->setChunkSize(Record.readSubExpr());
12958 C->setLParenLoc(Record.readSourceLocation());
12959 C->setDistScheduleKindLoc(Record.readSourceLocation());
12960 C->setCommaLoc(Record.readSourceLocation());
12961}
12962
12963void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12964 C->setDefaultmapKind(
12965 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12966 C->setDefaultmapModifier(
12967 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12968 C->setLParenLoc(Record.readSourceLocation());
12969 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12970 C->setDefaultmapKindLoc(Record.readSourceLocation());
12971}
12972
12973void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12974 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012975 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12976 DeclarationNameInfo DNI;
12977 Record.readDeclarationNameInfo(DNI);
12978 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012979 auto NumVars = C->varlist_size();
12980 auto UniqueDecls = C->getUniqueDeclarationsNum();
12981 auto TotalLists = C->getTotalComponentListNum();
12982 auto TotalComponents = C->getTotalComponentsNum();
12983
12984 SmallVector<Expr *, 16> Vars;
12985 Vars.reserve(NumVars);
12986 for (unsigned i = 0; i != NumVars; ++i)
12987 Vars.push_back(Record.readSubExpr());
12988 C->setVarRefs(Vars);
12989
Michael Kruse01f670d2019-02-22 22:29:42 +000012990 SmallVector<Expr *, 16> UDMappers;
12991 UDMappers.reserve(NumVars);
12992 for (unsigned I = 0; I < NumVars; ++I)
12993 UDMappers.push_back(Record.readSubExpr());
12994 C->setUDMapperRefs(UDMappers);
12995
Kelvin Libe286f52018-09-15 13:54:15 +000012996 SmallVector<ValueDecl *, 16> Decls;
12997 Decls.reserve(UniqueDecls);
12998 for (unsigned i = 0; i < UniqueDecls; ++i)
12999 Decls.push_back(Record.readDeclAs<ValueDecl>());
13000 C->setUniqueDecls(Decls);
13001
13002 SmallVector<unsigned, 16> ListsPerDecl;
13003 ListsPerDecl.reserve(UniqueDecls);
13004 for (unsigned i = 0; i < UniqueDecls; ++i)
13005 ListsPerDecl.push_back(Record.readInt());
13006 C->setDeclNumLists(ListsPerDecl);
13007
13008 SmallVector<unsigned, 32> ListSizes;
13009 ListSizes.reserve(TotalLists);
13010 for (unsigned i = 0; i < TotalLists; ++i)
13011 ListSizes.push_back(Record.readInt());
13012 C->setComponentListSizes(ListSizes);
13013
13014 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13015 Components.reserve(TotalComponents);
13016 for (unsigned i = 0; i < TotalComponents; ++i) {
13017 Expr *AssociatedExpr = Record.readSubExpr();
13018 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13019 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13020 AssociatedExpr, AssociatedDecl));
13021 }
13022 C->setComponents(Components, ListSizes);
13023}
13024
13025void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
13026 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000013027 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13028 DeclarationNameInfo DNI;
13029 Record.readDeclarationNameInfo(DNI);
13030 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013031 auto NumVars = C->varlist_size();
13032 auto UniqueDecls = C->getUniqueDeclarationsNum();
13033 auto TotalLists = C->getTotalComponentListNum();
13034 auto TotalComponents = C->getTotalComponentsNum();
13035
13036 SmallVector<Expr *, 16> Vars;
13037 Vars.reserve(NumVars);
13038 for (unsigned i = 0; i != NumVars; ++i)
13039 Vars.push_back(Record.readSubExpr());
13040 C->setVarRefs(Vars);
13041
Michael Kruse0336c752019-02-25 20:34:15 +000013042 SmallVector<Expr *, 16> UDMappers;
13043 UDMappers.reserve(NumVars);
13044 for (unsigned I = 0; I < NumVars; ++I)
13045 UDMappers.push_back(Record.readSubExpr());
13046 C->setUDMapperRefs(UDMappers);
13047
Kelvin Libe286f52018-09-15 13:54:15 +000013048 SmallVector<ValueDecl *, 16> Decls;
13049 Decls.reserve(UniqueDecls);
13050 for (unsigned i = 0; i < UniqueDecls; ++i)
13051 Decls.push_back(Record.readDeclAs<ValueDecl>());
13052 C->setUniqueDecls(Decls);
13053
13054 SmallVector<unsigned, 16> ListsPerDecl;
13055 ListsPerDecl.reserve(UniqueDecls);
13056 for (unsigned i = 0; i < UniqueDecls; ++i)
13057 ListsPerDecl.push_back(Record.readInt());
13058 C->setDeclNumLists(ListsPerDecl);
13059
13060 SmallVector<unsigned, 32> ListSizes;
13061 ListSizes.reserve(TotalLists);
13062 for (unsigned i = 0; i < TotalLists; ++i)
13063 ListSizes.push_back(Record.readInt());
13064 C->setComponentListSizes(ListSizes);
13065
13066 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13067 Components.reserve(TotalComponents);
13068 for (unsigned i = 0; i < TotalComponents; ++i) {
13069 Expr *AssociatedExpr = Record.readSubExpr();
13070 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13071 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13072 AssociatedExpr, AssociatedDecl));
13073 }
13074 C->setComponents(Components, ListSizes);
13075}
13076
13077void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13078 C->setLParenLoc(Record.readSourceLocation());
13079 auto NumVars = C->varlist_size();
13080 auto UniqueDecls = C->getUniqueDeclarationsNum();
13081 auto TotalLists = C->getTotalComponentListNum();
13082 auto TotalComponents = C->getTotalComponentsNum();
13083
13084 SmallVector<Expr *, 16> Vars;
13085 Vars.reserve(NumVars);
13086 for (unsigned i = 0; i != NumVars; ++i)
13087 Vars.push_back(Record.readSubExpr());
13088 C->setVarRefs(Vars);
13089 Vars.clear();
13090 for (unsigned i = 0; i != NumVars; ++i)
13091 Vars.push_back(Record.readSubExpr());
13092 C->setPrivateCopies(Vars);
13093 Vars.clear();
13094 for (unsigned i = 0; i != NumVars; ++i)
13095 Vars.push_back(Record.readSubExpr());
13096 C->setInits(Vars);
13097
13098 SmallVector<ValueDecl *, 16> Decls;
13099 Decls.reserve(UniqueDecls);
13100 for (unsigned i = 0; i < UniqueDecls; ++i)
13101 Decls.push_back(Record.readDeclAs<ValueDecl>());
13102 C->setUniqueDecls(Decls);
13103
13104 SmallVector<unsigned, 16> ListsPerDecl;
13105 ListsPerDecl.reserve(UniqueDecls);
13106 for (unsigned i = 0; i < UniqueDecls; ++i)
13107 ListsPerDecl.push_back(Record.readInt());
13108 C->setDeclNumLists(ListsPerDecl);
13109
13110 SmallVector<unsigned, 32> ListSizes;
13111 ListSizes.reserve(TotalLists);
13112 for (unsigned i = 0; i < TotalLists; ++i)
13113 ListSizes.push_back(Record.readInt());
13114 C->setComponentListSizes(ListSizes);
13115
13116 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13117 Components.reserve(TotalComponents);
13118 for (unsigned i = 0; i < TotalComponents; ++i) {
13119 Expr *AssociatedExpr = Record.readSubExpr();
13120 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13121 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13122 AssociatedExpr, AssociatedDecl));
13123 }
13124 C->setComponents(Components, ListSizes);
13125}
13126
13127void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13128 C->setLParenLoc(Record.readSourceLocation());
13129 auto NumVars = C->varlist_size();
13130 auto UniqueDecls = C->getUniqueDeclarationsNum();
13131 auto TotalLists = C->getTotalComponentListNum();
13132 auto TotalComponents = C->getTotalComponentsNum();
13133
13134 SmallVector<Expr *, 16> Vars;
13135 Vars.reserve(NumVars);
13136 for (unsigned i = 0; i != NumVars; ++i)
13137 Vars.push_back(Record.readSubExpr());
13138 C->setVarRefs(Vars);
13139 Vars.clear();
13140
13141 SmallVector<ValueDecl *, 16> Decls;
13142 Decls.reserve(UniqueDecls);
13143 for (unsigned i = 0; i < UniqueDecls; ++i)
13144 Decls.push_back(Record.readDeclAs<ValueDecl>());
13145 C->setUniqueDecls(Decls);
13146
13147 SmallVector<unsigned, 16> ListsPerDecl;
13148 ListsPerDecl.reserve(UniqueDecls);
13149 for (unsigned i = 0; i < UniqueDecls; ++i)
13150 ListsPerDecl.push_back(Record.readInt());
13151 C->setDeclNumLists(ListsPerDecl);
13152
13153 SmallVector<unsigned, 32> ListSizes;
13154 ListSizes.reserve(TotalLists);
13155 for (unsigned i = 0; i < TotalLists; ++i)
13156 ListSizes.push_back(Record.readInt());
13157 C->setComponentListSizes(ListSizes);
13158
13159 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13160 Components.reserve(TotalComponents);
13161 for (unsigned i = 0; i < TotalComponents; ++i) {
13162 Expr *AssociatedExpr = Record.readSubExpr();
13163 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13164 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13165 AssociatedExpr, AssociatedDecl));
13166 }
13167 C->setComponents(Components, ListSizes);
13168}