blob: 0d8209c01c8d89f278810e3011dd6c14786f70ae [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"
Guy Benyei11169dd2012-12-18 14:30:41 +0000104#include "llvm/Bitcode/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];
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1518 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001519 SrcMgr::FileInfo &FileInfo =
1520 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 FileInfo.NumCreatedFIDs = Record[5];
1522 if (Record[3])
1523 FileInfo.setHasLineDirectives();
1524
1525 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1526 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001527 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1529 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1530 NumFileDecls));
1531 }
Richard Smithaada85c2016-02-06 02:06:43 +00001532
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001534 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001536 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1537 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001538 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1539 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001540 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001541 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 }
1543
1544 break;
1545 }
1546
1547 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001548 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001550 SrcMgr::CharacteristicKind
1551 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001553 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 IncludeLoc = getImportLocation(F);
1555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001556
Richard Smithaada85c2016-02-06 02:06:43 +00001557 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1558 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001559 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001560 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001561 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 break;
1563 }
1564
1565 case SM_SLOC_EXPANSION_ENTRY: {
1566 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1567 SourceMgr.createExpansionLoc(SpellingLoc,
1568 ReadSourceLocation(*F, Record[2]),
1569 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001570 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 Record[4],
1572 ID,
1573 BaseOffset + Record[0]);
1574 break;
1575 }
1576 }
1577
1578 return false;
1579}
1580
1581std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1582 if (ID == 0)
1583 return std::make_pair(SourceLocation(), "");
1584
1585 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1586 Error("source location entry ID out-of-range for AST file");
1587 return std::make_pair(SourceLocation(), "");
1588 }
1589
1590 // Find which module file this entry lands in.
1591 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001592 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 return std::make_pair(SourceLocation(), "");
1594
1595 // FIXME: Can we map this down to a particular submodule? That would be
1596 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001597 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001598}
1599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001600/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001601SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1602 if (F->ImportLoc.isValid())
1603 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 // Otherwise we have a PCH. It's considered to be "imported" at the first
1606 // location of its includer.
1607 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001608 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001609 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001610 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001611 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 return F->ImportedBy[0]->FirstLoc;
1613}
1614
JF Bastien0e828952019-06-26 19:50:12 +00001615/// Enter a subblock of the specified BlockID with the specified cursor. Read
1616/// the abbreviations that are at the top of the block and then leave the cursor
1617/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001618bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001619 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1620 // FIXME this drops errors on the floor.
1621 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001622 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001624
1625 while (true) {
1626 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001627 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1628 if (!MaybeCode) {
1629 // FIXME this drops errors on the floor.
1630 consumeError(MaybeCode.takeError());
1631 return true;
1632 }
1633 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001634
1635 // We expect all abbrevs to be at the start of the block.
1636 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001637 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1638 // FIXME this drops errors on the floor.
1639 consumeError(std::move(Err));
1640 return true;
1641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001642 return false;
1643 }
JF Bastien0e828952019-06-26 19:50:12 +00001644 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1645 // FIXME this drops errors on the floor.
1646 consumeError(std::move(Err));
1647 return true;
1648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 }
1650}
1651
Richard Smithe40f2ba2013-08-07 21:41:30 +00001652Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001653 unsigned &Idx) {
1654 Token Tok;
1655 Tok.startToken();
1656 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1657 Tok.setLength(Record[Idx++]);
1658 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1659 Tok.setIdentifierInfo(II);
1660 Tok.setKind((tok::TokenKind)Record[Idx++]);
1661 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1662 return Tok;
1663}
1664
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001665MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001666 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667
1668 // Keep track of where we are in the stream, then jump back there
1669 // after reading this macro.
1670 SavedStreamPosition SavedPosition(Stream);
1671
JF Bastien0e828952019-06-26 19:50:12 +00001672 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1673 // FIXME this drops errors on the floor.
1674 consumeError(std::move(Err));
1675 return nullptr;
1676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001678 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001679 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001682 // Advance to the next record, but if we get to the end of the block, don't
1683 // pop it (removing all the abbreviations from the cursor) since we want to
1684 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001685 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001686 Expected<llvm::BitstreamEntry> MaybeEntry =
1687 Stream.advanceSkippingSubblocks(Flags);
1688 if (!MaybeEntry) {
1689 Error(MaybeEntry.takeError());
1690 return Macro;
1691 }
1692 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001693
Chris Lattnerefa77172013-01-20 00:00:22 +00001694 switch (Entry.Kind) {
1695 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1696 case llvm::BitstreamEntry::Error:
1697 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001698 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001699 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001700 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001701 case llvm::BitstreamEntry::Record:
1702 // The interesting case.
1703 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 }
1705
1706 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001708 PreprocessorRecordTypes RecType;
1709 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1710 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1711 else {
1712 Error(MaybeRecType.takeError());
1713 return Macro;
1714 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001716 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001717 case PP_MACRO_DIRECTIVE_HISTORY:
1718 return Macro;
1719
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 case PP_MACRO_OBJECT_LIKE:
1721 case PP_MACRO_FUNCTION_LIKE: {
1722 // If we already have a macro, that means that we've hit the end
1723 // of the definition of the macro we were looking for. We're
1724 // done.
1725 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001726 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001727
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001728 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001730 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001731 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001733 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001734
Guy Benyei11169dd2012-12-18 14:30:41 +00001735 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1736 // Decode function-like macro info.
1737 bool isC99VarArgs = Record[NextIndex++];
1738 bool isGNUVarArgs = Record[NextIndex++];
1739 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001740 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 unsigned NumArgs = Record[NextIndex++];
1742 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001743 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001744
1745 // Install function-like macro info.
1746 MI->setIsFunctionLike();
1747 if (isC99VarArgs) MI->setIsC99Varargs();
1748 if (isGNUVarArgs) MI->setIsGNUVarargs();
1749 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001750 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 }
1752
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 // Remember that we saw this macro last so that we add the tokens that
1754 // form its body to it.
1755 Macro = MI;
1756
1757 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1758 Record[NextIndex]) {
1759 // We have a macro definition. Register the association
1760 PreprocessedEntityID
1761 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1762 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001763 PreprocessingRecord::PPEntityID PPID =
1764 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001765 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001766 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001767 if (PPDef)
1768 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 }
1770
1771 ++NumMacrosRead;
1772 break;
1773 }
1774
1775 case PP_TOKEN: {
1776 // If we see a TOKEN before a PP_MACRO_*, then the file is
1777 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001778 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001779
John McCallf413f5e2013-05-03 00:10:13 +00001780 unsigned Idx = 0;
1781 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 Macro->AddTokenToBody(Tok);
1783 break;
1784 }
1785 }
1786 }
1787}
1788
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001789PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001790ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1791 unsigned LocalID) const {
1792 if (!M.ModuleOffsetMap.empty())
1793 ReadModuleOffsetMap(M);
1794
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001795 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001797 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001799
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 return LocalID + I->second;
1801}
1802
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001803unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1804 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001805}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001806
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001807HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001808HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001809 internal_key_type ikey = {FE->getSize(),
1810 M.HasTimestamps ? FE->getModificationTime() : 0,
1811 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001812 return ikey;
1813}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001814
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001815bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001816 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 return false;
1818
Mehdi Amini004b9c72016-10-10 22:52:47 +00001819 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001820 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001821
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001823 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001824 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1825 if (!Key.Imported)
1826 return FileMgr.getFile(Key.Filename);
1827
1828 std::string Resolved = Key.Filename;
1829 Reader.ResolveImportedPath(M, Resolved);
1830 return FileMgr.getFile(Resolved);
1831 };
1832
1833 const FileEntry *FEA = GetFile(a);
1834 const FileEntry *FEB = GetFile(b);
1835 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001836}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001837
Guy Benyei11169dd2012-12-18 14:30:41 +00001838std::pair<unsigned, unsigned>
1839HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001840 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001841
Vedant Kumar48b4f762018-04-14 01:40:48 +00001842 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1843 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001844 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001845}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001846
1847HeaderFileInfoTrait::internal_key_type
1848HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001849 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001850
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001851 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001852 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1853 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001854 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001855 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001856 return ikey;
1857}
1858
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001859HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001860HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001862 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001863
1864 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 HeaderFileInfo HFI;
1866 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001867 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001868 HFI.isImport |= (Flags >> 5) & 0x01;
1869 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1870 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001872 // FIXME: Find a better way to handle this. Maybe just store a
1873 // "has been included" flag?
1874 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1875 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001876 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1877 M, endian::readNext<uint32_t, little, unaligned>(d));
1878 if (unsigned FrameworkOffset =
1879 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001880 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 // since 0 is used as an indicator for "no framework name".
1882 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1883 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1884 }
Richard Smith386bb072015-08-18 23:42:23 +00001885
1886 assert((End - d) % 4 == 0 &&
1887 "Wrong data length in HeaderFileInfo deserialization");
1888 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001889 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001890 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1891 LocalSMID >>= 2;
1892
1893 // This header is part of a module. Associate it with the module to enable
1894 // implicit module import.
1895 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1896 Module *Mod = Reader.getSubmodule(GlobalSMID);
1897 FileManager &FileMgr = Reader.getFileManager();
1898 ModuleMap &ModMap =
1899 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1900
1901 std::string Filename = key.Filename;
1902 if (key.Imported)
1903 Reader.ResolveImportedPath(M, Filename);
1904 // FIXME: This is not always the right filename-as-written, but we're not
1905 // going to use this information to rebuild the module, so it doesn't make
1906 // a lot of difference.
1907 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001908 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1909 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001910 }
1911
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 // This HeaderFileInfo was externally loaded.
1913 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001914 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 return HFI;
1916}
1917
Richard Smithd7329392015-04-21 21:46:32 +00001918void ASTReader::addPendingMacro(IdentifierInfo *II,
1919 ModuleFile *M,
1920 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001921 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1922 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001923}
1924
1925void ASTReader::ReadDefinedMacros() {
1926 // Note that we are loading defined macros.
1927 Deserializing Macros(this);
1928
Vedant Kumar48b4f762018-04-14 01:40:48 +00001929 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001930 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001931
1932 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001933 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 continue;
1935
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001936 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001937 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1938 Error(std::move(Err));
1939 return;
1940 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001941
1942 RecordData Record;
1943 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001944 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1945 if (!MaybeE) {
1946 Error(MaybeE.takeError());
1947 return;
1948 }
1949 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001950
Chris Lattnere7b154b2013-01-19 21:39:22 +00001951 switch (E.Kind) {
1952 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1953 case llvm::BitstreamEntry::Error:
1954 Error("malformed block record in AST file");
1955 return;
1956 case llvm::BitstreamEntry::EndBlock:
1957 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001958
JF Bastien0e828952019-06-26 19:50:12 +00001959 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001960 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001961 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1962 if (!MaybeRecord) {
1963 Error(MaybeRecord.takeError());
1964 return;
1965 }
1966 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001967 default: // Default behavior: ignore.
1968 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001969
Chris Lattnere7b154b2013-01-19 21:39:22 +00001970 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001971 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001972 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001973 if (II->isOutOfDate())
1974 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001975 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001976 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001977
Chris Lattnere7b154b2013-01-19 21:39:22 +00001978 case PP_TOKEN:
1979 // Ignore tokens.
1980 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001982 break;
1983 }
JF Bastien0e828952019-06-26 19:50:12 +00001984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001985 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001986 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001987 }
1988}
1989
1990namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001992 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 class IdentifierLookupVisitor {
1994 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001995 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001997 unsigned &NumIdentifierLookups;
1998 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001999 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002000
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002002 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2003 unsigned &NumIdentifierLookups,
2004 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002005 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2006 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002007 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002008 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002009
2010 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002011 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002012 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002014
Vedant Kumar48b4f762018-04-14 01:40:48 +00002015 ASTIdentifierLookupTable *IdTable
2016 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 if (!IdTable)
2018 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002019
2020 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002021 Found);
2022 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002023 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002024 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002025 if (Pos == IdTable->end())
2026 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002027
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 // Dereferencing the iterator has the effect of building the
2029 // IdentifierInfo node and populating it with the various
2030 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002031 ++NumIdentifierLookupHits;
2032 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 return true;
2034 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002035
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002036 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 // files.
2038 IdentifierInfo *getIdentifierInfo() const { return Found; }
2039 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002040
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002041} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002042
2043void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2044 // Note that we are loading an identifier.
2045 Deserializing AnIdentifier(this);
2046
2047 unsigned PriorGeneration = 0;
2048 if (getContext().getLangOpts().Modules)
2049 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002050
2051 // If there is a global index, look there first to determine which modules
2052 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002053 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002054 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002055 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002056 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2057 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002058 }
2059 }
2060
Douglas Gregor7211ac12013-01-25 23:32:03 +00002061 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002062 NumIdentifierLookups,
2063 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002064 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002065 markIdentifierUpToDate(&II);
2066}
2067
2068void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2069 if (!II)
2070 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002071
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 II->setOutOfDate(false);
2073
2074 // Update the generation for this identifier.
2075 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002076 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002077}
2078
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002079void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2080 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002081 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002082
2083 BitstreamCursor &Cursor = M.MacroCursor;
2084 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002085 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2086 Error(std::move(Err));
2087 return;
2088 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002089
Richard Smith713369b2015-04-23 20:40:50 +00002090 struct ModuleMacroRecord {
2091 SubmoduleID SubModID;
2092 MacroInfo *MI;
2093 SmallVector<SubmoduleID, 8> Overrides;
2094 };
2095 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002096
Richard Smithd7329392015-04-21 21:46:32 +00002097 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2098 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2099 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002100 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002101 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002102 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002103 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002104 if (!MaybeEntry) {
2105 Error(MaybeEntry.takeError());
2106 return;
2107 }
2108 llvm::BitstreamEntry Entry = MaybeEntry.get();
2109
Richard Smithd7329392015-04-21 21:46:32 +00002110 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2111 Error("malformed block record in AST file");
2112 return;
2113 }
2114
2115 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002116 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2117 if (!MaybePP) {
2118 Error(MaybePP.takeError());
2119 return;
2120 }
2121 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002122 case PP_MACRO_DIRECTIVE_HISTORY:
2123 break;
2124
2125 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002126 ModuleMacros.push_back(ModuleMacroRecord());
2127 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002128 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2129 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002130 for (int I = 2, N = Record.size(); I != N; ++I)
2131 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002132 continue;
2133 }
2134
2135 default:
2136 Error("malformed block record in AST file");
2137 return;
2138 }
2139
2140 // We found the macro directive history; that's the last record
2141 // for this macro.
2142 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002143 }
2144
Richard Smithd7329392015-04-21 21:46:32 +00002145 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002146 {
2147 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002148 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002149 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002150 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002151 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002152 Module *Mod = getSubmodule(ModID);
2153 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002154 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002155 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002156 }
2157
2158 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002159 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002160 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002161 }
2162 }
2163
2164 // Don't read the directive history for a module; we don't have anywhere
2165 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002166 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002167 return;
2168
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002169 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002170 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002171 unsigned Idx = 0, N = Record.size();
2172 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002173 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002174 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002175 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002176 switch (K) {
2177 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002178 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002179 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002180 break;
2181 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002182 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002183 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002184 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002185 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002186 bool isPublic = Record[Idx++];
2187 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2188 break;
2189 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002190
2191 if (!Latest)
2192 Latest = MD;
2193 if (Earliest)
2194 Earliest->setPrevious(MD);
2195 Earliest = MD;
2196 }
2197
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002198 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002199 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002200}
2201
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002202ASTReader::InputFileInfo
2203ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002204 // Go find this input file.
2205 BitstreamCursor &Cursor = F.InputFilesCursor;
2206 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002207 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2208 // FIXME this drops errors on the floor.
2209 consumeError(std::move(Err));
2210 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002211
JF Bastien0e828952019-06-26 19:50:12 +00002212 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2213 if (!MaybeCode) {
2214 // FIXME this drops errors on the floor.
2215 consumeError(MaybeCode.takeError());
2216 }
2217 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002218 RecordData Record;
2219 StringRef Blob;
2220
JF Bastien0e828952019-06-26 19:50:12 +00002221 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2222 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2223 "invalid record type for input file");
2224 else {
2225 // FIXME this drops errors on the floor.
2226 consumeError(Maybe.takeError());
2227 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002228
2229 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002230 InputFileInfo R;
2231 R.StoredSize = static_cast<off_t>(Record[1]);
2232 R.StoredTime = static_cast<time_t>(Record[2]);
2233 R.Overridden = static_cast<bool>(Record[3]);
2234 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002235 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002236 R.Filename = Blob;
2237 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002238 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002239}
2240
Manman Renc8c94152016-10-21 23:35:03 +00002241static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002242InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 // If this ID is bogus, just return an empty input file.
2244 if (ID == 0 || ID > F.InputFilesLoaded.size())
2245 return InputFile();
2246
2247 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002248 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 return F.InputFilesLoaded[ID-1];
2250
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002251 if (F.InputFilesLoaded[ID-1].isNotFound())
2252 return InputFile();
2253
Guy Benyei11169dd2012-12-18 14:30:41 +00002254 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002255 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002257 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2258 // FIXME this drops errors on the floor.
2259 consumeError(std::move(Err));
2260 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002261
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002262 InputFileInfo FI = readInputFileInfo(F, ID);
2263 off_t StoredSize = FI.StoredSize;
2264 time_t StoredTime = FI.StoredTime;
2265 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002266 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002267 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002268
Richard Smitha8cfffa2015-11-26 02:04:16 +00002269 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002270 // If we didn't find the file, resolve it relative to the
2271 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002272 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2273 F.OriginalDir != F.BaseDirectory) {
2274 std::string Resolved = resolveFileRelativeToOriginalDir(
2275 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002276 if (!Resolved.empty())
2277 File = FileMgr.getFile(Resolved);
2278 }
2279
2280 // For an overridden file, create a virtual file with the stored
2281 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002282 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002283 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002284
Craig Toppera13603a2014-05-22 05:54:18 +00002285 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002286 if (Complain) {
2287 std::string ErrorStr = "could not find file '";
2288 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002289 ErrorStr += "' referenced by AST file '";
2290 ErrorStr += F.FileName;
2291 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002292 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002294 // Record that we didn't find the file.
2295 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2296 return InputFile();
2297 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002298
Ben Langmuir198c1682014-03-07 07:27:49 +00002299 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002300 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002301 // can lead to problems when lexing using the source locations from the
2302 // PCH.
2303 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002304 // FIXME: Reject if the overrides are different.
2305 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002306 if (Complain)
2307 Error(diag::err_fe_pch_file_overridden, Filename);
2308 // After emitting the diagnostic, recover by disabling the override so
2309 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002310 //
2311 // FIXME: This recovery is just as broken as the original state; there may
2312 // be another precompiled module that's using the overridden contents, or
2313 // we might be half way through parsing it. Instead, we should treat the
2314 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002315 SM.disableFileContentsOverride(File);
2316 // The FileEntry is a virtual file entry with the size of the contents
2317 // that would override the original contents. Set it to the original's
2318 // size/time.
2319 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2320 StoredSize, StoredTime);
2321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002322
Ben Langmuir198c1682014-03-07 07:27:49 +00002323 bool IsOutOfDate = false;
2324
2325 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002326 if (!Overridden && //
2327 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002328 (StoredTime && StoredTime != File->getModificationTime() &&
2329 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002330 )) {
2331 if (Complain) {
2332 // Build a list of the PCH imports that got us here (in reverse).
2333 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002334 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002335 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002336
Ben Langmuir198c1682014-03-07 07:27:49 +00002337 // The top-level PCH is stale.
2338 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002339 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2340 if (DiagnosticKind == 0)
2341 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2342 else if (DiagnosticKind == 1)
2343 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2344 else
2345 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002346
Ben Langmuir198c1682014-03-07 07:27:49 +00002347 // Print the import stack.
2348 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2349 Diag(diag::note_pch_required_by)
2350 << Filename << ImportStack[0]->FileName;
2351 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002352 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002353 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002354 }
2355
Ben Langmuir198c1682014-03-07 07:27:49 +00002356 if (!Diags.isDiagnosticInFlight())
2357 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 }
2359
Ben Langmuir198c1682014-03-07 07:27:49 +00002360 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002362 // FIXME: If the file is overridden and we've already opened it,
2363 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002364
Richard Smitha8cfffa2015-11-26 02:04:16 +00002365 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002366
2367 // Note that we've loaded this input file.
2368 F.InputFilesLoaded[ID-1] = IF;
2369 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002370}
2371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002372/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002373/// is not an absolute path, add the system or module root to the beginning of
2374/// the file name.
2375void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2376 // Resolve relative to the base directory, if we have one.
2377 if (!M.BaseDirectory.empty())
2378 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002379}
2380
Richard Smith7ed1bc92014-12-05 22:42:13 +00002381void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2383 return;
2384
Richard Smith7ed1bc92014-12-05 22:42:13 +00002385 SmallString<128> Buffer;
2386 llvm::sys::path::append(Buffer, Prefix, Filename);
2387 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002388}
2389
Richard Smith0f99d6a2015-08-09 08:48:41 +00002390static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2391 switch (ARR) {
2392 case ASTReader::Failure: return true;
2393 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2394 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2395 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2396 case ASTReader::ConfigurationMismatch:
2397 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2398 case ASTReader::HadErrors: return true;
2399 case ASTReader::Success: return false;
2400 }
2401
2402 llvm_unreachable("unknown ASTReadResult");
2403}
2404
Richard Smith0516b182015-09-08 19:40:14 +00002405ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2406 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2407 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002408 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002409 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2410 // FIXME this drops errors on the floor.
2411 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002412 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002413 }
Richard Smith0516b182015-09-08 19:40:14 +00002414
2415 // Read all of the records in the options block.
2416 RecordData Record;
2417 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002418 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002419 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2420 if (!MaybeEntry) {
2421 // FIXME this drops errors on the floor.
2422 consumeError(MaybeEntry.takeError());
2423 return Failure;
2424 }
2425 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002426
Richard Smith0516b182015-09-08 19:40:14 +00002427 switch (Entry.Kind) {
2428 case llvm::BitstreamEntry::Error:
2429 case llvm::BitstreamEntry::SubBlock:
2430 return Failure;
2431
2432 case llvm::BitstreamEntry::EndBlock:
2433 return Result;
2434
2435 case llvm::BitstreamEntry::Record:
2436 // The interesting case.
2437 break;
2438 }
2439
2440 // Read and process a record.
2441 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002442 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2443 if (!MaybeRecordType) {
2444 // FIXME this drops errors on the floor.
2445 consumeError(MaybeRecordType.takeError());
2446 return Failure;
2447 }
2448 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002449 case LANGUAGE_OPTIONS: {
2450 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2451 if (ParseLanguageOptions(Record, Complain, Listener,
2452 AllowCompatibleConfigurationMismatch))
2453 Result = ConfigurationMismatch;
2454 break;
2455 }
2456
2457 case TARGET_OPTIONS: {
2458 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2459 if (ParseTargetOptions(Record, Complain, Listener,
2460 AllowCompatibleConfigurationMismatch))
2461 Result = ConfigurationMismatch;
2462 break;
2463 }
2464
Richard Smith0516b182015-09-08 19:40:14 +00002465 case FILE_SYSTEM_OPTIONS: {
2466 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2467 if (!AllowCompatibleConfigurationMismatch &&
2468 ParseFileSystemOptions(Record, Complain, Listener))
2469 Result = ConfigurationMismatch;
2470 break;
2471 }
2472
2473 case HEADER_SEARCH_OPTIONS: {
2474 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2475 if (!AllowCompatibleConfigurationMismatch &&
2476 ParseHeaderSearchOptions(Record, Complain, Listener))
2477 Result = ConfigurationMismatch;
2478 break;
2479 }
2480
2481 case PREPROCESSOR_OPTIONS:
2482 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2483 if (!AllowCompatibleConfigurationMismatch &&
2484 ParsePreprocessorOptions(Record, Complain, Listener,
2485 SuggestedPredefines))
2486 Result = ConfigurationMismatch;
2487 break;
2488 }
2489 }
2490}
2491
Guy Benyei11169dd2012-12-18 14:30:41 +00002492ASTReader::ASTReadResult
2493ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002494 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002495 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002497 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002498 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499
JF Bastien0e828952019-06-26 19:50:12 +00002500 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2501 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 return Failure;
2503 }
2504
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002505 // Lambda to read the unhashed control block the first time it's called.
2506 //
2507 // For PCM files, the unhashed control block cannot be read until after the
2508 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2509 // need to look ahead before reading the IMPORTS record. For consistency,
2510 // this block is always read somehow (see BitstreamEntry::EndBlock).
2511 bool HasReadUnhashedControlBlock = false;
2512 auto readUnhashedControlBlockOnce = [&]() {
2513 if (!HasReadUnhashedControlBlock) {
2514 HasReadUnhashedControlBlock = true;
2515 if (ASTReadResult Result =
2516 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2517 return Result;
2518 }
2519 return Success;
2520 };
2521
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 // Read all of the records and blocks in the control block.
2523 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002524 unsigned NumInputs = 0;
2525 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002526 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002527 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002528 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2529 if (!MaybeEntry) {
2530 Error(MaybeEntry.takeError());
2531 return Failure;
2532 }
2533 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002534
Chris Lattnere7b154b2013-01-19 21:39:22 +00002535 switch (Entry.Kind) {
2536 case llvm::BitstreamEntry::Error:
2537 Error("malformed block record in AST file");
2538 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002539 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002540 // Validate the module before returning. This call catches an AST with
2541 // no module name and no imports.
2542 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2543 return Result;
2544
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002545 // Validate input files.
2546 const HeaderSearchOptions &HSOpts =
2547 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002548
Richard Smitha1825302014-10-23 22:18:29 +00002549 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002550 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2551 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002552 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2553 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002555
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002556 // If we are reading a module, we will create a verification timestamp,
2557 // so we verify all input files. Otherwise, verify only user input
2558 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002559
2560 unsigned N = NumUserInputs;
2561 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002562 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002563 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002564 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002565 N = NumInputs;
2566
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002567 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002568 InputFile IF = getInputFile(F, I+1, Complain);
2569 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002573
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002574 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002575 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002576
Ben Langmuircb69b572014-03-07 06:40:32 +00002577 if (Listener && Listener->needsInputFileVisitation()) {
2578 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2579 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002580 for (unsigned I = 0; I < N; ++I) {
2581 bool IsSystem = I >= NumUserInputs;
2582 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002583 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002584 F.Kind == MK_ExplicitModule ||
2585 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002586 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002587 }
2588
Richard Smith8a308ec2015-11-05 00:54:55 +00002589 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002590 }
2591
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592 case llvm::BitstreamEntry::SubBlock:
2593 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 case INPUT_FILES_BLOCK_ID:
2595 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002596 if (llvm::Error Err = Stream.SkipBlock()) {
2597 Error(std::move(Err));
2598 return Failure;
2599 }
2600 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 Error("malformed block record in AST file");
2602 return Failure;
2603 }
2604 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002605
2606 case OPTIONS_BLOCK_ID:
2607 // If we're reading the first module for this group, check its options
2608 // are compatible with ours. For modules it imports, no further checking
2609 // is required, because we checked them when we built it.
2610 if (Listener && !ImportedBy) {
2611 // Should we allow the configuration of the module file to differ from
2612 // the configuration of the current translation unit in a compatible
2613 // way?
2614 //
2615 // FIXME: Allow this for files explicitly specified with -include-pch.
2616 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002617 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002618
Richard Smith8a308ec2015-11-05 00:54:55 +00002619 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2620 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002621 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002622 if (Result == Failure) {
2623 Error("malformed block record in AST file");
2624 return Result;
2625 }
2626
Richard Smith8a308ec2015-11-05 00:54:55 +00002627 if (DisableValidation ||
2628 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2629 Result = Success;
2630
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002631 // If we can't load the module, exit early since we likely
2632 // will rebuild the module anyway. The stream may be in the
2633 // middle of a block.
2634 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002635 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002636 } else if (llvm::Error Err = Stream.SkipBlock()) {
2637 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002638 return Failure;
2639 }
2640 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002641
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 default:
JF Bastien0e828952019-06-26 19:50:12 +00002643 if (llvm::Error Err = Stream.SkipBlock()) {
2644 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002645 return Failure;
2646 }
2647 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002649
Chris Lattnere7b154b2013-01-19 21:39:22 +00002650 case llvm::BitstreamEntry::Record:
2651 // The interesting case.
2652 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654
2655 // Read and process a record.
2656 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002657 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002658 Expected<unsigned> MaybeRecordType =
2659 Stream.readRecord(Entry.ID, Record, &Blob);
2660 if (!MaybeRecordType) {
2661 Error(MaybeRecordType.takeError());
2662 return Failure;
2663 }
2664 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 case METADATA: {
2666 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2667 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002668 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2669 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 return VersionMismatch;
2671 }
2672
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002673 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2675 Diag(diag::err_pch_with_compiler_errors);
2676 return HadErrors;
2677 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002678 if (hasErrors) {
2679 Diags.ErrorOccurred = true;
2680 Diags.UncompilableErrorOccurred = true;
2681 Diags.UnrecoverableErrorOccurred = true;
2682 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002683
2684 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002685 // Relative paths in a relocatable PCH are relative to our sysroot.
2686 if (F.RelocatablePCH)
2687 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002688
Richard Smithe75ee0f2015-08-17 07:13:32 +00002689 F.HasTimestamps = Record[5];
2690
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002691 F.PCHHasObjectFile = Record[6];
2692
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002694 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2696 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002697 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 return VersionMismatch;
2699 }
2700 break;
2701 }
2702
2703 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002704 // Validate the AST before processing any imports (otherwise, untangling
2705 // them can be error-prone and expensive). A module will have a name and
2706 // will already have been validated, but this catches the PCH case.
2707 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2708 return Result;
2709
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002710 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 unsigned Idx = 0, N = Record.size();
2712 while (Idx < N) {
2713 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002714 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 // The import location will be the local one for now; we will adjust
2716 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002717 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002719 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002720 off_t StoredSize = (off_t)Record[Idx++];
2721 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002722 ASTFileSignature StoredSignature = {
2723 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2724 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2725 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002726
2727 std::string ImportedName = ReadString(Record, Idx);
2728 std::string ImportedFile;
2729
2730 // For prebuilt and explicit modules first consult the file map for
2731 // an override. Note that here we don't search prebuilt module
2732 // directories, only the explicit name to file mappings. Also, we will
2733 // still verify the size/signature making sure it is essentially the
2734 // same file but perhaps in a different location.
2735 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2736 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2737 ImportedName, /*FileMapOnly*/ true);
2738
2739 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002740 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2741 // ModuleCache as when writing.
2742 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002743 else
2744 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002745
Richard Smith0f99d6a2015-08-09 08:48:41 +00002746 // If our client can't cope with us being out of date, we can't cope with
2747 // our dependency being missing.
2748 unsigned Capabilities = ClientLoadCapabilities;
2749 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2750 Capabilities &= ~ARR_Missing;
2751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002753 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2754 Loaded, StoredSize, StoredModTime,
2755 StoredSignature, Capabilities);
2756
2757 // If we diagnosed a problem, produce a backtrace.
2758 if (isDiagnosedResult(Result, Capabilities))
2759 Diag(diag::note_module_file_imported_by)
2760 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2761
2762 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 case Failure: return Failure;
2764 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002765 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 case OutOfDate: return OutOfDate;
2767 case VersionMismatch: return VersionMismatch;
2768 case ConfigurationMismatch: return ConfigurationMismatch;
2769 case HadErrors: return HadErrors;
2770 case Success: break;
2771 }
2772 }
2773 break;
2774 }
2775
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 case ORIGINAL_FILE:
2777 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002778 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002780 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 break;
2782
2783 case ORIGINAL_FILE_ID:
2784 F.OriginalSourceFileID = FileID::get(Record[0]);
2785 break;
2786
2787 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002788 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 break;
2790
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002791 case MODULE_NAME:
2792 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002793 Diag(diag::remark_module_import)
2794 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2795 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002796 if (Listener)
2797 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002798
2799 // Validate the AST as soon as we have a name so we can exit early on
2800 // failure.
2801 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2802 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002803
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002804 break;
2805
Richard Smith223d3f22014-12-06 03:21:08 +00002806 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002807 // Save the BaseDirectory as written in the PCM for computing the module
2808 // filename for the ModuleCache.
2809 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002810 assert(!F.ModuleName.empty() &&
2811 "MODULE_DIRECTORY found before MODULE_NAME");
2812 // If we've already loaded a module map file covering this module, we may
2813 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002814 Module *M = PP.getHeaderSearchInfo().lookupModule(
2815 F.ModuleName, /*AllowSearch*/ true,
2816 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002817 if (M && M->Directory) {
2818 // If we're implicitly loading a module, the base directory can't
2819 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002820 // Don't emit module relocation error if we have -fno-validate-pch
2821 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2822 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002823 const DirectoryEntry *BuildDir =
2824 PP.getFileManager().getDirectory(Blob);
2825 if (!BuildDir || BuildDir != M->Directory) {
2826 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2827 Diag(diag::err_imported_module_relocated)
2828 << F.ModuleName << Blob << M->Directory->getName();
2829 return OutOfDate;
2830 }
2831 }
2832 F.BaseDirectory = M->Directory->getName();
2833 } else {
2834 F.BaseDirectory = Blob;
2835 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002836 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002837 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002838
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002839 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002840 if (ASTReadResult Result =
2841 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2842 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002843 break;
2844
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002845 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002846 NumInputs = Record[0];
2847 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002848 F.InputFileOffsets =
2849 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002850 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002851 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 break;
2853 }
2854 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002855}
2856
Ben Langmuir2c9af442014-04-10 17:57:43 +00002857ASTReader::ASTReadResult
2858ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002859 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002860
JF Bastien0e828952019-06-26 19:50:12 +00002861 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2862 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002863 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 }
2865
2866 // Read all of the records and blocks for the AST file.
2867 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002868 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002869 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2870 if (!MaybeEntry) {
2871 Error(MaybeEntry.takeError());
2872 return Failure;
2873 }
2874 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002875
Chris Lattnere7b154b2013-01-19 21:39:22 +00002876 switch (Entry.Kind) {
2877 case llvm::BitstreamEntry::Error:
2878 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002879 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002880 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002881 // Outside of C++, we do not store a lookup map for the translation unit.
2882 // Instead, mark it as needing a lookup map to be built if this module
2883 // contains any declarations lexically within it (which it always does!).
2884 // This usually has no cost, since we very rarely need the lookup map for
2885 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002886 if (ASTContext *Ctx = ContextObj) {
2887 DeclContext *DC = Ctx->getTranslationUnitDecl();
2888 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2889 DC->setMustBuildLookupTable();
2890 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002891
Ben Langmuir2c9af442014-04-10 17:57:43 +00002892 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002893 case llvm::BitstreamEntry::SubBlock:
2894 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 case DECLTYPES_BLOCK_ID:
2896 // We lazily load the decls block, but we want to set up the
2897 // DeclsCursor cursor to point into it. Clone our current bitcode
2898 // cursor to it, enter the block and read the abbrevs in that block.
2899 // With the main cursor, we just skip over it.
2900 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002901 if (llvm::Error Err = Stream.SkipBlock()) {
2902 Error(std::move(Err));
2903 return Failure;
2904 }
2905 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002907 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 }
2909 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002910
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 case PREPROCESSOR_BLOCK_ID:
2912 F.MacroCursor = Stream;
2913 if (!PP.getExternalSource())
2914 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002915
JF Bastien0e828952019-06-26 19:50:12 +00002916 if (llvm::Error Err = Stream.SkipBlock()) {
2917 Error(std::move(Err));
2918 return Failure;
2919 }
2920 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002922 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 }
2924 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2925 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002926
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 case PREPROCESSOR_DETAIL_BLOCK_ID:
2928 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002929
2930 if (llvm::Error Err = Stream.SkipBlock()) {
2931 Error(std::move(Err));
2932 return Failure;
2933 }
2934 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00002936 Error("malformed preprocessor detail record in AST file");
2937 return Failure;
2938 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002940 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 if (!PP.getPreprocessingRecord())
2943 PP.createPreprocessingRecord();
2944 if (!PP.getPreprocessingRecord()->getExternalSource())
2945 PP.getPreprocessingRecord()->SetExternalSource(*this);
2946 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002947
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 case SOURCE_MANAGER_BLOCK_ID:
2949 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002952
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002954 if (ASTReadResult Result =
2955 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002956 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002958
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002960 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002961
2962 if (llvm::Error Err = Stream.SkipBlock()) {
2963 Error(std::move(Err));
2964 return Failure;
2965 }
2966 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002968 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 }
2970 CommentsCursors.push_back(std::make_pair(C, &F));
2971 break;
2972 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002973
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 default:
JF Bastien0e828952019-06-26 19:50:12 +00002975 if (llvm::Error Err = Stream.SkipBlock()) {
2976 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002977 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002978 }
2979 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 }
2981 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002982
Chris Lattnere7b154b2013-01-19 21:39:22 +00002983 case llvm::BitstreamEntry::Record:
2984 // The interesting case.
2985 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 }
2987
2988 // Read and process a record.
2989 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002990 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002991 Expected<unsigned> MaybeRecordType =
2992 Stream.readRecord(Entry.ID, Record, &Blob);
2993 if (!MaybeRecordType) {
2994 Error(MaybeRecordType.takeError());
2995 return Failure;
2996 }
2997 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00002998
2999 // If we're not loading an AST context, we don't care about most records.
3000 if (!ContextObj) {
3001 switch (RecordType) {
3002 case IDENTIFIER_TABLE:
3003 case IDENTIFIER_OFFSET:
3004 case INTERESTING_IDENTIFIERS:
3005 case STATISTICS:
3006 case PP_CONDITIONAL_STACK:
3007 case PP_COUNTER_VALUE:
3008 case SOURCE_LOCATION_OFFSETS:
3009 case MODULE_OFFSET_MAP:
3010 case SOURCE_MANAGER_LINE_TABLE:
3011 case SOURCE_LOCATION_PRELOADS:
3012 case PPD_ENTITIES_OFFSETS:
3013 case HEADER_SEARCH_TABLE:
3014 case IMPORTED_MODULES:
3015 case MACRO_OFFSET:
3016 break;
3017 default:
3018 continue;
3019 }
3020 }
3021
3022 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 default: // Default behavior: ignore.
3024 break;
3025
3026 case TYPE_OFFSET: {
3027 if (F.LocalNumTypes != 0) {
3028 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003029 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003031 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 F.LocalNumTypes = Record[0];
3033 unsigned LocalBaseTypeIndex = Record[1];
3034 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003035
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 if (F.LocalNumTypes > 0) {
3037 // Introduce the global -> local mapping for types within this module.
3038 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003039
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 // Introduce the local -> global mapping for types within this module.
3041 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003042 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003044
3045 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 }
3047 break;
3048 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003049
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 case DECL_OFFSET: {
3051 if (F.LocalNumDecls != 0) {
3052 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003053 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003055 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 F.LocalNumDecls = Record[0];
3057 unsigned LocalBaseDeclID = Record[1];
3058 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003059
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003061 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 // module.
3063 GlobalDeclMap.insert(
3064 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003065
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 // Introduce the local -> global mapping for declarations within this
3067 // module.
3068 F.DeclRemap.insertOrReplace(
3069 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003070
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 // Introduce the global -> local mapping for declarations within this
3072 // module.
3073 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003074
Ben Langmuir52ca6782014-10-20 16:27:32 +00003075 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 break;
3078 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003079
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003081 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003082 LexicalContents Contents(
3083 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3084 Blob.data()),
3085 static_cast<unsigned int>(Blob.size() / 4));
3086 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 TU->setHasExternalLexicalStorage(true);
3088 break;
3089 }
3090
3091 case UPDATE_VISIBLE: {
3092 unsigned Idx = 0;
3093 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003094 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003095 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003096 // If we've already loaded the decl, perform the updates when we finish
3097 // loading this block.
3098 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003099 PendingUpdateRecords.push_back(
3100 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 break;
3102 }
3103
3104 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003105 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003107 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3108 (const unsigned char *)F.IdentifierTableData + Record[0],
3109 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3110 (const unsigned char *)F.IdentifierTableData,
3111 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003112
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3114 }
3115 break;
3116
3117 case IDENTIFIER_OFFSET: {
3118 if (F.LocalNumIdentifiers != 0) {
3119 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003120 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003122 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 F.LocalNumIdentifiers = Record[0];
3124 unsigned LocalBaseIdentifierID = Record[1];
3125 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 if (F.LocalNumIdentifiers > 0) {
3128 // Introduce the global -> local mapping for identifiers within this
3129 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003132
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 // Introduce the local -> global mapping for identifiers within this
3134 // module.
3135 F.IdentifierRemap.insertOrReplace(
3136 std::make_pair(LocalBaseIdentifierID,
3137 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003138
Ben Langmuir52ca6782014-10-20 16:27:32 +00003139 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3140 + F.LocalNumIdentifiers);
3141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 break;
3143 }
3144
Richard Smith33e0f7e2015-07-22 02:08:40 +00003145 case INTERESTING_IDENTIFIERS:
3146 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3147 break;
3148
Ben Langmuir332aafe2014-01-31 01:06:56 +00003149 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003150 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3151 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003153 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 break;
3155
David Blaikie9ffe5a32017-01-30 05:00:26 +00003156 case MODULAR_CODEGEN_DECLS:
3157 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3158 // them (ie: if we're not codegenerating this module).
3159 if (F.Kind == MK_MainFile)
3160 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3161 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3162 break;
3163
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003165 if (SpecialTypes.empty()) {
3166 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3167 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3168 break;
3169 }
3170
3171 if (SpecialTypes.size() != Record.size()) {
3172 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003173 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003174 }
3175
3176 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3177 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3178 if (!SpecialTypes[I])
3179 SpecialTypes[I] = ID;
3180 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3181 // merge step?
3182 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 break;
3184
3185 case STATISTICS:
3186 TotalNumStatements += Record[0];
3187 TotalNumMacros += Record[1];
3188 TotalLexicalDeclContexts += Record[2];
3189 TotalVisibleDeclContexts += Record[3];
3190 break;
3191
3192 case UNUSED_FILESCOPED_DECLS:
3193 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3194 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3195 break;
3196
3197 case DELEGATING_CTORS:
3198 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3199 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3200 break;
3201
3202 case WEAK_UNDECLARED_IDENTIFIERS:
3203 if (Record.size() % 4 != 0) {
3204 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003205 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003207
3208 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 // files. This isn't the way to do it :)
3210 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003211
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 // Translate the weak, undeclared identifiers into global IDs.
3213 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3214 WeakUndeclaredIdentifiers.push_back(
3215 getGlobalIdentifierID(F, Record[I++]));
3216 WeakUndeclaredIdentifiers.push_back(
3217 getGlobalIdentifierID(F, Record[I++]));
3218 WeakUndeclaredIdentifiers.push_back(
3219 ReadSourceLocation(F, Record, I).getRawEncoding());
3220 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3221 }
3222 break;
3223
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003225 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 F.LocalNumSelectors = Record[0];
3227 unsigned LocalBaseSelectorID = Record[1];
3228 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003229
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003231 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 // module.
3233 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003234
3235 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 // module.
3237 F.SelectorRemap.insertOrReplace(
3238 std::make_pair(LocalBaseSelectorID,
3239 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003240
3241 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 }
3243 break;
3244 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003245
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003247 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 if (Record[0])
3249 F.SelectorLookupTable
3250 = ASTSelectorLookupTable::Create(
3251 F.SelectorLookupTableData + Record[0],
3252 F.SelectorLookupTableData,
3253 ASTSelectorLookupTrait(*this, F));
3254 TotalNumMethodPoolEntries += Record[1];
3255 break;
3256
3257 case REFERENCED_SELECTOR_POOL:
3258 if (!Record.empty()) {
3259 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003260 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 Record[Idx++]));
3262 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3263 getRawEncoding());
3264 }
3265 }
3266 break;
3267
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003268 case PP_CONDITIONAL_STACK:
3269 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003270 unsigned Idx = 0, End = Record.size() - 1;
3271 bool ReachedEOFWhileSkipping = Record[Idx++];
3272 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3273 if (ReachedEOFWhileSkipping) {
3274 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3275 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3276 bool FoundNonSkipPortion = Record[Idx++];
3277 bool FoundElse = Record[Idx++];
3278 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3279 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3280 FoundElse, ElseLoc);
3281 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003282 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003283 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003284 auto Loc = ReadSourceLocation(F, Record, Idx);
3285 bool WasSkipping = Record[Idx++];
3286 bool FoundNonSkip = Record[Idx++];
3287 bool FoundElse = Record[Idx++];
3288 ConditionalStack.push_back(
3289 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3290 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003291 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003292 }
3293 break;
3294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 case PP_COUNTER_VALUE:
3296 if (!Record.empty() && Listener)
3297 Listener->ReadCounter(F, Record[0]);
3298 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003301 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 F.NumFileSortedDecls = Record[0];
3303 break;
3304
3305 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003306 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 F.LocalNumSLocEntries = Record[0];
3308 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003309 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003310 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003312 if (!F.SLocEntryBaseID) {
3313 Error("ran out of source locations");
3314 break;
3315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 // Make our entry in the range map. BaseID is negative and growing, so
3317 // we invert it. Because we invert it, though, we need the other end of
3318 // the range.
3319 unsigned RangeStart =
3320 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3321 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3322 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3323
3324 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3325 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3326 GlobalSLocOffsetMap.insert(
3327 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3328 - SLocSpaceSize,&F));
3329
3330 // Initialize the remapping table.
3331 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003332 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003334 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003336
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 TotalNumSLocEntries += F.LocalNumSLocEntries;
3338 break;
3339 }
3340
Richard Smith37a93df2017-02-18 00:32:02 +00003341 case MODULE_OFFSET_MAP:
3342 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003344
3345 case SOURCE_MANAGER_LINE_TABLE:
3346 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003347 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348 break;
3349
3350 case SOURCE_LOCATION_PRELOADS: {
3351 // Need to transform from the local view (1-based IDs) to the global view,
3352 // which is based off F.SLocEntryBaseID.
3353 if (!F.PreloadSLocEntries.empty()) {
3354 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003355 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003357
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 F.PreloadSLocEntries.swap(Record);
3359 break;
3360 }
3361
3362 case EXT_VECTOR_DECLS:
3363 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3364 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3365 break;
3366
3367 case VTABLE_USES:
3368 if (Record.size() % 3 != 0) {
3369 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003370 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003372
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 // Later tables overwrite earlier ones.
3374 // FIXME: Modules will have some trouble with this. This is clearly not
3375 // the right way to do this.
3376 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003377
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3379 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3380 VTableUses.push_back(
3381 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3382 VTableUses.push_back(Record[Idx++]);
3383 }
3384 break;
3385
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 case PENDING_IMPLICIT_INSTANTIATIONS:
3387 if (PendingInstantiations.size() % 2 != 0) {
3388 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003389 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 }
3391
3392 if (Record.size() % 2 != 0) {
3393 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003394 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 }
3396
3397 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3398 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3399 PendingInstantiations.push_back(
3400 ReadSourceLocation(F, Record, I).getRawEncoding());
3401 }
3402 break;
3403
3404 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003405 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003406 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003407 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003408 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3410 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3411 break;
3412
3413 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003414 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3415 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3416 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
3418 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003419
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 unsigned StartingID;
3421 if (!PP.getPreprocessingRecord())
3422 PP.createPreprocessingRecord();
3423 if (!PP.getPreprocessingRecord()->getExternalSource())
3424 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003425 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003427 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 F.BasePreprocessedEntityID = StartingID;
3429
3430 if (F.NumPreprocessedEntities > 0) {
3431 // Introduce the global -> local mapping for preprocessed entities in
3432 // this module.
3433 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 // Introduce the local -> global mapping for preprocessed entities in
3436 // this module.
3437 F.PreprocessedEntityRemap.insertOrReplace(
3438 std::make_pair(LocalBasePreprocessedEntityID,
3439 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3440 }
3441
3442 break;
3443 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003444
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003445 case PPD_SKIPPED_RANGES: {
3446 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3447 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3448 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3449
3450 if (!PP.getPreprocessingRecord())
3451 PP.createPreprocessingRecord();
3452 if (!PP.getPreprocessingRecord()->getExternalSource())
3453 PP.getPreprocessingRecord()->SetExternalSource(*this);
3454 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3455 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003456
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003457 if (F.NumPreprocessedSkippedRanges > 0)
3458 GlobalSkippedRangeMap.insert(
3459 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3460 break;
3461 }
3462
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003463 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 if (Record.size() % 2 != 0) {
3465 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003468 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3469 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3470 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3471
3472 // If we've already loaded the decl, perform the updates when we finish
3473 // loading this block.
3474 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003475 PendingUpdateRecords.push_back(
3476 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003477 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003479
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003480 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 if (F.LocalNumObjCCategoriesInMap != 0) {
3482 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003483 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003485
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003487 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003489
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 case OBJC_CATEGORIES:
3491 F.ObjCCategories.swap(Record);
3492 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 case CUDA_SPECIAL_DECL_REFS:
3495 // Later tables overwrite earlier ones.
3496 // FIXME: Modules will have trouble with this.
3497 CUDASpecialDeclRefs.clear();
3498 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3499 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3500 break;
3501
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003502 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003503 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 if (Record[0]) {
3506 F.HeaderFileInfoTable
3507 = HeaderFileInfoLookupTable::Create(
3508 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3509 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003510 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003512 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003513
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 PP.getHeaderSearchInfo().SetExternalSource(this);
3515 if (!PP.getHeaderSearchInfo().getExternalLookup())
3516 PP.getHeaderSearchInfo().SetExternalLookup(this);
3517 }
3518 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003519
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 case FP_PRAGMA_OPTIONS:
3521 // Later tables overwrite earlier ones.
3522 FPPragmaOptions.swap(Record);
3523 break;
3524
3525 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003526 for (unsigned I = 0, E = Record.size(); I != E; ) {
3527 auto Name = ReadString(Record, I);
3528 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003529 Opt.Supported = Record[I++] != 0;
3530 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003531 Opt.Avail = Record[I++];
3532 Opt.Core = Record[I++];
3533 }
3534 break;
3535
3536 case OPENCL_EXTENSION_TYPES:
3537 for (unsigned I = 0, E = Record.size(); I != E;) {
3538 auto TypeID = static_cast<::TypeID>(Record[I++]);
3539 auto *Type = GetType(TypeID).getTypePtr();
3540 auto NumExt = static_cast<unsigned>(Record[I++]);
3541 for (unsigned II = 0; II != NumExt; ++II) {
3542 auto Ext = ReadString(Record, I);
3543 OpenCLTypeExtMap[Type].insert(Ext);
3544 }
3545 }
3546 break;
3547
3548 case OPENCL_EXTENSION_DECLS:
3549 for (unsigned I = 0, E = Record.size(); I != E;) {
3550 auto DeclID = static_cast<::DeclID>(Record[I++]);
3551 auto *Decl = GetDecl(DeclID);
3552 auto NumExt = static_cast<unsigned>(Record[I++]);
3553 for (unsigned II = 0; II != NumExt; ++II) {
3554 auto Ext = ReadString(Record, I);
3555 OpenCLDeclExtMap[Decl].insert(Ext);
3556 }
3557 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 break;
3559
3560 case TENTATIVE_DEFINITIONS:
3561 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3562 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3563 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003564
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 case KNOWN_NAMESPACES:
3566 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3567 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3568 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003569
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003570 case UNDEFINED_BUT_USED:
3571 if (UndefinedButUsed.size() % 2 != 0) {
3572 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003573 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003574 }
3575
3576 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003577 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003578 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003579 }
3580 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003581 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3582 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003583 ReadSourceLocation(F, Record, I).getRawEncoding());
3584 }
3585 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003586
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003587 case DELETE_EXPRS_TO_ANALYZE:
3588 for (unsigned I = 0, N = Record.size(); I != N;) {
3589 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3590 const uint64_t Count = Record[I++];
3591 DelayedDeleteExprs.push_back(Count);
3592 for (uint64_t C = 0; C < Count; ++C) {
3593 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3594 bool IsArrayForm = Record[I++] == 1;
3595 DelayedDeleteExprs.push_back(IsArrayForm);
3596 }
3597 }
3598 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003599
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003600 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003601 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 // If we aren't loading a module (which has its own exports), make
3603 // all of the imported modules visible.
3604 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003605 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3606 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3607 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003608 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003609 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003610 if (DeserializationListener)
3611 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 }
3614 }
3615 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003616
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 case MACRO_OFFSET: {
3618 if (F.LocalNumMacros != 0) {
3619 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003620 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003622 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003623 F.LocalNumMacros = Record[0];
3624 unsigned LocalBaseMacroID = Record[1];
3625 F.BaseMacroID = getTotalNumMacros();
3626
3627 if (F.LocalNumMacros > 0) {
3628 // Introduce the global -> local mapping for macros within this module.
3629 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3630
3631 // Introduce the local -> global mapping for macros within this module.
3632 F.MacroRemap.insertOrReplace(
3633 std::make_pair(LocalBaseMacroID,
3634 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003635
3636 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 }
3638 break;
3639 }
3640
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003641 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003642 LateParsedTemplates.append(Record.begin(), Record.end());
3643 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003644
3645 case OPTIMIZE_PRAGMA_OPTIONS:
3646 if (Record.size() != 1) {
3647 Error("invalid pragma optimize record");
3648 return Failure;
3649 }
3650 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3651 break;
Nico Weber72889432014-09-06 01:25:55 +00003652
Nico Weber779355f2016-03-02 23:22:00 +00003653 case MSSTRUCT_PRAGMA_OPTIONS:
3654 if (Record.size() != 1) {
3655 Error("invalid pragma ms_struct record");
3656 return Failure;
3657 }
3658 PragmaMSStructState = Record[0];
3659 break;
3660
Nico Weber42932312016-03-03 00:17:35 +00003661 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3662 if (Record.size() != 2) {
3663 Error("invalid pragma ms_struct record");
3664 return Failure;
3665 }
3666 PragmaMSPointersToMembersState = Record[0];
3667 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3668 break;
3669
Nico Weber72889432014-09-06 01:25:55 +00003670 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3671 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3672 UnusedLocalTypedefNameCandidates.push_back(
3673 getGlobalDeclID(F, Record[I]));
3674 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003675
3676 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3677 if (Record.size() != 1) {
3678 Error("invalid cuda pragma options record");
3679 return Failure;
3680 }
3681 ForceCUDAHostDeviceDepth = Record[0];
3682 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003683
3684 case PACK_PRAGMA_OPTIONS: {
3685 if (Record.size() < 3) {
3686 Error("invalid pragma pack record");
3687 return Failure;
3688 }
3689 PragmaPackCurrentValue = Record[0];
3690 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3691 unsigned NumStackEntries = Record[2];
3692 unsigned Idx = 3;
3693 // Reset the stack when importing a new module.
3694 PragmaPackStack.clear();
3695 for (unsigned I = 0; I < NumStackEntries; ++I) {
3696 PragmaPackStackEntry Entry;
3697 Entry.Value = Record[Idx++];
3698 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003699 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003700 PragmaPackStrings.push_back(ReadString(Record, Idx));
3701 Entry.SlotLabel = PragmaPackStrings.back();
3702 PragmaPackStack.push_back(Entry);
3703 }
3704 break;
3705 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 }
3707 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003708}
3709
Richard Smith37a93df2017-02-18 00:32:02 +00003710void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3711 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3712
3713 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003714 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003715 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3716 F.ModuleOffsetMap = StringRef();
3717
3718 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3719 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3720 F.SLocRemap.insert(std::make_pair(0U, 0));
3721 F.SLocRemap.insert(std::make_pair(2U, 1));
3722 }
3723
3724 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003725 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003726 RemapBuilder SLocRemap(F.SLocRemap);
3727 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3728 RemapBuilder MacroRemap(F.MacroRemap);
3729 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3730 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3731 RemapBuilder SelectorRemap(F.SelectorRemap);
3732 RemapBuilder DeclRemap(F.DeclRemap);
3733 RemapBuilder TypeRemap(F.TypeRemap);
3734
3735 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003736 // FIXME: Looking up dependency modules by filename is horrible. Let's
3737 // start fixing this with prebuilt and explicit modules and see how it
3738 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003739 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003740 ModuleKind Kind = static_cast<ModuleKind>(
3741 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003742 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3743 StringRef Name = StringRef((const char*)Data, Len);
3744 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003745 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3746 ? ModuleMgr.lookupByModuleName(Name)
3747 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003748 if (!OM) {
3749 std::string Msg =
3750 "SourceLocation remap refers to unknown module, cannot find ";
3751 Msg.append(Name);
3752 Error(Msg);
3753 return;
3754 }
3755
3756 uint32_t SLocOffset =
3757 endian::readNext<uint32_t, little, unaligned>(Data);
3758 uint32_t IdentifierIDOffset =
3759 endian::readNext<uint32_t, little, unaligned>(Data);
3760 uint32_t MacroIDOffset =
3761 endian::readNext<uint32_t, little, unaligned>(Data);
3762 uint32_t PreprocessedEntityIDOffset =
3763 endian::readNext<uint32_t, little, unaligned>(Data);
3764 uint32_t SubmoduleIDOffset =
3765 endian::readNext<uint32_t, little, unaligned>(Data);
3766 uint32_t SelectorIDOffset =
3767 endian::readNext<uint32_t, little, unaligned>(Data);
3768 uint32_t DeclIDOffset =
3769 endian::readNext<uint32_t, little, unaligned>(Data);
3770 uint32_t TypeIndexOffset =
3771 endian::readNext<uint32_t, little, unaligned>(Data);
3772
3773 uint32_t None = std::numeric_limits<uint32_t>::max();
3774
3775 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3776 RemapBuilder &Remap) {
3777 if (Offset != None)
3778 Remap.insert(std::make_pair(Offset,
3779 static_cast<int>(BaseOffset - Offset)));
3780 };
3781 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3782 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3783 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3784 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3785 PreprocessedEntityRemap);
3786 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3787 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3788 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3789 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3790
3791 // Global -> local mappings.
3792 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3793 }
3794}
3795
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003796ASTReader::ASTReadResult
3797ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3798 const ModuleFile *ImportedBy,
3799 unsigned ClientLoadCapabilities) {
3800 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003801 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003802
3803 // Try to resolve ModuleName in the current header search context and
3804 // verify that it is found in the same module map file as we saved. If the
3805 // top-level AST file is a main file, skip this check because there is no
3806 // usable header search context.
3807 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003808 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003809 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003810 // An implicitly-loaded module file should have its module listed in some
3811 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003812 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003813 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3814 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003815 // Don't emit module relocation error if we have -fno-validate-pch
3816 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003817 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003818 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003819 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003820 // This module was defined by an imported (explicit) module.
3821 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3822 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003823 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003824 // This module was built with a different module map.
3825 Diag(diag::err_imported_module_not_found)
3826 << F.ModuleName << F.FileName << ImportedBy->FileName
3827 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003828 // In case it was imported by a PCH, there's a chance the user is
3829 // just missing to include the search path to the directory containing
3830 // the modulemap.
3831 if (ImportedBy->Kind == MK_PCH)
3832 Diag(diag::note_imported_by_pch_module_not_found)
3833 << llvm::sys::path::parent_path(F.ModuleMapPath);
3834 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003835 }
3836 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003837 }
3838
Richard Smithe842a472014-10-22 02:05:46 +00003839 assert(M->Name == F.ModuleName && "found module with different name");
3840
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003841 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003842 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003843 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3844 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003845 assert(ImportedBy && "top-level import should be verified");
3846 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3847 Diag(diag::err_imported_module_modmap_changed)
3848 << F.ModuleName << ImportedBy->FileName
3849 << ModMap->getName() << F.ModuleMapPath;
3850 return OutOfDate;
3851 }
3852
3853 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3854 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3855 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003856 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003857 const FileEntry *F =
3858 FileMgr.getFile(Filename, false, false);
3859 if (F == nullptr) {
3860 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3861 Error("could not find file '" + Filename +"' referenced by AST file");
3862 return OutOfDate;
3863 }
3864 AdditionalStoredMaps.insert(F);
3865 }
3866
3867 // Check any additional module map files (e.g. module.private.modulemap)
3868 // that are not in the pcm.
3869 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003870 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003871 // Remove files that match
3872 // Note: SmallPtrSet::erase is really remove
3873 if (!AdditionalStoredMaps.erase(ModMap)) {
3874 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3875 Diag(diag::err_module_different_modmap)
3876 << F.ModuleName << /*new*/0 << ModMap->getName();
3877 return OutOfDate;
3878 }
3879 }
3880 }
3881
3882 // Check any additional module map files that are in the pcm, but not
3883 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003884 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003885 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3886 Diag(diag::err_module_different_modmap)
3887 << F.ModuleName << /*not new*/1 << ModMap->getName();
3888 return OutOfDate;
3889 }
3890 }
3891
3892 if (Listener)
3893 Listener->ReadModuleMapFile(F.ModuleMapPath);
3894 return Success;
3895}
3896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003897/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003898static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3899 // Find the entry for this selector in the method pool.
3900 Sema::GlobalMethodPool::iterator Known
3901 = S.MethodPool.find(Method->getSelector());
3902 if (Known == S.MethodPool.end())
3903 return;
3904
3905 // Retrieve the appropriate method list.
3906 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3907 : Known->second.second;
3908 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003909 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003910 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003911 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003912 Found = true;
3913 } else {
3914 // Keep searching.
3915 continue;
3916 }
3917 }
3918
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003919 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003920 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003921 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003922 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003923 }
3924}
3925
Richard Smithde711422015-04-23 21:20:19 +00003926void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003927 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003928 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003929 bool wasHidden = D->isHidden();
3930 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003931
Vedant Kumar48b4f762018-04-14 01:40:48 +00003932 if (wasHidden && SemaObj) {
3933 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003934 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003935 }
3936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 }
3938}
3939
Richard Smith49f906a2014-03-01 00:08:04 +00003940void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003941 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003942 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003944 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003945 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003947 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003948
3949 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003950 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 // there is nothing more to do.
3952 continue;
3953 }
Richard Smith49f906a2014-03-01 00:08:04 +00003954
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 if (!Mod->isAvailable()) {
3956 // Modules that aren't available cannot be made visible.
3957 continue;
3958 }
3959
3960 // Update the module's name visibility.
3961 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003962
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 // If we've already deserialized any names from this module,
3964 // mark them as visible.
3965 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3966 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003967 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003969 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003970 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3971 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003973
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003975 SmallVector<Module *, 16> Exports;
3976 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003977 for (SmallVectorImpl<Module *>::iterator
3978 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3979 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003980 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003981 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003982 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 }
3984}
3985
Richard Smith6561f922016-09-12 21:06:40 +00003986/// We've merged the definition \p MergedDef into the existing definition
3987/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3988/// visible.
3989void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3990 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00003991 if (Def->isHidden()) {
3992 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003993 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003994 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00003995 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003996 getContext().mergeDefinitionIntoModule(
3997 Def, MergedDef->getImportedOwningModule(),
3998 /*NotifyListeners*/ false);
3999 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004000 }
Richard Smith6561f922016-09-12 21:06:40 +00004001 }
4002}
4003
Douglas Gregore060e572013-01-25 01:03:03 +00004004bool ASTReader::loadGlobalIndex() {
4005 if (GlobalIndex)
4006 return false;
4007
4008 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004009 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004010 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004011
Douglas Gregore060e572013-01-25 01:03:03 +00004012 // Try to load the global index.
4013 TriedLoadingGlobalIndex = true;
4014 StringRef ModuleCachePath
4015 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004016 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4017 GlobalModuleIndex::readIndex(ModuleCachePath);
4018 if (llvm::Error Err = std::move(Result.second)) {
4019 assert(!Result.first);
4020 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004021 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004022 }
Douglas Gregore060e572013-01-25 01:03:03 +00004023
4024 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004025 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004026 return false;
4027}
4028
4029bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004030 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004031 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4032}
4033
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004034static void updateModuleTimestamp(ModuleFile &MF) {
4035 // Overwrite the timestamp file contents so that file's mtime changes.
4036 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004037 std::error_code EC;
4038 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
4039 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004040 return;
4041 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004042 OS.close();
4043 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004044}
4045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004046/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004047/// cursor into the start of the given block ID, returning false on success and
4048/// true on failure.
4049static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004050 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004051 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4052 if (!MaybeEntry) {
4053 // FIXME this drops errors on the floor.
4054 consumeError(MaybeEntry.takeError());
4055 return true;
4056 }
4057 llvm::BitstreamEntry Entry = MaybeEntry.get();
4058
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004059 switch (Entry.Kind) {
4060 case llvm::BitstreamEntry::Error:
4061 case llvm::BitstreamEntry::EndBlock:
4062 return true;
4063
4064 case llvm::BitstreamEntry::Record:
4065 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004066 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4067 break;
4068 else {
4069 // FIXME this drops errors on the floor.
4070 consumeError(Skipped.takeError());
4071 return true;
4072 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004073
4074 case llvm::BitstreamEntry::SubBlock:
4075 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004076 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4077 // FIXME this drops the error on the floor.
4078 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004079 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004080 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004081 // Found it!
4082 return false;
4083 }
4084
JF Bastien0e828952019-06-26 19:50:12 +00004085 if (llvm::Error Err = Cursor.SkipBlock()) {
4086 // FIXME this drops the error on the floor.
4087 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004088 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004089 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004090 }
4091 }
4092}
4093
Benjamin Kramer0772c422016-02-13 13:42:54 +00004094ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 ModuleKind Type,
4096 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004097 unsigned ClientLoadCapabilities,
4098 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004099 llvm::SaveAndRestore<SourceLocation>
4100 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4101
Richard Smithd1c46742014-04-30 02:24:17 +00004102 // Defer any pending actions until we get to the end of reading the AST file.
4103 Deserializing AnASTFile(this);
4104
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004106 unsigned PreviousGeneration = 0;
4107 if (ContextObj)
4108 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004109
4110 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004111 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004112 switch (ASTReadResult ReadResult =
4113 ReadASTCore(FileName, Type, ImportLoc,
4114 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4115 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00004117 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 case OutOfDate:
4119 case VersionMismatch:
4120 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00004121 case HadErrors: {
4122 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004123 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00004124 LoadedSet.insert(IM.Mod);
4125
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004126 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004127 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004128 ? &PP.getHeaderSearchInfo().getModuleMap()
4129 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004130
4131 // If we find that any modules are unusable, the global index is going
4132 // to be out-of-date. Just remove it.
4133 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004134 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00004136 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 case Success:
4138 break;
4139 }
4140
4141 // Here comes stuff that we only do once the entire chain is loaded.
4142
4143 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004144 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4145 MEnd = Loaded.end();
4146 M != MEnd; ++M) {
4147 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004148
4149 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004150 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4151 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004153 // Read the extension blocks.
4154 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4155 if (ASTReadResult Result = ReadExtensionBlock(F))
4156 return Result;
4157 }
4158
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004159 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 // bits of all files we've seen.
4161 F.GlobalBitOffset = TotalModulesSizeInBits;
4162 TotalModulesSizeInBits += F.SizeInBits;
4163 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004164
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004166 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4167 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 // Load it through the SourceManager and don't call ReadSLocEntry()
4169 // directly because the entry may have already been loaded in which case
4170 // calling ReadSLocEntry() directly would trigger an assertion in
4171 // SourceManager.
4172 SourceMgr.getLoadedSLocEntryByID(Index);
4173 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004174
Richard Smithea741482017-05-01 22:10:47 +00004175 // Map the original source file ID into the ID space of the current
4176 // compilation.
4177 if (F.OriginalSourceFileID.isValid()) {
4178 F.OriginalSourceFileID = FileID::get(
4179 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4180 }
4181
Richard Smith33e0f7e2015-07-22 02:08:40 +00004182 // Preload all the pending interesting identifiers by marking them out of
4183 // date.
4184 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004185 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004186 F.IdentifierTableData + Offset);
4187
4188 ASTIdentifierLookupTrait Trait(*this, F);
4189 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4190 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004191 auto &II = PP.getIdentifierTable().getOwn(Key);
4192 II.setOutOfDate(true);
4193
4194 // Mark this identifier as being from an AST file so that we can track
4195 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004196 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004197
4198 // Associate the ID with the identifier so that the writer can reuse it.
4199 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4200 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004201 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
4203
Douglas Gregor603cd862013-03-22 18:50:14 +00004204 // Setup the import locations and notify the module manager that we've
4205 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004206 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4207 MEnd = Loaded.end();
4208 M != MEnd; ++M) {
4209 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004210
4211 ModuleMgr.moduleFileAccepted(&F);
4212
4213 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004214 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004215 // FIXME: We assume that locations from PCH / preamble do not need
4216 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004217 if (!M->ImportedBy)
4218 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00004220 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 }
4222
Richard Smithdbafb6c2017-06-29 23:23:46 +00004223 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004224 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4225 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004226 // Mark all of the identifiers in the identifier table as being out of date,
4227 // so that various accessors know to check the loaded modules when the
4228 // identifier is used.
4229 //
4230 // For C++ modules, we don't need information on many identifiers (just
4231 // those that provide macros or are poisoned), so we mark all of
4232 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004233 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4234 IdEnd = PP.getIdentifierTable().end();
4235 Id != IdEnd; ++Id)
4236 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004237 }
Manman Rena0f31a02016-04-29 19:04:05 +00004238 // Mark selectors as out of date.
4239 for (auto Sel : SelectorGeneration)
4240 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004241
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004243 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4244 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4246 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004247
4248 switch (Unresolved.Kind) {
4249 case UnresolvedModuleRef::Conflict:
4250 if (ResolvedMod) {
4251 Module::Conflict Conflict;
4252 Conflict.Other = ResolvedMod;
4253 Conflict.Message = Unresolved.String.str();
4254 Unresolved.Mod->Conflicts.push_back(Conflict);
4255 }
4256 continue;
4257
4258 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004260 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004262
Douglas Gregorfb912652013-03-20 21:10:35 +00004263 case UnresolvedModuleRef::Export:
4264 if (ResolvedMod || Unresolved.IsWildcard)
4265 Unresolved.Mod->Exports.push_back(
4266 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4267 continue;
4268 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004270 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004271
Graydon Hoaree7196af2016-12-09 21:45:49 +00004272 if (Imported)
4273 Imported->append(ImportedModules.begin(),
4274 ImportedModules.end());
4275
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004276 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4277 // Might be unnecessary as use declarations are only used to build the
4278 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004279
Richard Smithdbafb6c2017-06-29 23:23:46 +00004280 if (ContextObj)
4281 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
Richard Smith3d8e97e2013-10-18 06:54:39 +00004283 if (SemaObj)
4284 UpdateSema();
4285
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 if (DeserializationListener)
4287 DeserializationListener->ReaderInitialized(this);
4288
4289 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004290 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 // If this AST file is a precompiled preamble, then set the
4292 // preamble file ID of the source manager to the file source file
4293 // from which the preamble was built.
4294 if (Type == MK_Preamble) {
4295 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4296 } else if (Type == MK_MainFile) {
4297 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4298 }
4299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004300
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 // For any Objective-C class definitions we have already loaded, make sure
4302 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004303 if (ContextObj) {
4304 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4305 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4306 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004307 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004308 }
4309 }
Douglas Gregore060e572013-01-25 01:03:03 +00004310
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004311 if (PP.getHeaderSearchInfo()
4312 .getHeaderSearchOpts()
4313 .ModulesValidateOncePerBuildSession) {
4314 // Now we are certain that the module and all modules it depends on are
4315 // up to date. Create or update timestamp files for modules that are
4316 // located in the module cache (not for PCH files that could be anywhere
4317 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004318 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4319 ImportedModule &M = Loaded[I];
4320 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004321 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004322 }
4323 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004324 }
4325
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return Success;
4327}
4328
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004329static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004330
JF Bastien0e828952019-06-26 19:50:12 +00004331/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4332static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4333 // FIXME checking magic headers is done in other places such as
4334 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4335 // always done the same. Unify it all with a helper.
4336 if (!Stream.canSkipToPos(4))
4337 return llvm::createStringError(std::errc::illegal_byte_sequence,
4338 "file too small to contain AST file magic");
4339 for (unsigned C : {'C', 'P', 'C', 'H'})
4340 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4341 if (Res.get() != C)
4342 return llvm::createStringError(
4343 std::errc::illegal_byte_sequence,
4344 "file doesn't start with AST file magic");
4345 } else
4346 return Res.takeError();
4347 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004348}
4349
Richard Smith0f99d6a2015-08-09 08:48:41 +00004350static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4351 switch (Kind) {
4352 case MK_PCH:
4353 return 0; // PCH
4354 case MK_ImplicitModule:
4355 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004356 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004357 return 1; // module
4358 case MK_MainFile:
4359 case MK_Preamble:
4360 return 2; // main source file
4361 }
4362 llvm_unreachable("unknown module kind");
4363}
4364
Guy Benyei11169dd2012-12-18 14:30:41 +00004365ASTReader::ASTReadResult
4366ASTReader::ReadASTCore(StringRef FileName,
4367 ModuleKind Type,
4368 SourceLocation ImportLoc,
4369 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004370 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004371 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004372 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 unsigned ClientLoadCapabilities) {
4374 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004376 ModuleManager::AddModuleResult AddResult
4377 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004378 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004379 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004380 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004381
Douglas Gregor7029ce12013-03-19 00:28:20 +00004382 switch (AddResult) {
4383 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004384 Diag(diag::remark_module_import)
4385 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4386 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004387 return Success;
4388
4389 case ModuleManager::NewlyLoaded:
4390 // Load module file below.
4391 break;
4392
4393 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004394 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004395 // it.
4396 if (ClientLoadCapabilities & ARR_Missing)
4397 return Missing;
4398
4399 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004400 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004401 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004402 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004403 return Failure;
4404
4405 case ModuleManager::OutOfDate:
4406 // We couldn't load the module file because it is out-of-date. If the
4407 // client can handle out-of-date, return it.
4408 if (ClientLoadCapabilities & ARR_OutOfDate)
4409 return OutOfDate;
4410
4411 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004412 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004413 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004414 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 return Failure;
4416 }
4417
Douglas Gregor7029ce12013-03-19 00:28:20 +00004418 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004420 bool ShouldFinalizePCM = false;
4421 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4422 auto &MC = getModuleManager().getModuleCache();
4423 if (ShouldFinalizePCM)
4424 MC.finalizePCM(FileName);
4425 else
4426 MC.tryToDropPCM(FileName);
4427 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004429 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004430 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004431 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004432
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004434 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4435 Diag(diag::err_module_file_invalid)
4436 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 return Failure;
4438 }
4439
4440 // This is used for compatibility with older PCH formats.
4441 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004442 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004443 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4444 if (!MaybeEntry) {
4445 Error(MaybeEntry.takeError());
4446 return Failure;
4447 }
4448 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004449
Chris Lattnerefa77172013-01-20 00:00:22 +00004450 switch (Entry.Kind) {
4451 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004452 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004453 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 Error("invalid record at top-level of AST file");
4455 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004456
Chris Lattnerefa77172013-01-20 00:00:22 +00004457 case llvm::BitstreamEntry::SubBlock:
4458 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 }
4460
Chris Lattnerefa77172013-01-20 00:00:22 +00004461 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 case CONTROL_BLOCK_ID:
4463 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004464 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004466 // Check that we didn't try to load a non-module AST file as a module.
4467 //
4468 // FIXME: Should we also perform the converse check? Loading a module as
4469 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004470 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4471 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004472 F.ModuleName.empty()) {
4473 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4474 if (Result != OutOfDate ||
4475 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4476 Diag(diag::err_module_file_not_module) << FileName;
4477 return Result;
4478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 break;
4480
4481 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004482 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 case OutOfDate: return OutOfDate;
4484 case VersionMismatch: return VersionMismatch;
4485 case ConfigurationMismatch: return ConfigurationMismatch;
4486 case HadErrors: return HadErrors;
4487 }
4488 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004489
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 case AST_BLOCK_ID:
4491 if (!HaveReadControlBlock) {
4492 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004493 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 return VersionMismatch;
4495 }
4496
4497 // Record that we've loaded this module.
4498 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004499 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 return Success;
4501
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004502 case UNHASHED_CONTROL_BLOCK_ID:
4503 // This block is handled using look-ahead during ReadControlBlock. We
4504 // shouldn't get here!
4505 Error("malformed block record in AST file");
4506 return Failure;
4507
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 default:
JF Bastien0e828952019-06-26 19:50:12 +00004509 if (llvm::Error Err = Stream.SkipBlock()) {
4510 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 return Failure;
4512 }
4513 break;
4514 }
4515 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004516
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004517 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004518}
4519
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004520ASTReader::ASTReadResult
4521ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4522 unsigned ClientLoadCapabilities) {
4523 const HeaderSearchOptions &HSOpts =
4524 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4525 bool AllowCompatibleConfigurationMismatch =
4526 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4527
4528 ASTReadResult Result = readUnhashedControlBlockImpl(
4529 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4530 Listener.get(),
4531 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4532
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004533 // If F was directly imported by another module, it's implicitly validated by
4534 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004535 if (DisableValidation || WasImportedBy ||
4536 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4537 return Success;
4538
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004539 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004540 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004541 return Failure;
4542 }
4543
4544 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004545 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004546 // with it; we can only load a single version of each module.
4547 //
4548 // This can happen when a module is imported in two contexts: in one, as a
4549 // user module; in another, as a system module (due to an import from
4550 // another module marked with the [system] flag). It usually indicates a
4551 // bug in the module map: this module should also be marked with [system].
4552 //
4553 // If -Wno-system-headers (the default), and the first import is as a
4554 // system module, then validation will fail during the as-user import,
4555 // since -Werror flags won't have been validated. However, it's reasonable
4556 // to treat this consistently as a system module.
4557 //
4558 // If -Wsystem-headers, the PCM on disk was built with
4559 // -Wno-system-headers, and the first import is as a user module, then
4560 // validation will fail during the as-system import since the PCM on disk
4561 // doesn't guarantee that -Werror was respected. However, the -Werror
4562 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004563 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004564 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4565 return Success;
4566 }
4567 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004568
4569 return Result;
4570}
4571
4572ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4573 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4574 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4575 bool ValidateDiagnosticOptions) {
4576 // Initialize a stream.
4577 BitstreamCursor Stream(StreamData);
4578
4579 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004580 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4581 // FIXME this drops the error on the floor.
4582 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004583 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004584 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004585
4586 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4587 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4588 return Failure;
4589
4590 // Read all of the records in the options block.
4591 RecordData Record;
4592 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004593 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004594 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4595 if (!MaybeEntry) {
4596 // FIXME this drops the error on the floor.
4597 consumeError(MaybeEntry.takeError());
4598 return Failure;
4599 }
4600 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004601
4602 switch (Entry.Kind) {
4603 case llvm::BitstreamEntry::Error:
4604 case llvm::BitstreamEntry::SubBlock:
4605 return Failure;
4606
4607 case llvm::BitstreamEntry::EndBlock:
4608 return Result;
4609
4610 case llvm::BitstreamEntry::Record:
4611 // The interesting case.
4612 break;
4613 }
4614
4615 // Read and process a record.
4616 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004617 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4618 if (!MaybeRecordType) {
4619 // FIXME this drops the error.
4620 return Failure;
4621 }
4622 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004623 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004624 if (F)
4625 std::copy(Record.begin(), Record.end(), F->Signature.data());
4626 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004627 case DIAGNOSTIC_OPTIONS: {
4628 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4629 if (Listener && ValidateDiagnosticOptions &&
4630 !AllowCompatibleConfigurationMismatch &&
4631 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004632 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004633 break;
4634 }
4635 case DIAG_PRAGMA_MAPPINGS:
4636 if (!F)
4637 break;
4638 if (F->PragmaDiagMappings.empty())
4639 F->PragmaDiagMappings.swap(Record);
4640 else
4641 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4642 Record.begin(), Record.end());
4643 break;
4644 }
4645 }
4646}
4647
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004648/// Parse a record and blob containing module file extension metadata.
4649static bool parseModuleFileExtensionMetadata(
4650 const SmallVectorImpl<uint64_t> &Record,
4651 StringRef Blob,
4652 ModuleFileExtensionMetadata &Metadata) {
4653 if (Record.size() < 4) return true;
4654
4655 Metadata.MajorVersion = Record[0];
4656 Metadata.MinorVersion = Record[1];
4657
4658 unsigned BlockNameLen = Record[2];
4659 unsigned UserInfoLen = Record[3];
4660
4661 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4662
4663 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4664 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4665 Blob.data() + BlockNameLen + UserInfoLen);
4666 return false;
4667}
4668
4669ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4670 BitstreamCursor &Stream = F.Stream;
4671
4672 RecordData Record;
4673 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004674 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4675 if (!MaybeEntry) {
4676 Error(MaybeEntry.takeError());
4677 return Failure;
4678 }
4679 llvm::BitstreamEntry Entry = MaybeEntry.get();
4680
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004681 switch (Entry.Kind) {
4682 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004683 if (llvm::Error Err = Stream.SkipBlock()) {
4684 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004685 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004686 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004687 continue;
4688
4689 case llvm::BitstreamEntry::EndBlock:
4690 return Success;
4691
4692 case llvm::BitstreamEntry::Error:
4693 return HadErrors;
4694
4695 case llvm::BitstreamEntry::Record:
4696 break;
4697 }
4698
4699 Record.clear();
4700 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004701 Expected<unsigned> MaybeRecCode =
4702 Stream.readRecord(Entry.ID, Record, &Blob);
4703 if (!MaybeRecCode) {
4704 Error(MaybeRecCode.takeError());
4705 return Failure;
4706 }
4707 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004708 case EXTENSION_METADATA: {
4709 ModuleFileExtensionMetadata Metadata;
4710 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4711 return Failure;
4712
4713 // Find a module file extension with this block name.
4714 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4715 if (Known == ModuleFileExtensions.end()) break;
4716
4717 // Form a reader.
4718 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4719 F, Stream)) {
4720 F.ExtensionReaders.push_back(std::move(Reader));
4721 }
4722
4723 break;
4724 }
4725 }
4726 }
4727
4728 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004729}
4730
Richard Smitha7e2cc62015-05-01 01:53:09 +00004731void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004732 assert(ContextObj && "no context to initialize");
4733 ASTContext &Context = *ContextObj;
4734
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 // If there's a listener, notify them that we "read" the translation unit.
4736 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004737 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 Context.getTranslationUnitDecl());
4739
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 // FIXME: Find a better way to deal with collisions between these
4741 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004742
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 // Load the special types.
4744 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4745 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4746 if (!Context.CFConstantStringTypeDecl)
4747 Context.setCFConstantStringType(GetType(String));
4748 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004749
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4751 QualType FileType = GetType(File);
4752 if (FileType.isNull()) {
4753 Error("FILE type is NULL");
4754 return;
4755 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004756
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004758 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 Context.setFILEDecl(Typedef->getDecl());
4760 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004761 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 if (!Tag) {
4763 Error("Invalid FILE type in AST file");
4764 return;
4765 }
4766 Context.setFILEDecl(Tag->getDecl());
4767 }
4768 }
4769 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004770
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4772 QualType Jmp_bufType = GetType(Jmp_buf);
4773 if (Jmp_bufType.isNull()) {
4774 Error("jmp_buf type is NULL");
4775 return;
4776 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004777
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004779 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 Context.setjmp_bufDecl(Typedef->getDecl());
4781 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004782 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 if (!Tag) {
4784 Error("Invalid jmp_buf type in AST file");
4785 return;
4786 }
4787 Context.setjmp_bufDecl(Tag->getDecl());
4788 }
4789 }
4790 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004791
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4793 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4794 if (Sigjmp_bufType.isNull()) {
4795 Error("sigjmp_buf type is NULL");
4796 return;
4797 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004798
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004800 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 Context.setsigjmp_bufDecl(Typedef->getDecl());
4802 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004803 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 assert(Tag && "Invalid sigjmp_buf type in AST file");
4805 Context.setsigjmp_bufDecl(Tag->getDecl());
4806 }
4807 }
4808 }
4809
4810 if (unsigned ObjCIdRedef
4811 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4812 if (Context.ObjCIdRedefinitionType.isNull())
4813 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4814 }
4815
4816 if (unsigned ObjCClassRedef
4817 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4818 if (Context.ObjCClassRedefinitionType.isNull())
4819 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4820 }
4821
4822 if (unsigned ObjCSelRedef
4823 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4824 if (Context.ObjCSelRedefinitionType.isNull())
4825 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4826 }
4827
4828 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4829 QualType Ucontext_tType = GetType(Ucontext_t);
4830 if (Ucontext_tType.isNull()) {
4831 Error("ucontext_t type is NULL");
4832 return;
4833 }
4834
4835 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004836 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 Context.setucontext_tDecl(Typedef->getDecl());
4838 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004839 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004840 assert(Tag && "Invalid ucontext_t type in AST file");
4841 Context.setucontext_tDecl(Tag->getDecl());
4842 }
4843 }
4844 }
4845 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004846
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4848
4849 // If there were any CUDA special declarations, deserialize them.
4850 if (!CUDASpecialDeclRefs.empty()) {
4851 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4852 Context.setcudaConfigureCallDecl(
4853 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4854 }
Richard Smith56be7542014-03-21 00:33:59 +00004855
Guy Benyei11169dd2012-12-18 14:30:41 +00004856 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004857 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004858 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004859 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004860 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004861 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004862 if (Import.ImportLoc.isValid())
4863 PP.makeModuleVisible(Imported, Import.ImportLoc);
4864 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004865 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 }
4867 ImportedModules.clear();
4868}
4869
4870void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004871 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004872}
4873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004874/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004875/// else returns 0.
4876static ASTFileSignature readASTFileSignature(StringRef PCH) {
4877 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004878 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4879 // FIXME this drops the error on the floor.
4880 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004881 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004882 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004883
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004884 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4885 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004886 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004887
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004888 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004889 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004890 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004891 Expected<llvm::BitstreamEntry> MaybeEntry =
4892 Stream.advanceSkippingSubblocks();
4893 if (!MaybeEntry) {
4894 // FIXME this drops the error on the floor.
4895 consumeError(MaybeEntry.takeError());
4896 return ASTFileSignature();
4897 }
4898 llvm::BitstreamEntry Entry = MaybeEntry.get();
4899
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004900 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004901 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004902
4903 Record.clear();
4904 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004905 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4906 if (!MaybeRecord) {
4907 // FIXME this drops the error on the floor.
4908 consumeError(MaybeRecord.takeError());
4909 return ASTFileSignature();
4910 }
4911 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004912 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4913 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004914 }
4915}
4916
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004917/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004918/// directly from the AST file, without actually loading the AST
4919/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004920std::string ASTReader::getOriginalSourceFile(
4921 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004922 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004924 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004926 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4927 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004928 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 }
4930
4931 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004932 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004933
4934 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004935 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4936 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004937 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004939
Chris Lattnere7b154b2013-01-19 21:39:22 +00004940 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004941 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004942 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004943 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004944 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004945
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004946 // Scan for ORIGINAL_FILE inside the control block.
4947 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004948 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004949 Expected<llvm::BitstreamEntry> MaybeEntry =
4950 Stream.advanceSkippingSubblocks();
4951 if (!MaybeEntry) {
4952 // FIXME this drops errors on the floor.
4953 consumeError(MaybeEntry.takeError());
4954 return std::string();
4955 }
4956 llvm::BitstreamEntry Entry = MaybeEntry.get();
4957
Chris Lattnere7b154b2013-01-19 21:39:22 +00004958 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004959 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004960
Chris Lattnere7b154b2013-01-19 21:39:22 +00004961 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4962 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004963 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004965
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004967 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004968 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4969 if (!MaybeRecord) {
4970 // FIXME this drops the errors on the floor.
4971 consumeError(MaybeRecord.takeError());
4972 return std::string();
4973 }
4974 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00004975 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004977}
4978
4979namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004980
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 class SimplePCHValidator : public ASTReaderListener {
4982 const LangOptions &ExistingLangOpts;
4983 const TargetOptions &ExistingTargetOpts;
4984 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004985 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004987
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 public:
4989 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4990 const TargetOptions &ExistingTargetOpts,
4991 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004992 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 FileManager &FileMgr)
4994 : ExistingLangOpts(ExistingLangOpts),
4995 ExistingTargetOpts(ExistingTargetOpts),
4996 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004997 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004998 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004999
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005000 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5001 bool AllowCompatibleDifferences) override {
5002 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5003 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005005
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005006 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5007 bool AllowCompatibleDifferences) override {
5008 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5009 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005011
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005012 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5013 StringRef SpecificModuleCachePath,
5014 bool Complain) override {
5015 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5016 ExistingModuleCachePath,
5017 nullptr, ExistingLangOpts);
5018 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005019
Craig Topper3e89dfe2014-03-13 02:13:41 +00005020 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5021 bool Complain,
5022 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005023 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005024 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 }
5026 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005027
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005028} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005029
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005030bool ASTReader::readASTFileControlBlock(
5031 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005032 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005033 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005034 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005036 // FIXME: This allows use of the VFS; we do not allow use of the
5037 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005038 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 if (!Buffer) {
5040 return true;
5041 }
5042
5043 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005044 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5045 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005046
5047 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005048 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5049 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005051 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005052
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005053 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005054 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005055 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005056
5057 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005058 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005059 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005060 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005061
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005063 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005064 bool DoneWithControlBlock = false;
5065 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005066 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5067 if (!MaybeEntry) {
5068 // FIXME this drops the error on the floor.
5069 consumeError(MaybeEntry.takeError());
5070 return true;
5071 }
5072 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005073
5074 switch (Entry.Kind) {
5075 case llvm::BitstreamEntry::SubBlock: {
5076 switch (Entry.ID) {
5077 case OPTIONS_BLOCK_ID: {
5078 std::string IgnoredSuggestedPredefines;
5079 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5080 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005081 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005082 return true;
5083 break;
5084 }
5085
5086 case INPUT_FILES_BLOCK_ID:
5087 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005088 if (llvm::Error Err = Stream.SkipBlock()) {
5089 // FIXME this drops the error on the floor.
5090 consumeError(std::move(Err));
5091 return true;
5092 }
5093 if (NeedsInputFiles &&
5094 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005095 return true;
5096 break;
5097
5098 default:
JF Bastien0e828952019-06-26 19:50:12 +00005099 if (llvm::Error Err = Stream.SkipBlock()) {
5100 // FIXME this drops the error on the floor.
5101 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005102 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005103 }
Richard Smith0516b182015-09-08 19:40:14 +00005104 break;
5105 }
5106
5107 continue;
5108 }
5109
5110 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005111 DoneWithControlBlock = true;
5112 break;
Richard Smith0516b182015-09-08 19:40:14 +00005113
5114 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005115 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005116
5117 case llvm::BitstreamEntry::Record:
5118 break;
5119 }
5120
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005121 if (DoneWithControlBlock) break;
5122
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005124 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005125 Expected<unsigned> MaybeRecCode =
5126 Stream.readRecord(Entry.ID, Record, &Blob);
5127 if (!MaybeRecCode) {
5128 // FIXME this drops the error.
5129 return Failure;
5130 }
5131 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005132 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005133 if (Record[0] != VERSION_MAJOR)
5134 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005135 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005136 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005137 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005138 case MODULE_NAME:
5139 Listener.ReadModuleName(Blob);
5140 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005141 case MODULE_DIRECTORY:
5142 ModuleDir = Blob;
5143 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005144 case MODULE_MAP_FILE: {
5145 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005146 auto Path = ReadString(Record, Idx);
5147 ResolveImportedPath(Path, ModuleDir);
5148 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005149 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005150 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005151 case INPUT_FILE_OFFSETS: {
5152 if (!NeedsInputFiles)
5153 break;
5154
5155 unsigned NumInputFiles = Record[0];
5156 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005157 const llvm::support::unaligned_uint64_t *InputFileOffs =
5158 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005159 for (unsigned I = 0; I != NumInputFiles; ++I) {
5160 // Go find this input file.
5161 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005162
5163 if (isSystemFile && !NeedsSystemInputFiles)
5164 break; // the rest are system input files
5165
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005166 BitstreamCursor &Cursor = InputFilesCursor;
5167 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005168 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5169 // FIXME this drops errors on the floor.
5170 consumeError(std::move(Err));
5171 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005172
JF Bastien0e828952019-06-26 19:50:12 +00005173 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5174 if (!MaybeCode) {
5175 // FIXME this drops errors on the floor.
5176 consumeError(MaybeCode.takeError());
5177 }
5178 unsigned Code = MaybeCode.get();
5179
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005180 RecordData Record;
5181 StringRef Blob;
5182 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005183 Expected<unsigned> MaybeRecordType =
5184 Cursor.readRecord(Code, Record, &Blob);
5185 if (!MaybeRecordType) {
5186 // FIXME this drops errors on the floor.
5187 consumeError(MaybeRecordType.takeError());
5188 }
5189 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005190 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005191 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005192 std::string Filename = Blob;
5193 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005194 shouldContinue = Listener.visitInputFile(
5195 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005196 break;
5197 }
5198 if (!shouldContinue)
5199 break;
5200 }
5201 break;
5202 }
5203
Richard Smithd4b230b2014-10-27 23:01:16 +00005204 case IMPORTS: {
5205 if (!NeedsImports)
5206 break;
5207
5208 unsigned Idx = 0, N = Record.size();
5209 while (Idx < N) {
5210 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005211 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5212 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005213 std::string Filename = ReadString(Record, Idx);
5214 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005215 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005216 }
5217 break;
5218 }
5219
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005220 default:
5221 // No other validation to perform.
5222 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 }
5224 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005225
5226 // Look for module file extension blocks, if requested.
5227 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005228 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005229 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5230 bool DoneWithExtensionBlock = false;
5231 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005232 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5233 if (!MaybeEntry) {
5234 // FIXME this drops the error.
5235 return true;
5236 }
5237 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005238
JF Bastien0e828952019-06-26 19:50:12 +00005239 switch (Entry.Kind) {
5240 case llvm::BitstreamEntry::SubBlock:
5241 if (llvm::Error Err = Stream.SkipBlock()) {
5242 // FIXME this drops the error on the floor.
5243 consumeError(std::move(Err));
5244 return true;
5245 }
5246 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005247
JF Bastien0e828952019-06-26 19:50:12 +00005248 case llvm::BitstreamEntry::EndBlock:
5249 DoneWithExtensionBlock = true;
5250 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005251
JF Bastien0e828952019-06-26 19:50:12 +00005252 case llvm::BitstreamEntry::Error:
5253 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005254
JF Bastien0e828952019-06-26 19:50:12 +00005255 case llvm::BitstreamEntry::Record:
5256 break;
5257 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005258
5259 Record.clear();
5260 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005261 Expected<unsigned> MaybeRecCode =
5262 Stream.readRecord(Entry.ID, Record, &Blob);
5263 if (!MaybeRecCode) {
5264 // FIXME this drops the error.
5265 return true;
5266 }
5267 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005268 case EXTENSION_METADATA: {
5269 ModuleFileExtensionMetadata Metadata;
5270 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5271 return true;
5272
5273 Listener.readModuleFileExtension(Metadata);
5274 break;
5275 }
5276 }
5277 }
5278 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005279 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005280 }
5281
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005282 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5283 if (readUnhashedControlBlockImpl(
5284 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5285 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5286 ValidateDiagnosticOptions) != Success)
5287 return true;
5288
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005289 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005290}
5291
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005292bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5293 const PCHContainerReader &PCHContainerRdr,
5294 const LangOptions &LangOpts,
5295 const TargetOptions &TargetOpts,
5296 const PreprocessorOptions &PPOpts,
5297 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005298 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5299 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005300 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005301 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005302 validator,
5303 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005304}
5305
Ben Langmuir2c9af442014-04-10 17:57:43 +00005306ASTReader::ASTReadResult
5307ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005309 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5310 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005311 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 }
5313
5314 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5315 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005316 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 RecordData Record;
5318 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005319 Expected<llvm::BitstreamEntry> MaybeEntry =
5320 F.Stream.advanceSkippingSubblocks();
5321 if (!MaybeEntry) {
5322 Error(MaybeEntry.takeError());
5323 return Failure;
5324 }
5325 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005326
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005327 switch (Entry.Kind) {
5328 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5329 case llvm::BitstreamEntry::Error:
5330 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005331 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005332 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005333 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005334 case llvm::BitstreamEntry::Record:
5335 // The interesting case.
5336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005338
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005340 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005342 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5343 if (!MaybeKind) {
5344 Error(MaybeKind.takeError());
5345 return Failure;
5346 }
5347 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005348
5349 if ((Kind == SUBMODULE_METADATA) != First) {
5350 Error("submodule metadata record should be at beginning of block");
5351 return Failure;
5352 }
5353 First = false;
5354
5355 // Submodule information is only valid if we have a current module.
5356 // FIXME: Should we error on these cases?
5357 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5358 Kind != SUBMODULE_DEFINITION)
5359 continue;
5360
5361 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 default: // Default behavior: ignore.
5363 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005364
Richard Smith03478d92014-10-23 22:12:14 +00005365 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005366 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005368 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 }
Richard Smith03478d92014-10-23 22:12:14 +00005370
Chris Lattner0e6c9402013-01-20 02:38:54 +00005371 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005372 unsigned Idx = 0;
5373 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5374 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005375 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005376 bool IsFramework = Record[Idx++];
5377 bool IsExplicit = Record[Idx++];
5378 bool IsSystem = Record[Idx++];
5379 bool IsExternC = Record[Idx++];
5380 bool InferSubmodules = Record[Idx++];
5381 bool InferExplicitSubmodules = Record[Idx++];
5382 bool InferExportWildcard = Record[Idx++];
5383 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005384 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005385
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005386 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005387 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005389
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 // Retrieve this (sub)module from the module map, creating it if
5391 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005392 CurrentModule =
5393 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5394 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005395
5396 // FIXME: set the definition loc for CurrentModule, or call
5397 // ModMap.setInferredModuleAllowedBy()
5398
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5400 if (GlobalIndex >= SubmodulesLoaded.size() ||
5401 SubmodulesLoaded[GlobalIndex]) {
5402 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005403 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005405
Douglas Gregor7029ce12013-03-19 00:28:20 +00005406 if (!ParentModule) {
5407 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005408 // Don't emit module relocation error if we have -fno-validate-pch
5409 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5410 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005411 if (!Diags.isDiagnosticInFlight()) {
5412 Diag(diag::err_module_file_conflict)
5413 << CurrentModule->getTopLevelModuleName()
5414 << CurFile->getName()
5415 << F.File->getName();
5416 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005417 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005418 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005419 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005420
5421 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005422 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005423 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005424
Richard Smithdd8b5332017-09-04 05:37:53 +00005425 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005426 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 CurrentModule->IsFromModuleFile = true;
5428 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005429 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 CurrentModule->InferSubmodules = InferSubmodules;
5431 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5432 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005433 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005434 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 if (DeserializationListener)
5436 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005437
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005439
Richard Smith8a3e39a2016-03-28 21:31:09 +00005440 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005441 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005442 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005443 CurrentModule->UnresolvedConflicts.clear();
5444 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005445
5446 // The module is available unless it's missing a requirement; relevant
5447 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5448 // Missing headers that were present when the module was built do not
5449 // make it unavailable -- if we got this far, this must be an explicitly
5450 // imported module file.
5451 CurrentModule->Requirements.clear();
5452 CurrentModule->MissingHeaders.clear();
5453 CurrentModule->IsMissingRequirement =
5454 ParentModule && ParentModule->IsMissingRequirement;
5455 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 break;
5457 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005458
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005460 std::string Filename = Blob;
5461 ResolveImportedPath(F, Filename);
5462 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005463 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005464 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5465 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005466 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5467 Error("mismatched umbrella headers in submodule");
5468 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 }
5470 }
5471 break;
5472 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005473
Richard Smith202210b2014-10-24 20:23:01 +00005474 case SUBMODULE_HEADER:
5475 case SUBMODULE_EXCLUDED_HEADER:
5476 case SUBMODULE_PRIVATE_HEADER:
5477 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005478 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5479 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005480 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005481
Richard Smith202210b2014-10-24 20:23:01 +00005482 case SUBMODULE_TEXTUAL_HEADER:
5483 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5484 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5485 // them here.
5486 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005487
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005488 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005489 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005490 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005491
5492 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005493 std::string Dirname = Blob;
5494 ResolveImportedPath(F, Dirname);
5495 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005496 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005497 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5498 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005499 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5500 Error("mismatched umbrella directories in submodule");
5501 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005502 }
5503 }
5504 break;
5505 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005506
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005508 F.BaseSubmoduleID = getTotalNumSubmodules();
5509 F.LocalNumSubmodules = Record[0];
5510 unsigned LocalBaseSubmoduleID = Record[1];
5511 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005512 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 // module.
5514 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005515
5516 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005517 // module.
5518 F.SubmoduleRemap.insertOrReplace(
5519 std::make_pair(LocalBaseSubmoduleID,
5520 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005521
Ben Langmuir52ca6782014-10-20 16:27:32 +00005522 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5523 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 break;
5525 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005526
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005527 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005529 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 Unresolved.File = &F;
5531 Unresolved.Mod = CurrentModule;
5532 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005533 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005535 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 }
5537 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005538
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005539 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005541 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 Unresolved.File = &F;
5543 Unresolved.Mod = CurrentModule;
5544 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005545 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005547 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005549
5550 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005551 // the parsed, unresolved exports around.
5552 CurrentModule->UnresolvedExports.clear();
5553 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005554
5555 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005556 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5557 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005559
5560 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005561 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005562 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005563 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005564 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005565
5566 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005567 CurrentModule->ConfigMacros.push_back(Blob.str());
5568 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005569
5570 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005571 UnresolvedModuleRef Unresolved;
5572 Unresolved.File = &F;
5573 Unresolved.Mod = CurrentModule;
5574 Unresolved.ID = Record[0];
5575 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5576 Unresolved.IsWildcard = false;
5577 Unresolved.String = Blob;
5578 UnresolvedModuleRefs.push_back(Unresolved);
5579 break;
5580 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005581
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005582 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005583 if (!ContextObj)
5584 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005585 SmallVector<uint32_t, 16> Inits;
5586 for (auto &ID : Record)
5587 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005588 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005589 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005591
5592 case SUBMODULE_EXPORT_AS:
5593 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005594 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005595 break;
5596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 }
5598}
5599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005600/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005601/// structure.
5602///
5603/// This routine parses the language options from the AST file and then gives
5604/// them to the AST listener if one is set.
5605///
5606/// \returns true if the listener deems the file unacceptable, false otherwise.
5607bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5608 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005609 ASTReaderListener &Listener,
5610 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 LangOptions LangOpts;
5612 unsigned Idx = 0;
5613#define LANGOPT(Name, Bits, Default, Description) \
5614 LangOpts.Name = Record[Idx++];
5615#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5616 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5617#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005618#define SANITIZER(NAME, ID) \
5619 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005620#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005621
Ben Langmuircd98cb72015-06-23 18:20:18 +00005622 for (unsigned N = Record[Idx++]; N; --N)
5623 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5624
Vedant Kumar48b4f762018-04-14 01:40:48 +00005625 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5627 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005628
Ben Langmuird4a667a2015-06-23 18:20:23 +00005629 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005630
5631 // Comment options.
5632 for (unsigned N = Record[Idx++]; N; --N) {
5633 LangOpts.CommentOpts.BlockCommandNames.push_back(
5634 ReadString(Record, Idx));
5635 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005636 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005637
Samuel Antaoee8fb302016-01-06 13:42:12 +00005638 // OpenMP offloading options.
5639 for (unsigned N = Record[Idx++]; N; --N) {
5640 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5641 }
5642
5643 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5644
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005645 return Listener.ReadLanguageOptions(LangOpts, Complain,
5646 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647}
5648
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005649bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5650 ASTReaderListener &Listener,
5651 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 unsigned Idx = 0;
5653 TargetOptions TargetOpts;
5654 TargetOpts.Triple = ReadString(Record, Idx);
5655 TargetOpts.CPU = ReadString(Record, Idx);
5656 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 for (unsigned N = Record[Idx++]; N; --N) {
5658 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5659 }
5660 for (unsigned N = Record[Idx++]; N; --N) {
5661 TargetOpts.Features.push_back(ReadString(Record, Idx));
5662 }
5663
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005664 return Listener.ReadTargetOptions(TargetOpts, Complain,
5665 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005666}
5667
5668bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5669 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005670 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005672#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005673#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005674 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005675#include "clang/Basic/DiagnosticOptions.def"
5676
Richard Smith3be1cb22014-08-07 00:24:21 +00005677 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005678 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005679 for (unsigned N = Record[Idx++]; N; --N)
5680 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005681
5682 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5683}
5684
5685bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5686 ASTReaderListener &Listener) {
5687 FileSystemOptions FSOpts;
5688 unsigned Idx = 0;
5689 FSOpts.WorkingDir = ReadString(Record, Idx);
5690 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5691}
5692
5693bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5694 bool Complain,
5695 ASTReaderListener &Listener) {
5696 HeaderSearchOptions HSOpts;
5697 unsigned Idx = 0;
5698 HSOpts.Sysroot = ReadString(Record, Idx);
5699
5700 // Include entries.
5701 for (unsigned N = Record[Idx++]; N; --N) {
5702 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005703 frontend::IncludeDirGroup Group
5704 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005705 bool IsFramework = Record[Idx++];
5706 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005707 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5708 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 }
5710
5711 // System header prefixes.
5712 for (unsigned N = Record[Idx++]; N; --N) {
5713 std::string Prefix = ReadString(Record, Idx);
5714 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005715 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 }
5717
5718 HSOpts.ResourceDir = ReadString(Record, Idx);
5719 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005720 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005721 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005722 HSOpts.ImplicitModuleMaps = Record[Idx++];
5723 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 HSOpts.UseBuiltinIncludes = Record[Idx++];
5725 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5726 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5727 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005728 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005729
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005730 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5731 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005732}
5733
5734bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5735 bool Complain,
5736 ASTReaderListener &Listener,
5737 std::string &SuggestedPredefines) {
5738 PreprocessorOptions PPOpts;
5739 unsigned Idx = 0;
5740
5741 // Macro definitions/undefs
5742 for (unsigned N = Record[Idx++]; N; --N) {
5743 std::string Macro = ReadString(Record, Idx);
5744 bool IsUndef = Record[Idx++];
5745 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5746 }
5747
5748 // Includes
5749 for (unsigned N = Record[Idx++]; N; --N) {
5750 PPOpts.Includes.push_back(ReadString(Record, Idx));
5751 }
5752
5753 // Macro Includes
5754 for (unsigned N = Record[Idx++]; N; --N) {
5755 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5756 }
5757
5758 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005759 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005760 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 PPOpts.ObjCXXARCStandardLibrary =
5762 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5763 SuggestedPredefines.clear();
5764 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5765 SuggestedPredefines);
5766}
5767
5768std::pair<ModuleFile *, unsigned>
5769ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5770 GlobalPreprocessedEntityMapType::iterator
5771 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005772 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 "Corrupted global preprocessed entity map");
5774 ModuleFile *M = I->second;
5775 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5776 return std::make_pair(M, LocalIndex);
5777}
5778
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005779llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005780ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5781 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5782 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5783 Mod.NumPreprocessedEntities);
5784
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005785 return llvm::make_range(PreprocessingRecord::iterator(),
5786 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005787}
5788
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005789llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005790ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005791 return llvm::make_range(
5792 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5793 ModuleDeclIterator(this, &Mod,
5794 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005795}
5796
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005797SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5798 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5799 assert(I != GlobalSkippedRangeMap.end() &&
5800 "Corrupted global skipped range map");
5801 ModuleFile *M = I->second;
5802 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5803 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5804 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5805 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5806 TranslateSourceLocation(*M, RawRange.getEnd()));
5807 assert(Range.isValid());
5808 return Range;
5809}
5810
Guy Benyei11169dd2012-12-18 14:30:41 +00005811PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5812 PreprocessedEntityID PPID = Index+1;
5813 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5814 ModuleFile &M = *PPInfo.first;
5815 unsigned LocalIndex = PPInfo.second;
5816 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5817
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 if (!PP.getPreprocessingRecord()) {
5819 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005820 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005822
5823 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005824 if (llvm::Error Err =
5825 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5826 Error(std::move(Err));
5827 return nullptr;
5828 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005829
JF Bastien0e828952019-06-26 19:50:12 +00005830 Expected<llvm::BitstreamEntry> MaybeEntry =
5831 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5832 if (!MaybeEntry) {
5833 Error(MaybeEntry.takeError());
5834 return nullptr;
5835 }
5836 llvm::BitstreamEntry Entry = MaybeEntry.get();
5837
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005838 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005839 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005840
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005842 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5843 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005845 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005847 Expected<unsigned> MaybeRecType =
5848 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5849 if (!MaybeRecType) {
5850 Error(MaybeRecType.takeError());
5851 return nullptr;
5852 }
5853 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005854 case PPD_MACRO_EXPANSION: {
5855 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005856 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005857 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005858 if (isBuiltin)
5859 Name = getLocalIdentifier(M, Record[1]);
5860 else {
Richard Smith66a81862015-05-04 02:25:31 +00005861 PreprocessedEntityID GlobalID =
5862 getGlobalPreprocessedEntityID(M, Record[1]);
5863 Def = cast<MacroDefinitionRecord>(
5864 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005865 }
5866
5867 MacroExpansion *ME;
5868 if (isBuiltin)
5869 ME = new (PPRec) MacroExpansion(Name, Range);
5870 else
5871 ME = new (PPRec) MacroExpansion(Def, Range);
5872
5873 return ME;
5874 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005875
Guy Benyei11169dd2012-12-18 14:30:41 +00005876 case PPD_MACRO_DEFINITION: {
5877 // Decode the identifier info and then check again; if the macro is
5878 // still defined and associated with the identifier,
5879 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005880 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005881
5882 if (DeserializationListener)
5883 DeserializationListener->MacroDefinitionRead(PPID, MD);
5884
5885 return MD;
5886 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005887
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005889 const char *FullFileNameStart = Blob.data() + Record[0];
5890 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005891 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 if (!FullFileName.empty())
5893 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005894
Guy Benyei11169dd2012-12-18 14:30:41 +00005895 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005896 InclusionDirective::InclusionKind Kind
5897 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5898 InclusionDirective *ID
5899 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005900 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 Record[1], Record[3],
5902 File,
5903 Range);
5904 return ID;
5905 }
5906 }
5907
5908 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5909}
5910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005911/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005912/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005913///
5914/// \param SLocMapI points at a chunk of a module that contains no
5915/// preprocessed entities or the entities it contains are not the ones we are
5916/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005917PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5918 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5919 ++SLocMapI;
5920 for (GlobalSLocOffsetMapType::const_iterator
5921 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5922 ModuleFile &M = *SLocMapI->second;
5923 if (M.NumPreprocessedEntities)
5924 return M.BasePreprocessedEntityID;
5925 }
5926
5927 return getTotalNumPreprocessedEntities();
5928}
5929
5930namespace {
5931
Guy Benyei11169dd2012-12-18 14:30:41 +00005932struct PPEntityComp {
5933 const ASTReader &Reader;
5934 ModuleFile &M;
5935
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005936 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005937
5938 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5939 SourceLocation LHS = getLoc(L);
5940 SourceLocation RHS = getLoc(R);
5941 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5942 }
5943
5944 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5945 SourceLocation LHS = getLoc(L);
5946 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5947 }
5948
5949 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5950 SourceLocation RHS = getLoc(R);
5951 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5952 }
5953
5954 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005955 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 }
5957};
5958
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005959} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005960
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005961PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5962 bool EndsAfter) const {
5963 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 return getTotalNumPreprocessedEntities();
5965
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005966 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5967 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5969 "Corrupted global sloc offset map");
5970
5971 if (SLocMapI->second->NumPreprocessedEntities == 0)
5972 return findNextPreprocessedEntity(SLocMapI);
5973
5974 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005975
5976 using pp_iterator = const PPEntityOffset *;
5977
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5979 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5980
5981 size_t Count = M.NumPreprocessedEntities;
5982 size_t Half;
5983 pp_iterator First = pp_begin;
5984 pp_iterator PPI;
5985
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005986 if (EndsAfter) {
5987 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005988 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005989 } else {
5990 // Do a binary search manually instead of using std::lower_bound because
5991 // The end locations of entities may be unordered (when a macro expansion
5992 // is inside another macro argument), but for this case it is not important
5993 // whether we get the first macro expansion or its containing macro.
5994 while (Count > 0) {
5995 Half = Count / 2;
5996 PPI = First;
5997 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005998 if (SourceMgr.isBeforeInTranslationUnit(
5999 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006000 First = PPI;
6001 ++First;
6002 Count = Count - Half - 1;
6003 } else
6004 Count = Half;
6005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 }
6007
6008 if (PPI == pp_end)
6009 return findNextPreprocessedEntity(SLocMapI);
6010
6011 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6012}
6013
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006014/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006015/// preprocessed entities that \arg Range encompasses.
6016std::pair<unsigned, unsigned>
6017 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6018 if (Range.isInvalid())
6019 return std::make_pair(0,0);
6020 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6021
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006022 PreprocessedEntityID BeginID =
6023 findPreprocessedEntity(Range.getBegin(), false);
6024 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 return std::make_pair(BeginID, EndID);
6026}
6027
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006028/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006029/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006030Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 FileID FID) {
6032 if (FID.isInvalid())
6033 return false;
6034
6035 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6036 ModuleFile &M = *PPInfo.first;
6037 unsigned LocalIndex = PPInfo.second;
6038 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006039
Richard Smithcb34bd32016-03-27 07:28:06 +00006040 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 if (Loc.isInvalid())
6042 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006043
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6045 return true;
6046 else
6047 return false;
6048}
6049
6050namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006052 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006055 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006058 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006059
6060 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006061 HeaderFileInfoLookupTable *Table
6062 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 if (!Table)
6064 return false;
6065
6066 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006067 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 if (Pos == Table->end())
6069 return false;
6070
Richard Smithbdf2d932015-07-30 03:37:16 +00006071 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 return true;
6073 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006074
David Blaikie05785d12013-02-20 22:23:23 +00006075 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006077
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006078} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006079
6080HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006081 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006082 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006083 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 return HeaderFileInfo();
6087}
6088
6089void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006090 using DiagState = DiagnosticsEngine::DiagState;
6091 SmallVector<DiagState *, 32> DiagStates;
6092
Vedant Kumar48b4f762018-04-14 01:40:48 +00006093 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006095 auto &Record = F.PragmaDiagMappings;
6096 if (Record.empty())
6097 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006098
Richard Smithd230de22017-01-26 01:01:01 +00006099 DiagStates.clear();
6100
6101 auto ReadDiagState =
6102 [&](const DiagState &BasedOn, SourceLocation Loc,
6103 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6104 unsigned BackrefID = Record[Idx++];
6105 if (BackrefID != 0)
6106 return DiagStates[BackrefID - 1];
6107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006109 Diag.DiagStates.push_back(BasedOn);
6110 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006112 unsigned Size = Record[Idx++];
6113 assert(Idx + Size * 2 <= Record.size() &&
6114 "Invalid data, not enough diag/map pairs");
6115 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006116 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006117 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006118 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006119 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6120 continue;
6121
6122 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6123
6124 // If this mapping was specified as a warning but the severity was
6125 // upgraded due to diagnostic settings, simulate the current diagnostic
6126 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006127 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6128 NewMapping.setSeverity(diag::Severity::Warning);
6129 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006130 }
6131
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006132 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006133 }
Richard Smithd230de22017-01-26 01:01:01 +00006134 return NewState;
6135 };
6136
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006137 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006138 DiagState *FirstState;
6139 if (F.Kind == MK_ImplicitModule) {
6140 // Implicitly-built modules are reused with different diagnostic
6141 // settings. Use the initial diagnostic state from Diag to simulate this
6142 // compilation's diagnostic settings.
6143 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6144 DiagStates.push_back(FirstState);
6145
6146 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006147 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006148 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006149 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006150 assert(Idx < Record.size() &&
6151 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006152 } else if (F.isModule()) {
6153 // For an explicit module, preserve the flags from the module build
6154 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6155 // -Wblah flags.
6156 unsigned Flags = Record[Idx++];
6157 DiagState Initial;
6158 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6159 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6160 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6161 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6162 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6163 Initial.ExtBehavior = (diag::Severity)Flags;
6164 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006165
Richard Smith6c2b5a82018-02-09 01:15:13 +00006166 assert(F.OriginalSourceFileID.isValid());
6167
Richard Smithe37391c2017-05-03 00:28:49 +00006168 // Set up the root buffer of the module to start with the initial
6169 // diagnostic state of the module itself, to cover files that contain no
6170 // explicit transitions (for which we did not serialize anything).
6171 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6172 .StateTransitions.push_back({FirstState, 0});
6173 } else {
6174 // For prefix ASTs, start with whatever the user configured on the
6175 // command line.
6176 Idx++; // Skip flags.
6177 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6178 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006179 }
Richard Smithd230de22017-01-26 01:01:01 +00006180
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006181 // Read the state transitions.
6182 unsigned NumLocations = Record[Idx++];
6183 while (NumLocations--) {
6184 assert(Idx < Record.size() &&
6185 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006186 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6187 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006188 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006189 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6190 unsigned Transitions = Record[Idx++];
6191
6192 // Note that we don't need to set up Parent/ParentOffset here, because
6193 // we won't be changing the diagnostic state within imported FileIDs
6194 // (other than perhaps appending to the main source file, which has no
6195 // parent).
6196 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6197 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6198 for (unsigned I = 0; I != Transitions; ++I) {
6199 unsigned Offset = Record[Idx++];
6200 auto *State =
6201 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6202 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 }
6204 }
Richard Smithd230de22017-01-26 01:01:01 +00006205
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006206 // Read the final state.
6207 assert(Idx < Record.size() &&
6208 "Invalid data, missing final pragma diagnostic state");
6209 SourceLocation CurStateLoc =
6210 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6211 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6212
6213 if (!F.isModule()) {
6214 Diag.DiagStatesByLoc.CurDiagState = CurState;
6215 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6216
6217 // Preserve the property that the imaginary root file describes the
6218 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006219 FileID NullFile;
6220 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006221 if (T.empty())
6222 T.push_back({CurState, 0});
6223 else
6224 T[0].State = CurState;
6225 }
6226
Richard Smithd230de22017-01-26 01:01:01 +00006227 // Don't try to read these mappings again.
6228 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 }
6230}
6231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006232/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006233ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6234 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6235 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6236 ModuleFile *M = I->second;
6237 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6238}
6239
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006240/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006241///
6242/// The index is the type ID, shifted and minus the number of predefs. This
6243/// routine actually reads the record corresponding to the type at the given
6244/// location. It is a helper routine for GetType, which deals with reading type
6245/// IDs.
6246QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006247 assert(ContextObj && "reading type with no AST context");
6248 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006249 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006250 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006251
6252 // Keep track of where we are in the stream, then jump back there
6253 // after reading this type.
6254 SavedStreamPosition SavedPosition(DeclsCursor);
6255
6256 ReadingKindTracker ReadingKind(Read_Type, *this);
6257
6258 // Note that we are loading a type record.
6259 Deserializing AType(this);
6260
6261 unsigned Idx = 0;
JF Bastien0e828952019-06-26 19:50:12 +00006262 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6263 Error(std::move(Err));
6264 return QualType();
6265 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00006267 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
6268 if (!MaybeCode) {
6269 Error(MaybeCode.takeError());
6270 return QualType();
6271 }
6272 unsigned Code = MaybeCode.get();
6273
6274 Expected<unsigned> MaybeTypeCode = DeclsCursor.readRecord(Code, Record);
6275 if (!MaybeTypeCode) {
6276 Error(MaybeTypeCode.takeError());
6277 return QualType();
6278 }
6279 switch ((TypeCode)MaybeTypeCode.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 case TYPE_EXT_QUAL: {
6281 if (Record.size() != 2) {
6282 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006283 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 }
6285 QualType Base = readType(*Loc.F, Record, Idx);
6286 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
6287 return Context.getQualifiedType(Base, Quals);
6288 }
6289
6290 case TYPE_COMPLEX: {
6291 if (Record.size() != 1) {
6292 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006293 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 }
6295 QualType ElemType = readType(*Loc.F, Record, Idx);
6296 return Context.getComplexType(ElemType);
6297 }
6298
6299 case TYPE_POINTER: {
6300 if (Record.size() != 1) {
6301 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006302 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 }
6304 QualType PointeeType = readType(*Loc.F, Record, Idx);
6305 return Context.getPointerType(PointeeType);
6306 }
6307
Reid Kleckner8a365022013-06-24 17:51:48 +00006308 case TYPE_DECAYED: {
6309 if (Record.size() != 1) {
6310 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006311 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00006312 }
6313 QualType OriginalType = readType(*Loc.F, Record, Idx);
6314 QualType DT = Context.getAdjustedParameterType(OriginalType);
6315 if (!isa<DecayedType>(DT))
6316 Error("Decayed type does not decay");
6317 return DT;
6318 }
6319
Reid Kleckner0503a872013-12-05 01:23:43 +00006320 case TYPE_ADJUSTED: {
6321 if (Record.size() != 2) {
6322 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006323 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00006324 }
6325 QualType OriginalTy = readType(*Loc.F, Record, Idx);
6326 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
6327 return Context.getAdjustedType(OriginalTy, AdjustedTy);
6328 }
6329
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 case TYPE_BLOCK_POINTER: {
6331 if (Record.size() != 1) {
6332 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006333 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 }
6335 QualType PointeeType = readType(*Loc.F, Record, Idx);
6336 return Context.getBlockPointerType(PointeeType);
6337 }
6338
6339 case TYPE_LVALUE_REFERENCE: {
6340 if (Record.size() != 2) {
6341 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006342 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 }
6344 QualType PointeeType = readType(*Loc.F, Record, Idx);
6345 return Context.getLValueReferenceType(PointeeType, Record[1]);
6346 }
6347
6348 case TYPE_RVALUE_REFERENCE: {
6349 if (Record.size() != 1) {
6350 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006351 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 }
6353 QualType PointeeType = readType(*Loc.F, Record, Idx);
6354 return Context.getRValueReferenceType(PointeeType);
6355 }
6356
6357 case TYPE_MEMBER_POINTER: {
6358 if (Record.size() != 2) {
6359 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006360 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 }
6362 QualType PointeeType = readType(*Loc.F, Record, Idx);
6363 QualType ClassType = readType(*Loc.F, Record, Idx);
6364 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006365 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006366
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
6368 }
6369
6370 case TYPE_CONSTANT_ARRAY: {
6371 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006372 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006373 unsigned IndexTypeQuals = Record[2];
6374 unsigned Idx = 3;
6375 llvm::APInt Size = ReadAPInt(Record, Idx);
6376 return Context.getConstantArrayType(ElementType, Size,
6377 ASM, IndexTypeQuals);
6378 }
6379
6380 case TYPE_INCOMPLETE_ARRAY: {
6381 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006382 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 unsigned IndexTypeQuals = Record[2];
6384 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6385 }
6386
6387 case TYPE_VARIABLE_ARRAY: {
6388 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006389 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 unsigned IndexTypeQuals = Record[2];
6391 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6392 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6393 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6394 ASM, IndexTypeQuals,
6395 SourceRange(LBLoc, RBLoc));
6396 }
6397
6398 case TYPE_VECTOR: {
6399 if (Record.size() != 3) {
6400 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006401 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 }
6403
6404 QualType ElementType = readType(*Loc.F, Record, Idx);
6405 unsigned NumElements = Record[1];
6406 unsigned VecKind = Record[2];
6407 return Context.getVectorType(ElementType, NumElements,
6408 (VectorType::VectorKind)VecKind);
6409 }
6410
6411 case TYPE_EXT_VECTOR: {
6412 if (Record.size() != 3) {
6413 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006414 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 }
6416
6417 QualType ElementType = readType(*Loc.F, Record, Idx);
6418 unsigned NumElements = Record[1];
6419 return Context.getExtVectorType(ElementType, NumElements);
6420 }
6421
6422 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006423 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006425 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006426 }
6427 QualType ResultType = readType(*Loc.F, Record, Idx);
6428 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006429 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006430 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 return Context.getFunctionNoProtoType(ResultType, Info);
6432 }
6433
6434 case TYPE_FUNCTION_PROTO: {
6435 QualType ResultType = readType(*Loc.F, Record, Idx);
6436
6437 FunctionProtoType::ExtProtoInfo EPI;
6438 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6439 /*hasregparm*/ Record[2],
6440 /*regparm*/ Record[3],
6441 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006442 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006443 /*nocallersavedregs*/ Record[6],
6444 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006445
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006446 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006447
6448 EPI.Variadic = Record[Idx++];
6449 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006450 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006452 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006453 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006454
6455 unsigned NumParams = Record[Idx++];
6456 SmallVector<QualType, 16> ParamTypes;
6457 for (unsigned I = 0; I != NumParams; ++I)
6458 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6459
John McCall18afab72016-03-01 00:49:02 +00006460 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6461 if (Idx != Record.size()) {
6462 for (unsigned I = 0; I != NumParams; ++I)
6463 ExtParameterInfos.push_back(
6464 FunctionProtoType::ExtParameterInfo
6465 ::getFromOpaqueValue(Record[Idx++]));
6466 EPI.ExtParameterInfos = ExtParameterInfos.data();
6467 }
6468
6469 assert(Idx == Record.size());
6470
Jordan Rose5c382722013-03-08 21:51:21 +00006471 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 }
6473
6474 case TYPE_UNRESOLVED_USING: {
6475 unsigned Idx = 0;
6476 return Context.getTypeDeclType(
6477 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6478 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006479
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 case TYPE_TYPEDEF: {
6481 if (Record.size() != 2) {
6482 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006483 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 }
6485 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006486 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 QualType Canonical = readType(*Loc.F, Record, Idx);
6488 if (!Canonical.isNull())
6489 Canonical = Context.getCanonicalType(Canonical);
6490 return Context.getTypedefType(Decl, Canonical);
6491 }
6492
6493 case TYPE_TYPEOF_EXPR:
6494 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6495
6496 case TYPE_TYPEOF: {
6497 if (Record.size() != 1) {
6498 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006499 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 }
6501 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6502 return Context.getTypeOfType(UnderlyingType);
6503 }
6504
6505 case TYPE_DECLTYPE: {
6506 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6507 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6508 }
6509
6510 case TYPE_UNARY_TRANSFORM: {
6511 QualType BaseType = readType(*Loc.F, Record, Idx);
6512 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006513 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6515 }
6516
Richard Smith74aeef52013-04-26 16:15:35 +00006517 case TYPE_AUTO: {
6518 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006519 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006520 bool IsDependent = false, IsPack = false;
6521 if (Deduced.isNull()) {
6522 IsDependent = Record[Idx] > 0;
6523 IsPack = Record[Idx] > 1;
6524 ++Idx;
6525 }
6526 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006527 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006528
Richard Smith600b5262017-01-26 20:40:47 +00006529 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6530 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6531 QualType Deduced = readType(*Loc.F, Record, Idx);
6532 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6533 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6534 IsDependent);
6535 }
6536
Guy Benyei11169dd2012-12-18 14:30:41 +00006537 case TYPE_RECORD: {
6538 if (Record.size() != 2) {
6539 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006540 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 }
6542 unsigned Idx = 0;
6543 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006544 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6546 QualType T = Context.getRecordType(RD);
6547 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6548 return T;
6549 }
6550
6551 case TYPE_ENUM: {
6552 if (Record.size() != 2) {
6553 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006554 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 }
6556 unsigned Idx = 0;
6557 bool IsDependent = Record[Idx++];
6558 QualType T
6559 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6560 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6561 return T;
6562 }
6563
6564 case TYPE_ATTRIBUTED: {
6565 if (Record.size() != 3) {
6566 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006567 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006568 }
6569 QualType modifiedType = readType(*Loc.F, Record, Idx);
6570 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006571 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 return Context.getAttributedType(kind, modifiedType, equivalentType);
6573 }
6574
6575 case TYPE_PAREN: {
6576 if (Record.size() != 1) {
6577 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006578 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 }
6580 QualType InnerType = readType(*Loc.F, Record, Idx);
6581 return Context.getParenType(InnerType);
6582 }
6583
Leonard Chanc72aaf62019-05-07 03:20:17 +00006584 case TYPE_MACRO_QUALIFIED: {
6585 if (Record.size() != 2) {
6586 Error("incorrect encoding of macro defined type");
6587 return QualType();
6588 }
6589 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6590 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6591 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6592 }
6593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 case TYPE_PACK_EXPANSION: {
6595 if (Record.size() != 2) {
6596 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006597 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 }
6599 QualType Pattern = readType(*Loc.F, Record, Idx);
6600 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006601 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006602 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 if (Record[1])
6604 NumExpansions = Record[1] - 1;
6605 return Context.getPackExpansionType(Pattern, NumExpansions);
6606 }
6607
6608 case TYPE_ELABORATED: {
6609 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006610 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6612 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006613 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6614 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 }
6616
6617 case TYPE_OBJC_INTERFACE: {
6618 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006619 ObjCInterfaceDecl *ItfD
6620 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6622 }
6623
Manman Rene6be26c2016-09-13 17:25:08 +00006624 case TYPE_OBJC_TYPE_PARAM: {
6625 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006626 ObjCTypeParamDecl *Decl
6627 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006628 unsigned NumProtos = Record[Idx++];
6629 SmallVector<ObjCProtocolDecl*, 4> Protos;
6630 for (unsigned I = 0; I != NumProtos; ++I)
6631 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6632 return Context.getObjCTypeParamType(Decl, Protos);
6633 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006634
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 case TYPE_OBJC_OBJECT: {
6636 unsigned Idx = 0;
6637 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006638 unsigned NumTypeArgs = Record[Idx++];
6639 SmallVector<QualType, 4> TypeArgs;
6640 for (unsigned I = 0; I != NumTypeArgs; ++I)
6641 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 unsigned NumProtos = Record[Idx++];
6643 SmallVector<ObjCProtocolDecl*, 4> Protos;
6644 for (unsigned I = 0; I != NumProtos; ++I)
6645 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006646 bool IsKindOf = Record[Idx++];
6647 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 }
6649
6650 case TYPE_OBJC_OBJECT_POINTER: {
6651 unsigned Idx = 0;
6652 QualType Pointee = readType(*Loc.F, Record, Idx);
6653 return Context.getObjCObjectPointerType(Pointee);
6654 }
6655
6656 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6657 unsigned Idx = 0;
6658 QualType Parm = readType(*Loc.F, Record, Idx);
6659 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006660 return Context.getSubstTemplateTypeParmType(
6661 cast<TemplateTypeParmType>(Parm),
6662 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 }
6664
6665 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6666 unsigned Idx = 0;
6667 QualType Parm = readType(*Loc.F, Record, Idx);
6668 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6669 return Context.getSubstTemplateTypeParmPackType(
6670 cast<TemplateTypeParmType>(Parm),
6671 ArgPack);
6672 }
6673
6674 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006675 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006676 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6677 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6678 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006679 const Type *T = nullptr;
6680 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6681 if (const Type *Existing = DI->getTypeForDecl()) {
6682 T = Existing;
6683 break;
6684 }
6685 }
6686 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006687 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006688 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6689 DI->setTypeForDecl(T);
6690 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006691 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 }
6693
6694 case TYPE_TEMPLATE_TYPE_PARM: {
6695 unsigned Idx = 0;
6696 unsigned Depth = Record[Idx++];
6697 unsigned Index = Record[Idx++];
6698 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006699 TemplateTypeParmDecl *D
6700 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6702 }
6703
6704 case TYPE_DEPENDENT_NAME: {
6705 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006706 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006708 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 QualType Canon = readType(*Loc.F, Record, Idx);
6710 if (!Canon.isNull())
6711 Canon = Context.getCanonicalType(Canon);
6712 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6713 }
6714
6715 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
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 unsigned NumArgs = Record[Idx++];
6721 SmallVector<TemplateArgument, 8> Args;
6722 Args.reserve(NumArgs);
6723 while (NumArgs--)
6724 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6725 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006726 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 }
6728
6729 case TYPE_DEPENDENT_SIZED_ARRAY: {
6730 unsigned Idx = 0;
6731
6732 // ArrayType
6733 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006734 ArrayType::ArraySizeModifier ASM
6735 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 unsigned IndexTypeQuals = Record[Idx++];
6737
6738 // DependentSizedArrayType
6739 Expr *NumElts = ReadExpr(*Loc.F);
6740 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6741
6742 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6743 IndexTypeQuals, Brackets);
6744 }
6745
6746 case TYPE_TEMPLATE_SPECIALIZATION: {
6747 unsigned Idx = 0;
6748 bool IsDependent = Record[Idx++];
6749 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6750 SmallVector<TemplateArgument, 8> Args;
6751 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6752 QualType Underlying = readType(*Loc.F, Record, Idx);
6753 QualType T;
6754 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006755 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006757 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006758 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6759 return T;
6760 }
6761
6762 case TYPE_ATOMIC: {
6763 if (Record.size() != 1) {
6764 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006765 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 }
6767 QualType ValueType = readType(*Loc.F, Record, Idx);
6768 return Context.getAtomicType(ValueType);
6769 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006770
Joey Goulye3c85de2016-12-01 11:30:49 +00006771 case TYPE_PIPE: {
6772 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006773 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006774 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006775 }
6776
6777 // Reading the pipe element type.
6778 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006779 unsigned ReadOnly = Record[1];
6780 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006781 }
6782
Erich Keanef702b022018-07-13 19:46:04 +00006783 case TYPE_DEPENDENT_SIZED_VECTOR: {
6784 unsigned Idx = 0;
6785 QualType ElementType = readType(*Loc.F, Record, Idx);
6786 Expr *SizeExpr = ReadExpr(*Loc.F);
6787 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6788 unsigned VecKind = Record[Idx];
6789
6790 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6791 (VectorType::VectorKind)VecKind);
6792 }
6793
Alex Lorenz00aee432017-03-22 10:04:48 +00006794 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6795 unsigned Idx = 0;
6796
6797 // DependentSizedExtVectorType
6798 QualType ElementType = readType(*Loc.F, Record, Idx);
6799 Expr *SizeExpr = ReadExpr(*Loc.F);
6800 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6801
6802 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6803 AttrLoc);
6804 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006805
6806 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6807 unsigned Idx = 0;
6808
6809 // DependentAddressSpaceType
6810 QualType PointeeType = readType(*Loc.F, Record, Idx);
6811 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6812 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6813
6814 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6815 AttrLoc);
6816 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 }
6818 llvm_unreachable("Invalid TypeCode!");
6819}
6820
Richard Smith564417a2014-03-20 21:47:22 +00006821void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6822 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006823 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006824 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006825 ExceptionSpecificationType EST =
6826 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006827 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006828 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006829 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006830 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006831 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006832 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006833 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006834 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006835 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6836 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006837 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006838 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006839 }
6840}
6841
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006842namespace clang {
6843
6844class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006845 ModuleFile *F;
6846 ASTReader *Reader;
6847 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006848 unsigned &Idx;
6849
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006850 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006851 return Reader->ReadSourceLocation(*F, Record, Idx);
6852 }
6853
6854 TypeSourceInfo *GetTypeSourceInfo() {
6855 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6856 }
6857
6858 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6859 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 }
6861
Richard Smithe43e2b32018-08-20 21:47:29 +00006862 Attr *ReadAttr() {
6863 return Reader->ReadAttr(*F, Record, Idx);
6864 }
6865
Guy Benyei11169dd2012-12-18 14:30:41 +00006866public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006867 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006869 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006870
6871 // We want compile-time assurance that we've enumerated all of
6872 // these, so unfortunately we have to declare them first, then
6873 // define them out-of-line.
6874#define ABSTRACT_TYPELOC(CLASS, PARENT)
6875#define TYPELOC(CLASS, PARENT) \
6876 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6877#include "clang/AST/TypeLocNodes.def"
6878
6879 void VisitFunctionTypeLoc(FunctionTypeLoc);
6880 void VisitArrayTypeLoc(ArrayTypeLoc);
6881};
6882
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006883} // namespace clang
6884
Guy Benyei11169dd2012-12-18 14:30:41 +00006885void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6886 // nothing to do
6887}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006888
Guy Benyei11169dd2012-12-18 14:30:41 +00006889void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006890 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006892 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6893 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6894 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6895 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 }
6897}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006898
Guy Benyei11169dd2012-12-18 14:30:41 +00006899void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006900 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006901}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006902
Guy Benyei11169dd2012-12-18 14:30:41 +00006903void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006904 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006905}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006906
Reid Kleckner8a365022013-06-24 17:51:48 +00006907void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6908 // nothing to do
6909}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006910
Reid Kleckner0503a872013-12-05 01:23:43 +00006911void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6912 // nothing to do
6913}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006914
Leonard Chanc72aaf62019-05-07 03:20:17 +00006915void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6916 TL.setExpansionLoc(ReadSourceLocation());
6917}
6918
Guy Benyei11169dd2012-12-18 14:30:41 +00006919void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006920 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006921}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006922
Guy Benyei11169dd2012-12-18 14:30:41 +00006923void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006924 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006925}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006926
Guy Benyei11169dd2012-12-18 14:30:41 +00006927void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006928 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006929}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006930
Guy Benyei11169dd2012-12-18 14:30:41 +00006931void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006932 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006933 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006934}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006935
Guy Benyei11169dd2012-12-18 14:30:41 +00006936void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006937 TL.setLBracketLoc(ReadSourceLocation());
6938 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006939 if (Record[Idx++])
6940 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 else
Craig Toppera13603a2014-05-22 05:54:18 +00006942 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006943}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006944
Guy Benyei11169dd2012-12-18 14:30:41 +00006945void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6946 VisitArrayTypeLoc(TL);
6947}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006948
Guy Benyei11169dd2012-12-18 14:30:41 +00006949void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6950 VisitArrayTypeLoc(TL);
6951}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006952
Guy Benyei11169dd2012-12-18 14:30:41 +00006953void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6954 VisitArrayTypeLoc(TL);
6955}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006956
Guy Benyei11169dd2012-12-18 14:30:41 +00006957void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6958 DependentSizedArrayTypeLoc TL) {
6959 VisitArrayTypeLoc(TL);
6960}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006961
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006962void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6963 DependentAddressSpaceTypeLoc TL) {
6964
6965 TL.setAttrNameLoc(ReadSourceLocation());
6966 SourceRange range;
6967 range.setBegin(ReadSourceLocation());
6968 range.setEnd(ReadSourceLocation());
6969 TL.setAttrOperandParensRange(range);
6970 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6971}
6972
Guy Benyei11169dd2012-12-18 14:30:41 +00006973void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6974 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006975 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006976}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006977
Guy Benyei11169dd2012-12-18 14:30:41 +00006978void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006979 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006980}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006981
Erich Keanef702b022018-07-13 19:46:04 +00006982void TypeLocReader::VisitDependentVectorTypeLoc(
6983 DependentVectorTypeLoc TL) {
6984 TL.setNameLoc(ReadSourceLocation());
6985}
6986
Guy Benyei11169dd2012-12-18 14:30:41 +00006987void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006988 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006989}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006990
Guy Benyei11169dd2012-12-18 14:30:41 +00006991void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006992 TL.setLocalRangeBegin(ReadSourceLocation());
6993 TL.setLParenLoc(ReadSourceLocation());
6994 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006995 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6996 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006997 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006998 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006999 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 }
7001}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007002
Guy Benyei11169dd2012-12-18 14:30:41 +00007003void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7004 VisitFunctionTypeLoc(TL);
7005}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007006
Guy Benyei11169dd2012-12-18 14:30:41 +00007007void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7008 VisitFunctionTypeLoc(TL);
7009}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007010
Guy Benyei11169dd2012-12-18 14:30:41 +00007011void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007012 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007013}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007014
Guy Benyei11169dd2012-12-18 14:30:41 +00007015void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007016 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007017}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007018
Guy Benyei11169dd2012-12-18 14:30:41 +00007019void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007020 TL.setTypeofLoc(ReadSourceLocation());
7021 TL.setLParenLoc(ReadSourceLocation());
7022 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007023}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007024
Guy Benyei11169dd2012-12-18 14:30:41 +00007025void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007026 TL.setTypeofLoc(ReadSourceLocation());
7027 TL.setLParenLoc(ReadSourceLocation());
7028 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007029 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007030}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007031
Guy Benyei11169dd2012-12-18 14:30:41 +00007032void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007033 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007034}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007037 TL.setKWLoc(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 Zelenkoe95e7d52016-09-07 21:53:17 +00007042
Guy Benyei11169dd2012-12-18 14:30:41 +00007043void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc 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
Richard Smith600b5262017-01-26 20:40:47 +00007047void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7048 DeducedTemplateSpecializationTypeLoc TL) {
7049 TL.setTemplateNameLoc(ReadSourceLocation());
7050}
7051
Guy Benyei11169dd2012-12-18 14:30:41 +00007052void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007053 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007054}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007055
Guy Benyei11169dd2012-12-18 14:30:41 +00007056void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007057 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007058}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00007061 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00007062}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007063
Guy Benyei11169dd2012-12-18 14:30:41 +00007064void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007065 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007066}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007067
Guy Benyei11169dd2012-12-18 14:30:41 +00007068void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7069 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007070 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007071}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007072
Guy Benyei11169dd2012-12-18 14:30:41 +00007073void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7074 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007075 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007076}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007077
Guy Benyei11169dd2012-12-18 14:30:41 +00007078void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7079 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007080 TL.setTemplateKeywordLoc(ReadSourceLocation());
7081 TL.setTemplateNameLoc(ReadSourceLocation());
7082 TL.setLAngleLoc(ReadSourceLocation());
7083 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007085 TL.setArgLocInfo(
7086 i,
7087 Reader->GetTemplateArgumentLocInfo(
7088 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007089}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007090
Guy Benyei11169dd2012-12-18 14:30:41 +00007091void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007092 TL.setLParenLoc(ReadSourceLocation());
7093 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007094}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007095
Guy Benyei11169dd2012-12-18 14:30:41 +00007096void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007097 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007098 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007099}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007100
Guy Benyei11169dd2012-12-18 14:30:41 +00007101void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007102 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007103}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007104
Guy Benyei11169dd2012-12-18 14:30:41 +00007105void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007106 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007107 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007108 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007109}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007110
Guy Benyei11169dd2012-12-18 14:30:41 +00007111void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7112 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007113 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007114 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007115 TL.setTemplateKeywordLoc(ReadSourceLocation());
7116 TL.setTemplateNameLoc(ReadSourceLocation());
7117 TL.setLAngleLoc(ReadSourceLocation());
7118 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007119 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007120 TL.setArgLocInfo(
7121 I,
7122 Reader->GetTemplateArgumentLocInfo(
7123 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007124}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007125
Guy Benyei11169dd2012-12-18 14:30:41 +00007126void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007127 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007128}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007129
Guy Benyei11169dd2012-12-18 14:30:41 +00007130void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007131 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007133
Manman Rene6be26c2016-09-13 17:25:08 +00007134void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7135 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007136 TL.setProtocolLAngleLoc(ReadSourceLocation());
7137 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007138 }
7139 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007140 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007141}
7142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007144 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007145 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
7146 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00007147 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007148 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007149 TL.setProtocolLAngleLoc(ReadSourceLocation());
7150 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007152 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007154
Guy Benyei11169dd2012-12-18 14:30:41 +00007155void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007156 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007157}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007158
Guy Benyei11169dd2012-12-18 14:30:41 +00007159void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007160 TL.setKWLoc(ReadSourceLocation());
7161 TL.setLParenLoc(ReadSourceLocation());
7162 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007164
Xiuli Pan9c14e282016-01-09 12:53:17 +00007165void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007166 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00007167}
Guy Benyei11169dd2012-12-18 14:30:41 +00007168
Richard Smithc23d7342018-06-29 20:46:25 +00007169void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
7170 unsigned &Idx, TypeLoc TL) {
7171 TypeLocReader TLR(F, *this, Record, Idx);
7172 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7173 TLR.Visit(TL);
7174}
7175
David L. Jonesbe1557a2016-12-21 00:17:49 +00007176TypeSourceInfo *
7177ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
7178 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 QualType InfoTy = readType(F, Record, Idx);
7180 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00007181 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007182
7183 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00007184 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 return TInfo;
7186}
7187
7188QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007189 assert(ContextObj && "reading type with no AST context");
7190 ASTContext &Context = *ContextObj;
7191
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 unsigned FastQuals = ID & Qualifiers::FastMask;
7193 unsigned Index = ID >> Qualifiers::FastWidth;
7194
7195 if (Index < NUM_PREDEF_TYPE_IDS) {
7196 QualType T;
7197 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00007198 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00007199 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00007200 case PREDEF_TYPE_VOID_ID:
7201 T = Context.VoidTy;
7202 break;
7203 case PREDEF_TYPE_BOOL_ID:
7204 T = Context.BoolTy;
7205 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007206 case PREDEF_TYPE_CHAR_U_ID:
7207 case PREDEF_TYPE_CHAR_S_ID:
7208 // FIXME: Check that the signedness of CharTy is correct!
7209 T = Context.CharTy;
7210 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007211 case PREDEF_TYPE_UCHAR_ID:
7212 T = Context.UnsignedCharTy;
7213 break;
7214 case PREDEF_TYPE_USHORT_ID:
7215 T = Context.UnsignedShortTy;
7216 break;
7217 case PREDEF_TYPE_UINT_ID:
7218 T = Context.UnsignedIntTy;
7219 break;
7220 case PREDEF_TYPE_ULONG_ID:
7221 T = Context.UnsignedLongTy;
7222 break;
7223 case PREDEF_TYPE_ULONGLONG_ID:
7224 T = Context.UnsignedLongLongTy;
7225 break;
7226 case PREDEF_TYPE_UINT128_ID:
7227 T = Context.UnsignedInt128Ty;
7228 break;
7229 case PREDEF_TYPE_SCHAR_ID:
7230 T = Context.SignedCharTy;
7231 break;
7232 case PREDEF_TYPE_WCHAR_ID:
7233 T = Context.WCharTy;
7234 break;
7235 case PREDEF_TYPE_SHORT_ID:
7236 T = Context.ShortTy;
7237 break;
7238 case PREDEF_TYPE_INT_ID:
7239 T = Context.IntTy;
7240 break;
7241 case PREDEF_TYPE_LONG_ID:
7242 T = Context.LongTy;
7243 break;
7244 case PREDEF_TYPE_LONGLONG_ID:
7245 T = Context.LongLongTy;
7246 break;
7247 case PREDEF_TYPE_INT128_ID:
7248 T = Context.Int128Ty;
7249 break;
7250 case PREDEF_TYPE_HALF_ID:
7251 T = Context.HalfTy;
7252 break;
7253 case PREDEF_TYPE_FLOAT_ID:
7254 T = Context.FloatTy;
7255 break;
7256 case PREDEF_TYPE_DOUBLE_ID:
7257 T = Context.DoubleTy;
7258 break;
7259 case PREDEF_TYPE_LONGDOUBLE_ID:
7260 T = Context.LongDoubleTy;
7261 break;
Leonard Chanf921d852018-06-04 16:07:52 +00007262 case PREDEF_TYPE_SHORT_ACCUM_ID:
7263 T = Context.ShortAccumTy;
7264 break;
7265 case PREDEF_TYPE_ACCUM_ID:
7266 T = Context.AccumTy;
7267 break;
7268 case PREDEF_TYPE_LONG_ACCUM_ID:
7269 T = Context.LongAccumTy;
7270 break;
7271 case PREDEF_TYPE_USHORT_ACCUM_ID:
7272 T = Context.UnsignedShortAccumTy;
7273 break;
7274 case PREDEF_TYPE_UACCUM_ID:
7275 T = Context.UnsignedAccumTy;
7276 break;
7277 case PREDEF_TYPE_ULONG_ACCUM_ID:
7278 T = Context.UnsignedLongAccumTy;
7279 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00007280 case PREDEF_TYPE_SHORT_FRACT_ID:
7281 T = Context.ShortFractTy;
7282 break;
7283 case PREDEF_TYPE_FRACT_ID:
7284 T = Context.FractTy;
7285 break;
7286 case PREDEF_TYPE_LONG_FRACT_ID:
7287 T = Context.LongFractTy;
7288 break;
7289 case PREDEF_TYPE_USHORT_FRACT_ID:
7290 T = Context.UnsignedShortFractTy;
7291 break;
7292 case PREDEF_TYPE_UFRACT_ID:
7293 T = Context.UnsignedFractTy;
7294 break;
7295 case PREDEF_TYPE_ULONG_FRACT_ID:
7296 T = Context.UnsignedLongFractTy;
7297 break;
7298 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7299 T = Context.SatShortAccumTy;
7300 break;
7301 case PREDEF_TYPE_SAT_ACCUM_ID:
7302 T = Context.SatAccumTy;
7303 break;
7304 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7305 T = Context.SatLongAccumTy;
7306 break;
7307 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7308 T = Context.SatUnsignedShortAccumTy;
7309 break;
7310 case PREDEF_TYPE_SAT_UACCUM_ID:
7311 T = Context.SatUnsignedAccumTy;
7312 break;
7313 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7314 T = Context.SatUnsignedLongAccumTy;
7315 break;
7316 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7317 T = Context.SatShortFractTy;
7318 break;
7319 case PREDEF_TYPE_SAT_FRACT_ID:
7320 T = Context.SatFractTy;
7321 break;
7322 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7323 T = Context.SatLongFractTy;
7324 break;
7325 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7326 T = Context.SatUnsignedShortFractTy;
7327 break;
7328 case PREDEF_TYPE_SAT_UFRACT_ID:
7329 T = Context.SatUnsignedFractTy;
7330 break;
7331 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7332 T = Context.SatUnsignedLongFractTy;
7333 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00007334 case PREDEF_TYPE_FLOAT16_ID:
7335 T = Context.Float16Ty;
7336 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007337 case PREDEF_TYPE_FLOAT128_ID:
7338 T = Context.Float128Ty;
7339 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007340 case PREDEF_TYPE_OVERLOAD_ID:
7341 T = Context.OverloadTy;
7342 break;
7343 case PREDEF_TYPE_BOUND_MEMBER:
7344 T = Context.BoundMemberTy;
7345 break;
7346 case PREDEF_TYPE_PSEUDO_OBJECT:
7347 T = Context.PseudoObjectTy;
7348 break;
7349 case PREDEF_TYPE_DEPENDENT_ID:
7350 T = Context.DependentTy;
7351 break;
7352 case PREDEF_TYPE_UNKNOWN_ANY:
7353 T = Context.UnknownAnyTy;
7354 break;
7355 case PREDEF_TYPE_NULLPTR_ID:
7356 T = Context.NullPtrTy;
7357 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007358 case PREDEF_TYPE_CHAR8_ID:
7359 T = Context.Char8Ty;
7360 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007361 case PREDEF_TYPE_CHAR16_ID:
7362 T = Context.Char16Ty;
7363 break;
7364 case PREDEF_TYPE_CHAR32_ID:
7365 T = Context.Char32Ty;
7366 break;
7367 case PREDEF_TYPE_OBJC_ID:
7368 T = Context.ObjCBuiltinIdTy;
7369 break;
7370 case PREDEF_TYPE_OBJC_CLASS:
7371 T = Context.ObjCBuiltinClassTy;
7372 break;
7373 case PREDEF_TYPE_OBJC_SEL:
7374 T = Context.ObjCBuiltinSelTy;
7375 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007376#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7377 case PREDEF_TYPE_##Id##_ID: \
7378 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007379 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007380#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007381#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7382 case PREDEF_TYPE_##Id##_ID: \
7383 T = Context.Id##Ty; \
7384 break;
7385#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007386 case PREDEF_TYPE_SAMPLER_ID:
7387 T = Context.OCLSamplerTy;
7388 break;
7389 case PREDEF_TYPE_EVENT_ID:
7390 T = Context.OCLEventTy;
7391 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007392 case PREDEF_TYPE_CLK_EVENT_ID:
7393 T = Context.OCLClkEventTy;
7394 break;
7395 case PREDEF_TYPE_QUEUE_ID:
7396 T = Context.OCLQueueTy;
7397 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007398 case PREDEF_TYPE_RESERVE_ID_ID:
7399 T = Context.OCLReserveIDTy;
7400 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007401 case PREDEF_TYPE_AUTO_DEDUCT:
7402 T = Context.getAutoDeductType();
7403 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007404 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7405 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007407 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7408 T = Context.ARCUnbridgedCastTy;
7409 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007410 case PREDEF_TYPE_BUILTIN_FN:
7411 T = Context.BuiltinFnTy;
7412 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007413 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7414 T = Context.OMPArraySectionTy;
7415 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007416 }
7417
7418 assert(!T.isNull() && "Unknown predefined type");
7419 return T.withFastQualifiers(FastQuals);
7420 }
7421
7422 Index -= NUM_PREDEF_TYPE_IDS;
7423 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7424 if (TypesLoaded[Index].isNull()) {
7425 TypesLoaded[Index] = readTypeRecord(Index);
7426 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007427 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007428
7429 TypesLoaded[Index]->setFromAST();
7430 if (DeserializationListener)
7431 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7432 TypesLoaded[Index]);
7433 }
7434
7435 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7436}
7437
7438QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7439 return GetType(getGlobalTypeID(F, LocalID));
7440}
7441
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007442serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007443ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7444 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7445 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007446
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7448 return LocalID;
7449
Richard Smith37a93df2017-02-18 00:32:02 +00007450 if (!F.ModuleOffsetMap.empty())
7451 ReadModuleOffsetMap(F);
7452
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7454 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7455 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007456
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 unsigned GlobalIndex = LocalIndex + I->second;
7458 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7459}
7460
7461TemplateArgumentLocInfo
7462ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7463 TemplateArgument::ArgKind Kind,
7464 const RecordData &Record,
7465 unsigned &Index) {
7466 switch (Kind) {
7467 case TemplateArgument::Expression:
7468 return ReadExpr(F);
7469 case TemplateArgument::Type:
7470 return GetTypeSourceInfo(F, Record, Index);
7471 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007472 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 Index);
7474 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7475 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7476 SourceLocation());
7477 }
7478 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007479 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 Index);
7481 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7482 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007483 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 EllipsisLoc);
7485 }
7486 case TemplateArgument::Null:
7487 case TemplateArgument::Integral:
7488 case TemplateArgument::Declaration:
7489 case TemplateArgument::NullPtr:
7490 case TemplateArgument::Pack:
7491 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007492 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 }
7494 llvm_unreachable("unexpected template argument loc");
7495}
7496
7497TemplateArgumentLoc
7498ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7499 const RecordData &Record, unsigned &Index) {
7500 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7501
7502 if (Arg.getKind() == TemplateArgument::Expression) {
7503 if (Record[Index++]) // bool InfoHasSameExpr.
7504 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7505 }
7506 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7507 Record, Index));
7508}
7509
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007510const ASTTemplateArgumentListInfo*
7511ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7512 const RecordData &Record,
7513 unsigned &Index) {
7514 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7515 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7516 unsigned NumArgsAsWritten = Record[Index++];
7517 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7518 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7519 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7520 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7521}
7522
Guy Benyei11169dd2012-12-18 14:30:41 +00007523Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7524 return GetDecl(ID);
7525}
7526
Richard Smith053f6c62014-05-16 23:01:30 +00007527void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007528 if (NumCurrentElementsDeserializing) {
7529 // We arrange to not care about the complete redeclaration chain while we're
7530 // deserializing. Just remember that the AST has marked this one as complete
7531 // but that it's not actually complete yet, so we know we still need to
7532 // complete it later.
7533 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7534 return;
7535 }
7536
Richard Smith053f6c62014-05-16 23:01:30 +00007537 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7538
Richard Smith053f6c62014-05-16 23:01:30 +00007539 // If this is a named declaration, complete it by looking it up
7540 // within its context.
7541 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007542 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007543 // all mergeable entities within it.
7544 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7545 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7546 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007547 if (!getContext().getLangOpts().CPlusPlus &&
7548 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007549 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007550 // the identifier instead. (For C++ modules, we don't store decls
7551 // in the serialized identifier table, so we do the lookup in the TU.)
7552 auto *II = Name.getAsIdentifierInfo();
7553 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007554 if (II->isOutOfDate())
7555 updateOutOfDateIdentifier(*II);
7556 } else
7557 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007558 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007559 // Find all declarations of this kind from the relevant context.
7560 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7561 auto *DC = cast<DeclContext>(DCDecl);
7562 SmallVector<Decl*, 8> Decls;
7563 FindExternalLexicalDecls(
7564 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7565 }
Richard Smith053f6c62014-05-16 23:01:30 +00007566 }
7567 }
Richard Smith50895422015-01-31 03:04:55 +00007568
7569 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7570 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7571 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7572 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7573 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7574 if (auto *Template = FD->getPrimaryTemplate())
7575 Template->LoadLazySpecializations();
7576 }
Richard Smith053f6c62014-05-16 23:01:30 +00007577}
7578
Richard Smithc2bb8182015-03-24 06:36:48 +00007579CXXCtorInitializer **
7580ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7581 RecordLocation Loc = getLocalBitOffset(Offset);
7582 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7583 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007584 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7585 Error(std::move(Err));
7586 return nullptr;
7587 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007588 ReadingKindTracker ReadingKind(Read_Decl, *this);
7589
7590 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007591 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7592 if (!MaybeCode) {
7593 Error(MaybeCode.takeError());
7594 return nullptr;
7595 }
7596 unsigned Code = MaybeCode.get();
7597
7598 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7599 if (!MaybeRecCode) {
7600 Error(MaybeRecCode.takeError());
7601 return nullptr;
7602 }
7603 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007604 Error("malformed AST file: missing C++ ctor initializers");
7605 return nullptr;
7606 }
7607
7608 unsigned Idx = 0;
7609 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7610}
7611
Guy Benyei11169dd2012-12-18 14:30:41 +00007612CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007613 assert(ContextObj && "reading base specifiers with no AST context");
7614 ASTContext &Context = *ContextObj;
7615
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007617 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007619 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7620 Error(std::move(Err));
7621 return nullptr;
7622 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 ReadingKindTracker ReadingKind(Read_Decl, *this);
7624 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007625
7626 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7627 if (!MaybeCode) {
7628 Error(MaybeCode.takeError());
7629 return nullptr;
7630 }
7631 unsigned Code = MaybeCode.get();
7632
7633 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7634 if (!MaybeRecCode) {
7635 Error(MaybeCode.takeError());
7636 return nullptr;
7637 }
7638 unsigned RecCode = MaybeRecCode.get();
7639
Guy Benyei11169dd2012-12-18 14:30:41 +00007640 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007641 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007642 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 }
7644
7645 unsigned Idx = 0;
7646 unsigned NumBases = Record[Idx++];
7647 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007648 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 for (unsigned I = 0; I != NumBases; ++I)
7650 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7651 return Bases;
7652}
7653
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007654serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007655ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7656 if (LocalID < NUM_PREDEF_DECL_IDS)
7657 return LocalID;
7658
Richard Smith37a93df2017-02-18 00:32:02 +00007659 if (!F.ModuleOffsetMap.empty())
7660 ReadModuleOffsetMap(F);
7661
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7663 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7664 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007665
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 return LocalID + I->second;
7667}
7668
7669bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7670 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007671 // Predefined decls aren't from any module.
7672 if (ID < NUM_PREDEF_DECL_IDS)
7673 return false;
7674
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007675 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007676 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007677}
7678
Douglas Gregor9f782892013-01-21 15:25:38 +00007679ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007681 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7683 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7684 return I->second;
7685}
7686
7687SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7688 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007689 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007690
Guy Benyei11169dd2012-12-18 14:30:41 +00007691 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7692
7693 if (Index > DeclsLoaded.size()) {
7694 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007695 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007697
Guy Benyei11169dd2012-12-18 14:30:41 +00007698 if (Decl *D = DeclsLoaded[Index])
7699 return D->getLocation();
7700
Richard Smithcb34bd32016-03-27 07:28:06 +00007701 SourceLocation Loc;
7702 DeclCursorForID(ID, Loc);
7703 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007704}
7705
Richard Smithfe620d22015-03-05 23:24:12 +00007706static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7707 switch (ID) {
7708 case PREDEF_DECL_NULL_ID:
7709 return nullptr;
7710
7711 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7712 return Context.getTranslationUnitDecl();
7713
7714 case PREDEF_DECL_OBJC_ID_ID:
7715 return Context.getObjCIdDecl();
7716
7717 case PREDEF_DECL_OBJC_SEL_ID:
7718 return Context.getObjCSelDecl();
7719
7720 case PREDEF_DECL_OBJC_CLASS_ID:
7721 return Context.getObjCClassDecl();
7722
7723 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7724 return Context.getObjCProtocolDecl();
7725
7726 case PREDEF_DECL_INT_128_ID:
7727 return Context.getInt128Decl();
7728
7729 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7730 return Context.getUInt128Decl();
7731
7732 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7733 return Context.getObjCInstanceTypeDecl();
7734
7735 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7736 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007737
Richard Smith9b88a4c2015-07-27 05:40:23 +00007738 case PREDEF_DECL_VA_LIST_TAG:
7739 return Context.getVaListTagDecl();
7740
Charles Davisc7d5c942015-09-17 20:55:33 +00007741 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7742 return Context.getBuiltinMSVaListDecl();
7743
Richard Smithf19e1272015-03-07 00:04:49 +00007744 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7745 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007746
7747 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7748 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007749
7750 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7751 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007752
7753 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7754 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007755
7756 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7757 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007758 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007759 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007760}
7761
Richard Smithcd45dbc2014-04-19 03:48:30 +00007762Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007763 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007764 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007765 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007766 if (D) {
7767 // Track that we have merged the declaration with ID \p ID into the
7768 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007769 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007770 if (Merged.empty())
7771 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007772 }
Richard Smithfe620d22015-03-05 23:24:12 +00007773 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007775
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7777
7778 if (Index >= DeclsLoaded.size()) {
7779 assert(0 && "declaration ID out-of-range for AST file");
7780 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007781 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007783
7784 return DeclsLoaded[Index];
7785}
7786
7787Decl *ASTReader::GetDecl(DeclID ID) {
7788 if (ID < NUM_PREDEF_DECL_IDS)
7789 return GetExistingDecl(ID);
7790
7791 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7792
7793 if (Index >= DeclsLoaded.size()) {
7794 assert(0 && "declaration ID out-of-range for AST file");
7795 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007796 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007797 }
7798
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 if (!DeclsLoaded[Index]) {
7800 ReadDeclRecord(ID);
7801 if (DeserializationListener)
7802 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7803 }
7804
7805 return DeclsLoaded[Index];
7806}
7807
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007808DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007809 DeclID GlobalID) {
7810 if (GlobalID < NUM_PREDEF_DECL_IDS)
7811 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007812
Guy Benyei11169dd2012-12-18 14:30:41 +00007813 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7814 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7815 ModuleFile *Owner = I->second;
7816
7817 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7818 = M.GlobalToLocalDeclIDs.find(Owner);
7819 if (Pos == M.GlobalToLocalDeclIDs.end())
7820 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007821
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 return GlobalID - Owner->BaseDeclID + Pos->second;
7823}
7824
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007825serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 const RecordData &Record,
7827 unsigned &Idx) {
7828 if (Idx >= Record.size()) {
7829 Error("Corrupted AST file");
7830 return 0;
7831 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007832
Guy Benyei11169dd2012-12-18 14:30:41 +00007833 return getGlobalDeclID(F, Record[Idx++]);
7834}
7835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007836/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007837///
7838/// This operation will read a new statement from the external
7839/// source each time it is called, and is meant to be used via a
7840/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7841Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7842 // Switch case IDs are per Decl.
7843 ClearSwitchCaseIDs();
7844
7845 // Offset here is a global offset across the entire chain.
7846 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007847 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7848 Error(std::move(Err));
7849 return nullptr;
7850 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007851 assert(NumCurrentElementsDeserializing == 0 &&
7852 "should not be called while already deserializing");
7853 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 return ReadStmtFromStream(*Loc.F);
7855}
7856
Richard Smith3cb15722015-08-05 22:41:45 +00007857void ASTReader::FindExternalLexicalDecls(
7858 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7859 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007860 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7861
Richard Smith9ccdd932015-08-06 22:14:12 +00007862 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007863 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7864 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7865 auto K = (Decl::Kind)+LexicalDecls[I];
7866 if (!IsKindWeWant(K))
7867 continue;
7868
7869 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7870
7871 // Don't add predefined declarations to the lexical context more
7872 // than once.
7873 if (ID < NUM_PREDEF_DECL_IDS) {
7874 if (PredefsVisited[ID])
7875 continue;
7876
7877 PredefsVisited[ID] = true;
7878 }
7879
7880 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007881 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007882 if (!DC->isDeclInLexicalTraversal(D))
7883 Decls.push_back(D);
7884 }
7885 }
7886 };
7887
7888 if (isa<TranslationUnitDecl>(DC)) {
7889 for (auto Lexical : TULexicalDecls)
7890 Visit(Lexical.first, Lexical.second);
7891 } else {
7892 auto I = LexicalDecls.find(DC);
7893 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007894 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007895 }
7896
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007898}
7899
7900namespace {
7901
7902class DeclIDComp {
7903 ASTReader &Reader;
7904 ModuleFile &Mod;
7905
7906public:
7907 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7908
7909 bool operator()(LocalDeclID L, LocalDeclID R) const {
7910 SourceLocation LHS = getLocation(L);
7911 SourceLocation RHS = getLocation(R);
7912 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7913 }
7914
7915 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7916 SourceLocation RHS = getLocation(R);
7917 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7918 }
7919
7920 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7921 SourceLocation LHS = getLocation(L);
7922 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7923 }
7924
7925 SourceLocation getLocation(LocalDeclID ID) const {
7926 return Reader.getSourceManager().getFileLoc(
7927 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7928 }
7929};
7930
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007931} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007932
7933void ASTReader::FindFileRegionDecls(FileID File,
7934 unsigned Offset, unsigned Length,
7935 SmallVectorImpl<Decl *> &Decls) {
7936 SourceManager &SM = getSourceManager();
7937
7938 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7939 if (I == FileDeclIDs.end())
7940 return;
7941
7942 FileDeclsInfo &DInfo = I->second;
7943 if (DInfo.Decls.empty())
7944 return;
7945
7946 SourceLocation
7947 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7948 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7949
7950 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007951 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7952 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 if (BeginIt != DInfo.Decls.begin())
7954 --BeginIt;
7955
7956 // If we are pointing at a top-level decl inside an objc container, we need
7957 // to backtrack until we find it otherwise we will fail to report that the
7958 // region overlaps with an objc container.
7959 while (BeginIt != DInfo.Decls.begin() &&
7960 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7961 ->isTopLevelDeclInObjCContainer())
7962 --BeginIt;
7963
Fangrui Song7264a472019-07-03 08:13:17 +00007964 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7965 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 if (EndIt != DInfo.Decls.end())
7967 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007968
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 for (ArrayRef<serialization::LocalDeclID>::iterator
7970 DIt = BeginIt; DIt != EndIt; ++DIt)
7971 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7972}
7973
Richard Smith9ce12e32013-02-07 03:30:24 +00007974bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007975ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7976 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007977 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 "DeclContext has no visible decls in storage");
7979 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007980 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007981
Richard Smithd88a7f12015-09-01 20:35:42 +00007982 auto It = Lookups.find(DC);
7983 if (It == Lookups.end())
7984 return false;
7985
Richard Smith8c913ec2014-08-14 02:21:01 +00007986 Deserializing LookupResults(this);
7987
Richard Smithd88a7f12015-09-01 20:35:42 +00007988 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007990 for (DeclID ID : It->second.Table.find(Name)) {
7991 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007992 if (ND->getDeclName() == Name)
7993 Decls.push_back(ND);
7994 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 ++NumVisibleDeclContextsRead;
7997 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007998 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007999}
8000
Guy Benyei11169dd2012-12-18 14:30:41 +00008001void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8002 if (!DC->hasExternalVisibleStorage())
8003 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00008004
8005 auto It = Lookups.find(DC);
8006 assert(It != Lookups.end() &&
8007 "have external visible storage but no lookup tables");
8008
Craig Topper79be4cd2013-07-05 04:33:53 +00008009 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00008010
Vedant Kumar48b4f762018-04-14 01:40:48 +00008011 for (DeclID ID : It->second.Table.findAll()) {
8012 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008013 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 }
8015
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 ++NumVisibleDeclContextsRead;
8017
Vedant Kumar48b4f762018-04-14 01:40:48 +00008018 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8019 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8020 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8022}
8023
Richard Smithd88a7f12015-09-01 20:35:42 +00008024const serialization::reader::DeclContextLookupTable *
8025ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8026 auto I = Lookups.find(Primary);
8027 return I == Lookups.end() ? nullptr : &I->second;
8028}
8029
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008030/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00008031/// before receiving the implementation, and codegen depends on this.
8032/// We simulate this by deserializing and passing to consumer the methods of the
8033/// implementation before passing the deserialized implementation decl.
8034static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8035 ASTConsumer *Consumer) {
8036 assert(ImplD && Consumer);
8037
Aaron Ballmanaff18c02014-03-13 19:03:34 +00008038 for (auto *I : ImplD->methods())
8039 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00008040
8041 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8042}
8043
Guy Benyei11169dd2012-12-18 14:30:41 +00008044void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008045 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 PassObjCImplDeclToConsumer(ImplD, Consumer);
8047 else
8048 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8049}
8050
8051void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8052 this->Consumer = Consumer;
8053
Richard Smith9e2341d2015-03-23 03:25:59 +00008054 if (Consumer)
8055 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00008056
8057 if (DeserializationListener)
8058 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00008059}
8060
8061void ASTReader::PrintStats() {
8062 std::fprintf(stderr, "*** AST File Statistics:\n");
8063
8064 unsigned NumTypesLoaded
8065 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
8066 QualType());
8067 unsigned NumDeclsLoaded
8068 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008069 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 unsigned NumIdentifiersLoaded
8071 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
8072 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008073 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 unsigned NumMacrosLoaded
8075 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
8076 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008077 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 unsigned NumSelectorsLoaded
8079 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
8080 SelectorsLoaded.end(),
8081 Selector());
8082
8083 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8084 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8085 NumSLocEntriesRead, TotalNumSLocEntries,
8086 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8087 if (!TypesLoaded.empty())
8088 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8089 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8090 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8091 if (!DeclsLoaded.empty())
8092 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8093 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8094 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8095 if (!IdentifiersLoaded.empty())
8096 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8097 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8098 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8099 if (!MacrosLoaded.empty())
8100 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8101 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8102 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8103 if (!SelectorsLoaded.empty())
8104 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8105 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8106 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8107 if (TotalNumStatements)
8108 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8109 NumStatementsRead, TotalNumStatements,
8110 ((float)NumStatementsRead/TotalNumStatements * 100));
8111 if (TotalNumMacros)
8112 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8113 NumMacrosRead, TotalNumMacros,
8114 ((float)NumMacrosRead/TotalNumMacros * 100));
8115 if (TotalLexicalDeclContexts)
8116 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8117 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8118 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8119 * 100));
8120 if (TotalVisibleDeclContexts)
8121 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8122 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8123 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8124 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008125 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8127 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8128 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8129 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008130 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008131 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8132 NumMethodPoolHits, NumMethodPoolLookups,
8133 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008134 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008135 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8136 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8137 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8138 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008139 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00008140 std::fprintf(stderr,
8141 " %u / %u identifier table lookups succeeded (%f%%)\n",
8142 NumIdentifierLookupHits, NumIdentifierLookups,
8143 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00008144
Douglas Gregore060e572013-01-25 01:03:03 +00008145 if (GlobalIndex) {
8146 std::fprintf(stderr, "\n");
8147 GlobalIndex->printStats();
8148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008149
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 std::fprintf(stderr, "\n");
8151 dump();
8152 std::fprintf(stderr, "\n");
8153}
8154
8155template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00008156LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00008157dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008158 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 InitialCapacity> &Map) {
8160 if (Map.begin() == Map.end())
8161 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008162
Vedant Kumar48b4f762018-04-14 01:40:48 +00008163 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8164
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008166 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8167 I != IEnd; ++I) {
8168 llvm::errs() << " " << I->first << " -> " << I->second->FileName
8169 << "\n";
8170 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008171}
8172
Yaron Kerencdae9412016-01-29 19:38:18 +00008173LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8175 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8176 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8177 dumpModuleIDMap("Global type map", GlobalTypeMap);
8178 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8179 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8180 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8181 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8182 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008183 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008185
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008187 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00008188 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00008189}
8190
8191/// Return the amount of memory used by memory buffers, breaking down
8192/// by heap-backed versus mmap'ed memory.
8193void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008194 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00008195 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 size_t bytes = buf->getBufferSize();
8197 switch (buf->getBufferKind()) {
8198 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8199 sizes.malloc_bytes += bytes;
8200 break;
8201 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8202 sizes.mmap_bytes += bytes;
8203 break;
8204 }
8205 }
8206 }
8207}
8208
8209void ASTReader::InitializeSema(Sema &S) {
8210 SemaObj = &S;
8211 S.addExternalSource(this);
8212
8213 // Makes sure any declarations that were deserialized "too early"
8214 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008215 for (uint64_t ID : PreloadedDeclIDs) {
8216 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00008217 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008218 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008219 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008220
Richard Smith3d8e97e2013-10-18 06:54:39 +00008221 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00008222 if (!FPPragmaOptions.empty()) {
8223 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00008224 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 }
8226
Yaxun Liu5b746652016-12-18 05:18:55 +00008227 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
8228 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
8229 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00008230
8231 UpdateSema();
8232}
8233
8234void ASTReader::UpdateSema() {
8235 assert(SemaObj && "no Sema to update");
8236
8237 // Load the offsets of the declarations that Sema references.
8238 // They will be lazily deserialized when needed.
8239 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00008240 assert(SemaDeclRefs.size() % 3 == 0);
8241 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00008242 if (!SemaObj->StdNamespace)
8243 SemaObj->StdNamespace = SemaDeclRefs[I];
8244 if (!SemaObj->StdBadAlloc)
8245 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00008246 if (!SemaObj->StdAlignValT)
8247 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00008248 }
8249 SemaDeclRefs.clear();
8250 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00008251
Nico Weber779355f2016-03-02 23:22:00 +00008252 // Update the state of pragmas. Use the same API as if we had encountered the
8253 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00008254 if(OptimizeOffPragmaLocation.isValid())
8255 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00008256 if (PragmaMSStructState != -1)
8257 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00008258 if (PointersToMembersPragmaLocation.isValid()) {
8259 SemaObj->ActOnPragmaMSPointersToMembers(
8260 (LangOptions::PragmaMSPointersToMembersKind)
8261 PragmaMSPointersToMembersState,
8262 PointersToMembersPragmaLocation);
8263 }
Justin Lebar67a78a62016-10-08 22:15:58 +00008264 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008265
8266 if (PragmaPackCurrentValue) {
8267 // The bottom of the stack might have a default value. It must be adjusted
8268 // to the current value to ensure that the packing state is preserved after
8269 // popping entries that were included/imported from a PCH/module.
8270 bool DropFirst = false;
8271 if (!PragmaPackStack.empty() &&
8272 PragmaPackStack.front().Location.isInvalid()) {
8273 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
8274 "Expected a default alignment value");
8275 SemaObj->PackStack.Stack.emplace_back(
8276 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00008277 SemaObj->PackStack.CurrentPragmaLocation,
8278 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008279 DropFirst = true;
8280 }
8281 for (const auto &Entry :
8282 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
8283 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00008284 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008285 if (PragmaPackCurrentLocation.isInvalid()) {
8286 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
8287 "Expected a default alignment value");
8288 // Keep the current values.
8289 } else {
8290 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
8291 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
8292 }
8293 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008294}
8295
Richard Smitha8d5b6a2015-07-17 19:51:03 +00008296IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 // Note that we are loading an identifier.
8298 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00008299
Douglas Gregor7211ac12013-01-25 23:32:03 +00008300 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00008301 NumIdentifierLookups,
8302 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008303
8304 // We don't need to do identifier table lookups in C++ modules (we preload
8305 // all interesting declarations, and don't need to use the scope for name
8306 // lookups). Perform the lookup in PCH files, though, since we don't build
8307 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00008308 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00008309 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008310 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00008311 break;
8312 } else {
8313 // If there is a global index, look there first to determine which modules
8314 // provably do not have any results for this identifier.
8315 GlobalModuleIndex::HitSet Hits;
8316 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8317 if (!loadGlobalIndex()) {
8318 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8319 HitsPtr = &Hits;
8320 }
8321 }
8322
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008323 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008324 }
8325
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 IdentifierInfo *II = Visitor.getIdentifierInfo();
8327 markIdentifierUpToDate(II);
8328 return II;
8329}
8330
8331namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008333 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00008334 /// identifiers stored within a set of AST files.
8335 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008336 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 const ASTReader &Reader;
8338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008339 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00008340 /// the AST reader.
8341 unsigned Index;
8342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008343 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00008344 /// of the current AST file.
8345 ASTIdentifierLookupTable::key_iterator Current;
8346
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008347 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00008348 /// the current AST file.
8349 ASTIdentifierLookupTable::key_iterator End;
8350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008351 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00008352 bool SkipModules;
8353
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00008355 explicit ASTIdentifierIterator(const ASTReader &Reader,
8356 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00008357
Craig Topper3e89dfe2014-03-13 02:13:41 +00008358 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00008359 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008360
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008361} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008362
Ben Langmuir537c5b52016-05-04 00:53:13 +00008363ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8364 bool SkipModules)
8365 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008366}
8367
8368StringRef ASTIdentifierIterator::Next() {
8369 while (Current == End) {
8370 // If we have exhausted all of our AST files, we're done.
8371 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008372 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008373
8374 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008375 ModuleFile &F = Reader.ModuleMgr[Index];
8376 if (SkipModules && F.isModule())
8377 continue;
8378
Vedant Kumar48b4f762018-04-14 01:40:48 +00008379 ASTIdentifierLookupTable *IdTable =
8380 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008381 Current = IdTable->key_begin();
8382 End = IdTable->key_end();
8383 }
8384
8385 // We have any identifiers remaining in the current AST file; return
8386 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008387 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008389 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008390}
8391
Ben Langmuir537c5b52016-05-04 00:53:13 +00008392namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008393
Ben Langmuir537c5b52016-05-04 00:53:13 +00008394/// A utility for appending two IdentifierIterators.
8395class ChainedIdentifierIterator : public IdentifierIterator {
8396 std::unique_ptr<IdentifierIterator> Current;
8397 std::unique_ptr<IdentifierIterator> Queued;
8398
8399public:
8400 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8401 std::unique_ptr<IdentifierIterator> Second)
8402 : Current(std::move(First)), Queued(std::move(Second)) {}
8403
8404 StringRef Next() override {
8405 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008406 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008407
8408 StringRef result = Current->Next();
8409 if (!result.empty())
8410 return result;
8411
8412 // Try the queued iterator, which may itself be empty.
8413 Current.reset();
8414 std::swap(Current, Queued);
8415 return Next();
8416 }
8417};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008418
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008419} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008420
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008421IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008422 if (!loadGlobalIndex()) {
8423 std::unique_ptr<IdentifierIterator> ReaderIter(
8424 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8425 std::unique_ptr<IdentifierIterator> ModulesIter(
8426 GlobalIndex->createIdentifierIterator());
8427 return new ChainedIdentifierIterator(std::move(ReaderIter),
8428 std::move(ModulesIter));
8429 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008430
Guy Benyei11169dd2012-12-18 14:30:41 +00008431 return new ASTIdentifierIterator(*this);
8432}
8433
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008434namespace clang {
8435namespace serialization {
8436
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 class ReadMethodPoolVisitor {
8438 ASTReader &Reader;
8439 Selector Sel;
8440 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008441 unsigned InstanceBits = 0;
8442 unsigned FactoryBits = 0;
8443 bool InstanceHasMoreThanOneDecl = false;
8444 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008445 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8446 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008447
8448 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008449 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008451 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008452
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008453 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008454 if (!M.SelectorLookupTable)
8455 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008456
Guy Benyei11169dd2012-12-18 14:30:41 +00008457 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008458 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 return true;
8460
Richard Smithbdf2d932015-07-30 03:37:16 +00008461 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008462 ASTSelectorLookupTable *PoolTable
8463 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008464 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008465 if (Pos == PoolTable->end())
8466 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008467
Richard Smithbdf2d932015-07-30 03:37:16 +00008468 ++Reader.NumMethodPoolTableHits;
8469 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 // FIXME: Not quite happy with the statistics here. We probably should
8471 // disable this tracking when called via LoadSelector.
8472 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008473 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008474 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008475 if (Reader.DeserializationListener)
8476 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008477
Richard Smithbdf2d932015-07-30 03:37:16 +00008478 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8479 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8480 InstanceBits = Data.InstanceBits;
8481 FactoryBits = Data.FactoryBits;
8482 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8483 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008484 return true;
8485 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008486
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008487 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008488 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8489 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 }
8491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008492 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008493 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008494 return FactoryMethods;
8495 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008496
8497 unsigned getInstanceBits() const { return InstanceBits; }
8498 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008499
Nico Weberff4b35e2014-12-27 22:14:15 +00008500 bool instanceHasMoreThanOneDecl() const {
8501 return InstanceHasMoreThanOneDecl;
8502 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008503
Nico Weberff4b35e2014-12-27 22:14:15 +00008504 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008506
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008507} // namespace serialization
8508} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008509
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008510/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008511static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8512 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008513 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8514 S.addMethodToGlobalList(&List, Methods[I]);
8515 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008516}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008517
Guy Benyei11169dd2012-12-18 14:30:41 +00008518void ASTReader::ReadMethodPool(Selector Sel) {
8519 // Get the selector generation and update it to the current generation.
8520 unsigned &Generation = SelectorGeneration[Sel];
8521 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008522 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008523 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008524
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008526 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008527 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008528 ModuleMgr.visit(Visitor);
8529
Guy Benyei11169dd2012-12-18 14:30:41 +00008530 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008531 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008532 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008533
8534 ++NumMethodPoolHits;
8535
Guy Benyei11169dd2012-12-18 14:30:41 +00008536 if (!getSema())
8537 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008538
Guy Benyei11169dd2012-12-18 14:30:41 +00008539 Sema &S = *getSema();
8540 Sema::GlobalMethodPool::iterator Pos
8541 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008542
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008543 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008544 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008545 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008546 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008547
8548 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8549 // when building a module we keep every method individually and may need to
8550 // update hasMoreThanOneDecl as we add the methods.
8551 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8552 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008553}
8554
Manman Rena0f31a02016-04-29 19:04:05 +00008555void ASTReader::updateOutOfDateSelector(Selector Sel) {
8556 if (SelectorOutOfDate[Sel])
8557 ReadMethodPool(Sel);
8558}
8559
Guy Benyei11169dd2012-12-18 14:30:41 +00008560void ASTReader::ReadKnownNamespaces(
8561 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8562 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008563
Vedant Kumar48b4f762018-04-14 01:40:48 +00008564 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8565 if (NamespaceDecl *Namespace
8566 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008567 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008568 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008569}
8570
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008571void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008572 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008573 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008574 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008575 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008576 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008577 Undefined.insert(std::make_pair(D, Loc));
8578 }
8579}
Nick Lewycky8334af82013-01-26 00:35:08 +00008580
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008581void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8582 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8583 Exprs) {
8584 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008585 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008586 uint64_t Count = DelayedDeleteExprs[Idx++];
8587 for (uint64_t C = 0; C < Count; ++C) {
8588 SourceLocation DeleteLoc =
8589 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8590 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8591 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8592 }
8593 }
8594}
8595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596void ASTReader::ReadTentativeDefinitions(
8597 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008598 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8599 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008600 if (Var)
8601 TentativeDefs.push_back(Var);
8602 }
8603 TentativeDefinitions.clear();
8604}
8605
8606void ASTReader::ReadUnusedFileScopedDecls(
8607 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008608 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8609 DeclaratorDecl *D
8610 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 if (D)
8612 Decls.push_back(D);
8613 }
8614 UnusedFileScopedDecls.clear();
8615}
8616
8617void ASTReader::ReadDelegatingConstructors(
8618 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008619 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8620 CXXConstructorDecl *D
8621 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008622 if (D)
8623 Decls.push_back(D);
8624 }
8625 DelegatingCtorDecls.clear();
8626}
8627
8628void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008629 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8630 TypedefNameDecl *D
8631 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 if (D)
8633 Decls.push_back(D);
8634 }
8635 ExtVectorDecls.clear();
8636}
8637
Nico Weber72889432014-09-06 01:25:55 +00008638void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8639 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008640 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8641 ++I) {
8642 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8643 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008644 if (D)
8645 Decls.insert(D);
8646 }
8647 UnusedLocalTypedefNameCandidates.clear();
8648}
8649
Guy Benyei11169dd2012-12-18 14:30:41 +00008650void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008651 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008652 if (ReferencedSelectorsData.empty())
8653 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008654
Guy Benyei11169dd2012-12-18 14:30:41 +00008655 // If there are @selector references added them to its pool. This is for
8656 // implementation of -Wselector.
8657 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8658 unsigned I = 0;
8659 while (I < DataSize) {
8660 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8661 SourceLocation SelLoc
8662 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8663 Sels.push_back(std::make_pair(Sel, SelLoc));
8664 }
8665 ReferencedSelectorsData.clear();
8666}
8667
8668void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008669 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008670 if (WeakUndeclaredIdentifiers.empty())
8671 return;
8672
8673 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008674 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008675 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008676 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008677 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8678 SourceLocation Loc
8679 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8680 bool Used = WeakUndeclaredIdentifiers[I++];
8681 WeakInfo WI(AliasId, Loc);
8682 WI.setUsed(Used);
8683 WeakIDs.push_back(std::make_pair(WeakId, WI));
8684 }
8685 WeakUndeclaredIdentifiers.clear();
8686}
8687
8688void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8689 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8690 ExternalVTableUse VT;
8691 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8692 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8693 VT.DefinitionRequired = VTableUses[Idx++];
8694 VTables.push_back(VT);
8695 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008696
Guy Benyei11169dd2012-12-18 14:30:41 +00008697 VTableUses.clear();
8698}
8699
8700void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008701 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008702 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008703 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008704 SourceLocation Loc
8705 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8706
8707 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008709 PendingInstantiations.clear();
8710}
8711
Richard Smithe40f2ba2013-08-07 21:41:30 +00008712void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008713 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8714 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008715 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8716 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008717 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008718
Justin Lebar28f09c52016-10-10 16:26:08 +00008719 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008720 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8721
8722 ModuleFile *F = getOwningModuleFile(LT->D);
8723 assert(F && "No module");
8724
8725 unsigned TokN = LateParsedTemplates[Idx++];
8726 LT->Toks.reserve(TokN);
8727 for (unsigned T = 0; T < TokN; ++T)
8728 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8729
Justin Lebar28f09c52016-10-10 16:26:08 +00008730 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008731 }
8732
8733 LateParsedTemplates.clear();
8734}
8735
Guy Benyei11169dd2012-12-18 14:30:41 +00008736void ASTReader::LoadSelector(Selector Sel) {
8737 // It would be complicated to avoid reading the methods anyway. So don't.
8738 ReadMethodPool(Sel);
8739}
8740
8741void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8742 assert(ID && "Non-zero identifier ID required");
8743 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8744 IdentifiersLoaded[ID - 1] = II;
8745 if (DeserializationListener)
8746 DeserializationListener->IdentifierRead(ID, II);
8747}
8748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008749/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008750/// identifier.
8751///
8752/// If the AST reader is currently in a state where the given declaration IDs
8753/// cannot safely be resolved, they are queued until it is safe to resolve
8754/// them.
8755///
8756/// \param II an IdentifierInfo that refers to one or more globally-visible
8757/// declarations.
8758///
8759/// \param DeclIDs the set of declaration IDs with the name @p II that are
8760/// visible at global scope.
8761///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008762/// \param Decls if non-null, this vector will be populated with the set of
8763/// deserialized declarations. These declarations will not be pushed into
8764/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008765void
8766ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8767 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008768 SmallVectorImpl<Decl *> *Decls) {
8769 if (NumCurrentElementsDeserializing && !Decls) {
8770 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008771 return;
8772 }
8773
Vedant Kumar48b4f762018-04-14 01:40:48 +00008774 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008775 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008776 // Queue this declaration so that it will be added to the
8777 // translation unit scope and identifier's declaration chain
8778 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008779 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008780 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008781 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008782
Vedant Kumar48b4f762018-04-14 01:40:48 +00008783 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008784
8785 // If we're simply supposed to record the declarations, do so now.
8786 if (Decls) {
8787 Decls->push_back(D);
8788 continue;
8789 }
8790
8791 // Introduce this declaration into the translation-unit scope
8792 // and add it to the declaration chain for this identifier, so
8793 // that (unqualified) name lookup will find it.
8794 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008795 }
8796}
8797
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008798IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008799 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008800 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008801
8802 if (IdentifiersLoaded.empty()) {
8803 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008804 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008805 }
8806
8807 ID -= 1;
8808 if (!IdentifiersLoaded[ID]) {
8809 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8810 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8811 ModuleFile *M = I->second;
8812 unsigned Index = ID - M->BaseIdentifierID;
8813 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8814
8815 // All of the strings in the AST file are preceded by a 16-bit length.
8816 // Extract that 16-bit length to avoid having to execute strlen().
8817 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8818 // unsigned integers. This is important to avoid integer overflow when
8819 // we cast them to 'unsigned'.
8820 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8821 unsigned StrLen = (((unsigned) StrLenPtr[0])
8822 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008823 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8824 IdentifiersLoaded[ID] = &II;
8825 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008826 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008827 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008828 }
8829
8830 return IdentifiersLoaded[ID];
8831}
8832
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008833IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8834 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008835}
8836
8837IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8838 if (LocalID < NUM_PREDEF_IDENT_IDS)
8839 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008840
Richard Smith37a93df2017-02-18 00:32:02 +00008841 if (!M.ModuleOffsetMap.empty())
8842 ReadModuleOffsetMap(M);
8843
Guy Benyei11169dd2012-12-18 14:30:41 +00008844 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8845 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008846 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008847 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008848
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 return LocalID + I->second;
8850}
8851
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008852MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008853 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008854 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008855
8856 if (MacrosLoaded.empty()) {
8857 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008858 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008859 }
8860
8861 ID -= NUM_PREDEF_MACRO_IDS;
8862 if (!MacrosLoaded[ID]) {
8863 GlobalMacroMapType::iterator I
8864 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8865 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8866 ModuleFile *M = I->second;
8867 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008868 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008869
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008870 if (DeserializationListener)
8871 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8872 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008873 }
8874
8875 return MacrosLoaded[ID];
8876}
8877
8878MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8879 if (LocalID < NUM_PREDEF_MACRO_IDS)
8880 return LocalID;
8881
Richard Smith37a93df2017-02-18 00:32:02 +00008882 if (!M.ModuleOffsetMap.empty())
8883 ReadModuleOffsetMap(M);
8884
Guy Benyei11169dd2012-12-18 14:30:41 +00008885 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8886 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8887 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8888
8889 return LocalID + I->second;
8890}
8891
8892serialization::SubmoduleID
8893ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8894 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8895 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008896
Richard Smith37a93df2017-02-18 00:32:02 +00008897 if (!M.ModuleOffsetMap.empty())
8898 ReadModuleOffsetMap(M);
8899
Guy Benyei11169dd2012-12-18 14:30:41 +00008900 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8901 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008902 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008904
Guy Benyei11169dd2012-12-18 14:30:41 +00008905 return LocalID + I->second;
8906}
8907
8908Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8909 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8910 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008911 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008912 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008913
Guy Benyei11169dd2012-12-18 14:30:41 +00008914 if (GlobalID > SubmodulesLoaded.size()) {
8915 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008916 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008917 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008918
Guy Benyei11169dd2012-12-18 14:30:41 +00008919 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8920}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008921
8922Module *ASTReader::getModule(unsigned ID) {
8923 return getSubmodule(ID);
8924}
8925
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008926bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8927 ModuleFile *MF = getOwningModuleFile(D);
8928 return MF && MF->PCHHasObjectFile;
8929}
8930
Richard Smithd88a7f12015-09-01 20:35:42 +00008931ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8932 if (ID & 1) {
8933 // It's a module, look it up by submodule ID.
8934 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8935 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8936 } else {
8937 // It's a prefix (preamble, PCH, ...). Look it up by index.
8938 unsigned IndexFromEnd = ID >> 1;
8939 assert(IndexFromEnd && "got reference to unknown module file");
8940 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8941 }
8942}
8943
8944unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8945 if (!F)
8946 return 1;
8947
8948 // For a file representing a module, use the submodule ID of the top-level
8949 // module as the file ID. For any other kind of file, the number of such
8950 // files loaded beforehand will be the same on reload.
8951 // FIXME: Is this true even if we have an explicit module file and a PCH?
8952 if (F->isModule())
8953 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8954
8955 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008956 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008957 assert(I != PCHModules.end() && "emitting reference to unknown file");
8958 return (I - PCHModules.end()) << 1;
8959}
8960
Adrian Prantl15bcf702015-06-30 17:39:43 +00008961llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8962ASTReader::getSourceDescriptor(unsigned ID) {
8963 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008964 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008965
8966 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008967 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008968 const auto &PCHChain = ModuleMgr.pch_modules();
8969 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008970 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008971 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008972 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8973 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8974 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008975 }
8976 return None;
8977}
8978
David Blaikie1ac9c982017-04-11 21:13:37 +00008979ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008980 auto I = DefinitionSource.find(FD);
8981 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008982 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008983 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008984}
8985
Guy Benyei11169dd2012-12-18 14:30:41 +00008986Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8987 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8988}
8989
8990Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8991 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008992 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008993
8994 if (ID > SelectorsLoaded.size()) {
8995 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008996 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008997 }
8998
Craig Toppera13603a2014-05-22 05:54:18 +00008999 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009000 // Load this selector from the selector table.
9001 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9002 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9003 ModuleFile &M = *I->second;
9004 ASTSelectorLookupTrait Trait(*this, M);
9005 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9006 SelectorsLoaded[ID - 1] =
9007 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9008 if (DeserializationListener)
9009 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9010 }
9011
9012 return SelectorsLoaded[ID - 1];
9013}
9014
9015Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9016 return DecodeSelector(ID);
9017}
9018
9019uint32_t ASTReader::GetNumExternalSelectors() {
9020 // ID 0 (the null selector) is considered an external selector.
9021 return getTotalNumSelectors() + 1;
9022}
9023
9024serialization::SelectorID
9025ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9026 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9027 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009028
Richard Smith37a93df2017-02-18 00:32:02 +00009029 if (!M.ModuleOffsetMap.empty())
9030 ReadModuleOffsetMap(M);
9031
Guy Benyei11169dd2012-12-18 14:30:41 +00009032 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9033 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009034 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00009035 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009036
Guy Benyei11169dd2012-12-18 14:30:41 +00009037 return LocalID + I->second;
9038}
9039
9040DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009041ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009042 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009043 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009044 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009045 switch (Kind) {
9046 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00009047 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009048
9049 case DeclarationName::ObjCZeroArgSelector:
9050 case DeclarationName::ObjCOneArgSelector:
9051 case DeclarationName::ObjCMultiArgSelector:
9052 return DeclarationName(ReadSelector(F, Record, Idx));
9053
9054 case DeclarationName::CXXConstructorName:
9055 return Context.DeclarationNames.getCXXConstructorName(
9056 Context.getCanonicalType(readType(F, Record, Idx)));
9057
9058 case DeclarationName::CXXDestructorName:
9059 return Context.DeclarationNames.getCXXDestructorName(
9060 Context.getCanonicalType(readType(F, Record, Idx)));
9061
Richard Smith35845152017-02-07 01:37:30 +00009062 case DeclarationName::CXXDeductionGuideName:
9063 return Context.DeclarationNames.getCXXDeductionGuideName(
9064 ReadDeclAs<TemplateDecl>(F, Record, Idx));
9065
Guy Benyei11169dd2012-12-18 14:30:41 +00009066 case DeclarationName::CXXConversionFunctionName:
9067 return Context.DeclarationNames.getCXXConversionFunctionName(
9068 Context.getCanonicalType(readType(F, Record, Idx)));
9069
9070 case DeclarationName::CXXOperatorName:
9071 return Context.DeclarationNames.getCXXOperatorName(
9072 (OverloadedOperatorKind)Record[Idx++]);
9073
9074 case DeclarationName::CXXLiteralOperatorName:
9075 return Context.DeclarationNames.getCXXLiteralOperatorName(
9076 GetIdentifierInfo(F, Record, Idx));
9077
9078 case DeclarationName::CXXUsingDirective:
9079 return DeclarationName::getUsingDirectiveName();
9080 }
9081
9082 llvm_unreachable("Invalid NameKind!");
9083}
9084
9085void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
9086 DeclarationNameLoc &DNLoc,
9087 DeclarationName Name,
9088 const RecordData &Record, unsigned &Idx) {
9089 switch (Name.getNameKind()) {
9090 case DeclarationName::CXXConstructorName:
9091 case DeclarationName::CXXDestructorName:
9092 case DeclarationName::CXXConversionFunctionName:
9093 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
9094 break;
9095
9096 case DeclarationName::CXXOperatorName:
9097 DNLoc.CXXOperatorName.BeginOpNameLoc
9098 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9099 DNLoc.CXXOperatorName.EndOpNameLoc
9100 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9101 break;
9102
9103 case DeclarationName::CXXLiteralOperatorName:
9104 DNLoc.CXXLiteralOperatorName.OpNameLoc
9105 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9106 break;
9107
9108 case DeclarationName::Identifier:
9109 case DeclarationName::ObjCZeroArgSelector:
9110 case DeclarationName::ObjCOneArgSelector:
9111 case DeclarationName::ObjCMultiArgSelector:
9112 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00009113 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00009114 break;
9115 }
9116}
9117
9118void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
9119 DeclarationNameInfo &NameInfo,
9120 const RecordData &Record, unsigned &Idx) {
9121 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
9122 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
9123 DeclarationNameLoc DNLoc;
9124 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
9125 NameInfo.setInfo(DNLoc);
9126}
9127
9128void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
9129 const RecordData &Record, unsigned &Idx) {
9130 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
9131 unsigned NumTPLists = Record[Idx++];
9132 Info.NumTemplParamLists = NumTPLists;
9133 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009134 Info.TemplParamLists =
9135 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00009136 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00009137 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
9138 }
9139}
9140
9141TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009142ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009143 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009144 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009145 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009146 switch (Kind) {
9147 case TemplateName::Template:
9148 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
9149
9150 case TemplateName::OverloadedTemplate: {
9151 unsigned size = Record[Idx++];
9152 UnresolvedSet<8> Decls;
9153 while (size--)
9154 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
9155
9156 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
9157 }
9158
Richard Smithb23c5e82019-05-09 03:31:27 +00009159 case TemplateName::AssumedTemplate: {
9160 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
9161 return Context.getAssumedTemplateName(Name);
9162 }
9163
Guy Benyei11169dd2012-12-18 14:30:41 +00009164 case TemplateName::QualifiedTemplate: {
9165 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9166 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009167 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009168 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
9169 }
9170
9171 case TemplateName::DependentTemplate: {
9172 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9173 if (Record[Idx++]) // isIdentifier
9174 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009175 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009176 Idx));
9177 return Context.getDependentTemplateName(NNS,
9178 (OverloadedOperatorKind)Record[Idx++]);
9179 }
9180
9181 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009182 TemplateTemplateParmDecl *param
9183 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
9184 if (!param) return TemplateName();
9185 TemplateName replacement = ReadTemplateName(F, Record, Idx);
9186 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00009187 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009188
Guy Benyei11169dd2012-12-18 14:30:41 +00009189 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009190 TemplateTemplateParmDecl *Param
9191 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009192 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009193 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009194
Guy Benyei11169dd2012-12-18 14:30:41 +00009195 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
9196 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009197 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009198
Guy Benyei11169dd2012-12-18 14:30:41 +00009199 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
9200 }
9201 }
9202
9203 llvm_unreachable("Unhandled template name kind!");
9204}
9205
Richard Smith2bb3c342015-08-09 01:05:31 +00009206TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
9207 const RecordData &Record,
9208 unsigned &Idx,
9209 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009210 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00009211 if (Canonicalize) {
9212 // The caller wants a canonical template argument. Sometimes the AST only
9213 // wants template arguments in canonical form (particularly as the template
9214 // argument lists of template specializations) so ensure we preserve that
9215 // canonical form across serialization.
9216 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
9217 return Context.getCanonicalTemplateArgument(Arg);
9218 }
9219
Vedant Kumar48b4f762018-04-14 01:40:48 +00009220 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009221 switch (Kind) {
9222 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00009223 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00009224 case TemplateArgument::Type:
9225 return TemplateArgument(readType(F, Record, Idx));
9226 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009227 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00009228 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009229 }
9230 case TemplateArgument::NullPtr:
9231 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
9232 case TemplateArgument::Integral: {
9233 llvm::APSInt Value = ReadAPSInt(Record, Idx);
9234 QualType T = readType(F, Record, Idx);
9235 return TemplateArgument(Context, Value, T);
9236 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009237 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00009238 return TemplateArgument(ReadTemplateName(F, Record, Idx));
9239 case TemplateArgument::TemplateExpansion: {
9240 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00009241 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00009242 if (unsigned NumExpansions = Record[Idx++])
9243 NumTemplateExpansions = NumExpansions - 1;
9244 return TemplateArgument(Name, NumTemplateExpansions);
9245 }
9246 case TemplateArgument::Expression:
9247 return TemplateArgument(ReadExpr(F));
9248 case TemplateArgument::Pack: {
9249 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009250 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00009251 for (unsigned I = 0; I != NumArgs; ++I)
9252 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00009253 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00009254 }
9255 }
9256
9257 llvm_unreachable("Unhandled template argument kind!");
9258}
9259
9260TemplateParameterList *
9261ASTReader::ReadTemplateParameterList(ModuleFile &F,
9262 const RecordData &Record, unsigned &Idx) {
9263 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
9264 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
9265 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
9266
9267 unsigned NumParams = Record[Idx++];
9268 SmallVector<NamedDecl *, 16> Params;
9269 Params.reserve(NumParams);
9270 while (NumParams--)
9271 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
9272
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00009273 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00009274 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
9275 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00009276 return TemplateParams;
9277}
9278
9279void
9280ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00009281ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00009282 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00009283 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009284 unsigned NumTemplateArgs = Record[Idx++];
9285 TemplArgs.reserve(NumTemplateArgs);
9286 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00009287 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00009288}
9289
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009290/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00009291void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00009292 const RecordData &Record, unsigned &Idx) {
9293 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009294 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00009295 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00009296 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009297 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009298 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00009299 }
9300}
9301
9302CXXBaseSpecifier
9303ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
9304 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009305 bool isVirtual = static_cast<bool>(Record[Idx++]);
9306 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
9307 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
9308 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009309 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
9310 SourceRange Range = ReadSourceRange(F, Record, Idx);
9311 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009312 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00009313 EllipsisLoc);
9314 Result.setInheritConstructors(inheritConstructors);
9315 return Result;
9316}
9317
Richard Smithc2bb8182015-03-24 06:36:48 +00009318CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00009319ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
9320 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009321 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009322 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009323 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009324 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00009325 for (unsigned i = 0; i != NumInitializers; ++i) {
9326 TypeSourceInfo *TInfo = nullptr;
9327 bool IsBaseVirtual = false;
9328 FieldDecl *Member = nullptr;
9329 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009330
Vedant Kumar48b4f762018-04-14 01:40:48 +00009331 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009332 switch (Type) {
9333 case CTOR_INITIALIZER_BASE:
9334 TInfo = GetTypeSourceInfo(F, Record, Idx);
9335 IsBaseVirtual = Record[Idx++];
9336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009337
Richard Smithc2bb8182015-03-24 06:36:48 +00009338 case CTOR_INITIALIZER_DELEGATING:
9339 TInfo = GetTypeSourceInfo(F, Record, Idx);
9340 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009341
Richard Smithc2bb8182015-03-24 06:36:48 +00009342 case CTOR_INITIALIZER_MEMBER:
9343 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
9344 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009345
Richard Smithc2bb8182015-03-24 06:36:48 +00009346 case CTOR_INITIALIZER_INDIRECT_MEMBER:
9347 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
9348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009349 }
Richard Smithc2bb8182015-03-24 06:36:48 +00009350
9351 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
9352 Expr *Init = ReadExpr(F);
9353 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
9354 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00009355
9356 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00009357 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00009358 BOMInit = new (Context)
9359 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9360 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009361 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00009362 BOMInit = new (Context)
9363 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009364 else if (Member)
9365 BOMInit = new (Context)
9366 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9367 Init, RParenLoc);
9368 else
9369 BOMInit = new (Context)
9370 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9371 LParenLoc, Init, RParenLoc);
9372
Richard Smith418ed822016-12-14 19:45:03 +00009373 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00009374 unsigned SourceOrder = Record[Idx++];
9375 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00009376 }
9377
Richard Smithc2bb8182015-03-24 06:36:48 +00009378 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00009379 }
9380
Richard Smithc2bb8182015-03-24 06:36:48 +00009381 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00009382}
9383
9384NestedNameSpecifier *
9385ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
9386 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009387 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009388 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00009389 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009390 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009391 NestedNameSpecifier::SpecifierKind Kind
9392 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009393 switch (Kind) {
9394 case NestedNameSpecifier::Identifier: {
9395 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
9396 NNS = NestedNameSpecifier::Create(Context, Prev, II);
9397 break;
9398 }
9399
9400 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009401 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009402 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
9403 break;
9404 }
9405
9406 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009407 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009408 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9409 break;
9410 }
9411
9412 case NestedNameSpecifier::TypeSpec:
9413 case NestedNameSpecifier::TypeSpecWithTemplate: {
9414 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9415 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009416 return nullptr;
9417
Guy Benyei11169dd2012-12-18 14:30:41 +00009418 bool Template = Record[Idx++];
9419 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9420 break;
9421 }
9422
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009423 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009424 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9425 // No associated value, and there can't be a prefix.
9426 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009427
9428 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009429 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009430 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9431 break;
9432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009433 }
9434 Prev = NNS;
9435 }
9436 return NNS;
9437}
9438
9439NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009440ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009441 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009442 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009443 unsigned N = Record[Idx++];
9444 NestedNameSpecifierLocBuilder Builder;
9445 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009446 NestedNameSpecifier::SpecifierKind Kind
9447 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009448 switch (Kind) {
9449 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009450 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009451 SourceRange Range = ReadSourceRange(F, Record, Idx);
9452 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9453 break;
9454 }
9455
9456 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009457 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009458 SourceRange Range = ReadSourceRange(F, Record, Idx);
9459 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9460 break;
9461 }
9462
9463 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009464 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009465 SourceRange Range = ReadSourceRange(F, Record, Idx);
9466 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9467 break;
9468 }
9469
9470 case NestedNameSpecifier::TypeSpec:
9471 case NestedNameSpecifier::TypeSpecWithTemplate: {
9472 bool Template = Record[Idx++];
9473 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9474 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009475 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009476 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9477
9478 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009479 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009480 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9481 T->getTypeLoc(), ColonColonLoc);
9482 break;
9483 }
9484
9485 case NestedNameSpecifier::Global: {
9486 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9487 Builder.MakeGlobal(Context, ColonColonLoc);
9488 break;
9489 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009490
9491 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009492 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009493 SourceRange Range = ReadSourceRange(F, Record, Idx);
9494 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9495 break;
9496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009497 }
9498 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009499
Guy Benyei11169dd2012-12-18 14:30:41 +00009500 return Builder.getWithLocInContext(Context);
9501}
9502
9503SourceRange
9504ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9505 unsigned &Idx) {
9506 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9507 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9508 return SourceRange(beg, end);
9509}
9510
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009511static FixedPointSemantics
9512ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9513 unsigned &Idx) {
9514 unsigned Width = Record[Idx++];
9515 unsigned Scale = Record[Idx++];
9516 uint64_t Tmp = Record[Idx++];
9517 bool IsSigned = Tmp & 0x1;
9518 bool IsSaturated = Tmp & 0x2;
9519 bool HasUnsignedPadding = Tmp & 0x4;
9520 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9521 HasUnsignedPadding);
9522}
9523
9524APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9525 unsigned Kind = Record[Idx++];
9526 switch (Kind) {
9527 case APValue::None:
9528 return APValue();
9529 case APValue::Indeterminate:
9530 return APValue::IndeterminateValue();
9531 case APValue::Int:
9532 return APValue(ReadAPSInt(Record, Idx));
9533 case APValue::Float: {
9534 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9535 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9536 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9537 }
9538 case APValue::FixedPoint: {
9539 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9540 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9541 }
9542 case APValue::ComplexInt: {
9543 llvm::APSInt First = ReadAPSInt(Record, Idx);
9544 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9545 }
9546 case APValue::ComplexFloat: {
9547 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9548 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9549 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9550 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9551 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9552 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9553 }
9554 case APValue::LValue:
9555 case APValue::Vector:
9556 case APValue::Array:
9557 case APValue::Struct:
9558 case APValue::Union:
9559 case APValue::MemberPointer:
9560 case APValue::AddrLabelDiff:
9561 // TODO : Handle all these APValue::ValueKind.
9562 return APValue();
9563 }
9564 llvm_unreachable("Invalid APValue::ValueKind");
9565}
9566
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009567/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009568llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9569 unsigned BitWidth = Record[Idx++];
9570 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9571 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9572 Idx += NumWords;
9573 return Result;
9574}
9575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009576/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009577llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9578 bool isUnsigned = Record[Idx++];
9579 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9580}
9581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009582/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009583llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9584 const llvm::fltSemantics &Sem,
9585 unsigned &Idx) {
9586 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009587}
9588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009589// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009590std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9591 unsigned Len = Record[Idx++];
9592 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9593 Idx += Len;
9594 return Result;
9595}
9596
Richard Smith7ed1bc92014-12-05 22:42:13 +00009597std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9598 unsigned &Idx) {
9599 std::string Filename = ReadString(Record, Idx);
9600 ResolveImportedPath(F, Filename);
9601 return Filename;
9602}
9603
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009604std::string ASTReader::ReadPath(StringRef BaseDirectory,
9605 const RecordData &Record, unsigned &Idx) {
9606 std::string Filename = ReadString(Record, Idx);
9607 if (!BaseDirectory.empty())
9608 ResolveImportedPath(Filename, BaseDirectory);
9609 return Filename;
9610}
9611
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009612VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009613 unsigned &Idx) {
9614 unsigned Major = Record[Idx++];
9615 unsigned Minor = Record[Idx++];
9616 unsigned Subminor = Record[Idx++];
9617 if (Minor == 0)
9618 return VersionTuple(Major);
9619 if (Subminor == 0)
9620 return VersionTuple(Major, Minor - 1);
9621 return VersionTuple(Major, Minor - 1, Subminor - 1);
9622}
9623
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009624CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009625 const RecordData &Record,
9626 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009627 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009628 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009629}
9630
Richard Smith37a93df2017-02-18 00:32:02 +00009631DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009632 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009633}
9634
Richard Smith37a93df2017-02-18 00:32:02 +00009635DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009636 return Diags.Report(Loc, DiagID);
9637}
9638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009639/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009640/// preprocessor.
9641IdentifierTable &ASTReader::getIdentifierTable() {
9642 return PP.getIdentifierTable();
9643}
9644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009645/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009646/// statement.
9647void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009648 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009649 "Already have a SwitchCase with this ID");
9650 (*CurrSwitchCaseStmts)[ID] = SC;
9651}
9652
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009653/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009654SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009655 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009656 return (*CurrSwitchCaseStmts)[ID];
9657}
9658
9659void ASTReader::ClearSwitchCaseIDs() {
9660 CurrSwitchCaseStmts->clear();
9661}
9662
9663void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009664 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009665 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009666 for (SmallVectorImpl<std::pair<BitstreamCursor,
9667 serialization::ModuleFile *>>::iterator
9668 I = CommentsCursors.begin(),
9669 E = CommentsCursors.end();
9670 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009671 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009672 BitstreamCursor &Cursor = I->first;
9673 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009674 SavedStreamPosition SavedPosition(Cursor);
9675
9676 RecordData Record;
9677 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009678 Expected<llvm::BitstreamEntry> MaybeEntry =
9679 Cursor.advanceSkippingSubblocks(
9680 BitstreamCursor::AF_DontPopBlockAtEnd);
9681 if (!MaybeEntry) {
9682 Error(MaybeEntry.takeError());
9683 return;
9684 }
9685 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009686
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009687 switch (Entry.Kind) {
9688 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9689 case llvm::BitstreamEntry::Error:
9690 Error("malformed block record in AST file");
9691 return;
9692 case llvm::BitstreamEntry::EndBlock:
9693 goto NextCursor;
9694 case llvm::BitstreamEntry::Record:
9695 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009696 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009697 }
9698
9699 // Read a record.
9700 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009701 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9702 if (!MaybeComment) {
9703 Error(MaybeComment.takeError());
9704 return;
9705 }
9706 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009707 case COMMENTS_RAW_COMMENT: {
9708 unsigned Idx = 0;
9709 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009710 RawComment::CommentKind Kind =
9711 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009712 bool IsTrailingComment = Record[Idx++];
9713 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009714 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009715 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009716 break;
9717 }
9718 }
9719 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009720 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009721 // De-serialized SourceLocations get negative FileIDs for other modules,
9722 // potentially invalidating the original order. Sort it again.
Fangrui Song55fab262018-09-26 22:16:28 +00009723 llvm::sort(Comments, BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009724 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009725 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009726}
9727
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009728void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9729 bool IncludeSystem, bool Complain,
9730 llvm::function_ref<void(const serialization::InputFile &IF,
9731 bool isSystem)> Visitor) {
9732 unsigned NumUserInputs = MF.NumUserInputFiles;
9733 unsigned NumInputs = MF.InputFilesLoaded.size();
9734 assert(NumUserInputs <= NumInputs);
9735 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9736 for (unsigned I = 0; I < N; ++I) {
9737 bool IsSystem = I >= NumUserInputs;
9738 InputFile IF = getInputFile(MF, I+1, Complain);
9739 Visitor(IF, IsSystem);
9740 }
9741}
9742
Richard Smithf3f84612017-06-29 02:19:42 +00009743void ASTReader::visitTopLevelModuleMaps(
9744 serialization::ModuleFile &MF,
9745 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9746 unsigned NumInputs = MF.InputFilesLoaded.size();
9747 for (unsigned I = 0; I < NumInputs; ++I) {
9748 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9749 if (IFI.TopLevelModuleMap)
9750 // FIXME: This unnecessarily re-reads the InputFileInfo.
9751 if (auto *FE = getInputFile(MF, I + 1).getFile())
9752 Visitor(FE);
9753 }
9754}
9755
Richard Smithcd45dbc2014-04-19 03:48:30 +00009756std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9757 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009758 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009759 return M->getFullModuleName();
9760
9761 // Otherwise, use the name of the top-level module the decl is within.
9762 if (ModuleFile *M = getOwningModuleFile(D))
9763 return M->ModuleName;
9764
9765 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009766 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009767}
9768
Guy Benyei11169dd2012-12-18 14:30:41 +00009769void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009770 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009771 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009772 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009773 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009774 // If any identifiers with corresponding top-level declarations have
9775 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009776 using TopLevelDeclsMap =
9777 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009778 TopLevelDeclsMap TopLevelDecls;
9779
Guy Benyei11169dd2012-12-18 14:30:41 +00009780 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009781 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009782 SmallVector<uint32_t, 4> DeclIDs =
9783 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009784 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009785
9786 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009787 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009788
Richard Smitha62d1982018-08-03 01:00:01 +00009789 // Load each function type that we deferred loading because it was a
9790 // deduced type that might refer to a local type declared within itself.
9791 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9792 auto *FD = PendingFunctionTypes[I].first;
9793 FD->setType(GetType(PendingFunctionTypes[I].second));
9794
9795 // If we gave a function a deduced return type, remember that we need to
9796 // propagate that along the redeclaration chain.
9797 auto *DT = FD->getReturnType()->getContainedDeducedType();
9798 if (DT && DT->isDeduced())
9799 PendingDeducedTypeUpdates.insert(
9800 {FD->getCanonicalDecl(), FD->getReturnType()});
9801 }
9802 PendingFunctionTypes.clear();
9803
Richard Smith851072e2014-05-19 20:59:20 +00009804 // For each decl chain that we wanted to complete while deserializing, mark
9805 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009806 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9807 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9808 }
Richard Smith851072e2014-05-19 20:59:20 +00009809 PendingIncompleteDeclChains.clear();
9810
Guy Benyei11169dd2012-12-18 14:30:41 +00009811 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009812 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009813 loadPendingDeclChain(PendingDeclChains[I].first,
9814 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009815 PendingDeclChains.clear();
9816
Douglas Gregor6168bd22013-02-18 15:53:43 +00009817 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009818 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9819 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9820 IdentifierInfo *II = TLD->first;
9821 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9822 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009823 }
9824 }
9825
Guy Benyei11169dd2012-12-18 14:30:41 +00009826 // Load any pending macro definitions.
9827 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009828 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9829 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9830 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9831 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009832 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009833 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009834 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009835 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009836 resolvePendingMacro(II, Info);
9837 }
9838 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009839 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009840 ++IDIdx) {
9841 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009842 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009843 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009844 }
9845 }
9846 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009847
9848 // Wire up the DeclContexts for Decls that we delayed setting until
9849 // recursive loading is completed.
9850 while (!PendingDeclContextInfos.empty()) {
9851 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9852 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009853 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9854 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009855 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9856 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009857
Richard Smithd1c46742014-04-30 02:24:17 +00009858 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009859 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009860 auto Update = PendingUpdateRecords.pop_back_val();
9861 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009862 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009863 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009864 }
Richard Smith8a639892015-01-24 01:07:20 +00009865
9866 // At this point, all update records for loaded decls are in place, so any
9867 // fake class definitions should have become real.
9868 assert(PendingFakeDefinitionData.empty() &&
9869 "faked up a class definition but never saw the real one");
9870
Guy Benyei11169dd2012-12-18 14:30:41 +00009871 // If we deserialized any C++ or Objective-C class definitions, any
9872 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009873 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009874 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009875 for (Decl *D : PendingDefinitions) {
9876 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9877 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009878 // Make sure that the TagType points at the definition.
9879 const_cast<TagType*>(TagT)->decl = TD;
9880 }
Richard Smith8ce51082015-03-11 01:44:51 +00009881
Vedant Kumar48b4f762018-04-14 01:40:48 +00009882 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009883 for (auto *R = getMostRecentExistingDecl(RD); R;
9884 R = R->getPreviousDecl()) {
9885 assert((R == D) ==
9886 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009887 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009888 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009889 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009890 }
9891
9892 continue;
9893 }
Richard Smith8ce51082015-03-11 01:44:51 +00009894
Vedant Kumar48b4f762018-04-14 01:40:48 +00009895 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009896 // Make sure that the ObjCInterfaceType points at the definition.
9897 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9898 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009899
9900 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9901 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9902
Guy Benyei11169dd2012-12-18 14:30:41 +00009903 continue;
9904 }
Richard Smith8ce51082015-03-11 01:44:51 +00009905
Vedant Kumar48b4f762018-04-14 01:40:48 +00009906 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009907 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9908 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9909
Guy Benyei11169dd2012-12-18 14:30:41 +00009910 continue;
9911 }
Richard Smith8ce51082015-03-11 01:44:51 +00009912
Vedant Kumar48b4f762018-04-14 01:40:48 +00009913 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009914 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9915 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009916 }
9917 PendingDefinitions.clear();
9918
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009919 // Load the bodies of any functions or methods we've encountered. We do
9920 // this now (delayed) so that we can be sure that the declaration chains
9921 // have been fully wired up (hasBody relies on this).
9922 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009923 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9924 PBEnd = PendingBodies.end();
9925 PB != PBEnd; ++PB) {
9926 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009927 // For a function defined inline within a class template, force the
9928 // canonical definition to be the one inside the canonical definition of
9929 // the template. This ensures that we instantiate from a correct view
9930 // of the template.
9931 //
9932 // Sadly we can't do this more generally: we can't be sure that all
9933 // copies of an arbitrary class definition will have the same members
9934 // defined (eg, some member functions may not be instantiated, and some
9935 // special members may or may not have been implicitly defined).
9936 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9937 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9938 continue;
9939
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009940 // FIXME: Check for =delete/=default?
9941 // FIXME: Complain about ODR violations here?
9942 const FunctionDecl *Defn = nullptr;
9943 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009944 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009945 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009946 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009947 mergeDefinitionVisibility(NonConstDefn, FD);
9948
9949 if (!FD->isLateTemplateParsed() &&
9950 !NonConstDefn->isLateTemplateParsed() &&
9951 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009952 if (!isa<CXXMethodDecl>(FD)) {
9953 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9954 } else if (FD->getLexicalParent()->isFileContext() &&
9955 NonConstDefn->getLexicalParent()->isFileContext()) {
9956 // Only diagnose out-of-line method definitions. If they are
9957 // in class definitions, then an error will be generated when
9958 // processing the class bodies.
9959 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9960 }
Richard Trieue6caa262017-12-23 00:41:01 +00009961 }
9962 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009963 continue;
9964 }
9965
Vedant Kumar48b4f762018-04-14 01:40:48 +00009966 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009967 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009968 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009969 }
9970 PendingBodies.clear();
9971
Richard Smith42413142015-05-15 20:05:43 +00009972 // Do some cleanup.
9973 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9974 getContext().deduplicateMergedDefinitonsFor(ND);
9975 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009976}
9977
9978void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009979 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009980 PendingFunctionOdrMergeFailures.empty() &&
9981 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009982 return;
9983
Richard Smitha0ce9c42014-07-29 23:23:27 +00009984 // Trigger the import of the full definition of each class that had any
9985 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009986 // These updates may in turn find and diagnose some ODR failures, so take
9987 // ownership of the set first.
9988 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9989 PendingOdrMergeFailures.clear();
9990 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009991 Merge.first->buildLookup();
9992 Merge.first->decls_begin();
9993 Merge.first->bases_begin();
9994 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009995 for (auto &RecordPair : Merge.second) {
9996 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009997 RD->decls_begin();
9998 RD->bases_begin();
9999 RD->vbases_begin();
10000 }
10001 }
10002
Richard Trieue6caa262017-12-23 00:41:01 +000010003 // Trigger the import of functions.
10004 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10005 PendingFunctionOdrMergeFailures.clear();
10006 for (auto &Merge : FunctionOdrMergeFailures) {
10007 Merge.first->buildLookup();
10008 Merge.first->decls_begin();
10009 Merge.first->getBody();
10010 for (auto &FD : Merge.second) {
10011 FD->buildLookup();
10012 FD->decls_begin();
10013 FD->getBody();
10014 }
10015 }
10016
Richard Trieuab4d7302018-07-25 22:52:05 +000010017 // Trigger the import of enums.
10018 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10019 PendingEnumOdrMergeFailures.clear();
10020 for (auto &Merge : EnumOdrMergeFailures) {
10021 Merge.first->decls_begin();
10022 for (auto &Enum : Merge.second) {
10023 Enum->decls_begin();
10024 }
10025 }
10026
Richard Smitha0ce9c42014-07-29 23:23:27 +000010027 // For each declaration from a merged context, check that the canonical
10028 // definition of that context also contains a declaration of the same
10029 // entity.
10030 //
10031 // Caution: this loop does things that might invalidate iterators into
10032 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10033 while (!PendingOdrMergeChecks.empty()) {
10034 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10035
10036 // FIXME: Skip over implicit declarations for now. This matters for things
10037 // like implicitly-declared special member functions. This isn't entirely
10038 // correct; we can end up with multiple unmerged declarations of the same
10039 // implicit entity.
10040 if (D->isImplicit())
10041 continue;
10042
10043 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010044
10045 bool Found = false;
10046 const Decl *DCanon = D->getCanonicalDecl();
10047
Richard Smith01bdb7a2014-08-28 05:44:07 +000010048 for (auto RI : D->redecls()) {
10049 if (RI->getLexicalDeclContext() == CanonDef) {
10050 Found = true;
10051 break;
10052 }
10053 }
10054 if (Found)
10055 continue;
10056
Richard Smith0f4e2c42015-08-06 04:23:48 +000010057 // Quick check failed, time to do the slow thing. Note, we can't just
10058 // look up the name of D in CanonDef here, because the member that is
10059 // in CanonDef might not be found by name lookup (it might have been
10060 // replaced by a more recent declaration in the lookup table), and we
10061 // can't necessarily find it in the redeclaration chain because it might
10062 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010063 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +000010064 for (auto *CanonMember : CanonDef->decls()) {
10065 if (CanonMember->getCanonicalDecl() == DCanon) {
10066 // This can happen if the declaration is merely mergeable and not
10067 // actually redeclarable (we looked for redeclarations earlier).
10068 //
10069 // FIXME: We should be able to detect this more efficiently, without
10070 // pulling in all of the members of CanonDef.
10071 Found = true;
10072 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010073 }
Richard Smith0f4e2c42015-08-06 04:23:48 +000010074 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10075 if (ND->getDeclName() == D->getDeclName())
10076 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010077 }
10078
10079 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +000010080 // The AST doesn't like TagDecls becoming invalid after they've been
10081 // completed. We only really need to mark FieldDecls as invalid here.
10082 if (!isa<TagDecl>(D))
10083 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010084
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010085 // Ensure we don't accidentally recursively enter deserialization while
10086 // we're producing our diagnostic.
10087 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010088
10089 std::string CanonDefModule =
10090 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
10091 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10092 << D << getOwningModuleNameForDiagnostic(D)
10093 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10094
10095 if (Candidates.empty())
10096 Diag(cast<Decl>(CanonDef)->getLocation(),
10097 diag::note_module_odr_violation_no_possible_decls) << D;
10098 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010099 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10100 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +000010101 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +000010102 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +000010103 }
10104
10105 DiagnosedOdrMergeFailures.insert(CanonDef);
10106 }
10107 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010108
Richard Trieuab4d7302018-07-25 22:52:05 +000010109 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
10110 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010111 return;
10112
10113 // Ensure we don't accidentally recursively enter deserialization while
10114 // we're producing our diagnostics.
10115 Deserializing RecursionGuard(this);
10116
Richard Trieue6caa262017-12-23 00:41:01 +000010117 // Common code for hashing helpers.
10118 ODRHash Hash;
10119 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
10120 Hash.clear();
10121 Hash.AddQualType(Ty);
10122 return Hash.CalculateHash();
10123 };
10124
10125 auto ComputeODRHash = [&Hash](const Stmt *S) {
10126 assert(S);
10127 Hash.clear();
10128 Hash.AddStmt(S);
10129 return Hash.CalculateHash();
10130 };
10131
10132 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
10133 assert(D);
10134 Hash.clear();
10135 Hash.AddSubDecl(D);
10136 return Hash.CalculateHash();
10137 };
10138
Richard Trieu7282d322018-04-25 00:31:15 +000010139 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
10140 Hash.clear();
10141 Hash.AddTemplateArgument(TA);
10142 return Hash.CalculateHash();
10143 };
10144
Richard Trieu9359e8f2018-05-30 01:12:26 +000010145 auto ComputeTemplateParameterListODRHash =
10146 [&Hash](const TemplateParameterList *TPL) {
10147 assert(TPL);
10148 Hash.clear();
10149 Hash.AddTemplateParameterList(TPL);
10150 return Hash.CalculateHash();
10151 };
10152
Richard Smithcd45dbc2014-04-19 03:48:30 +000010153 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010154 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010155 // If we've already pointed out a specific problem with this class, don't
10156 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010157 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010158 continue;
10159
10160 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010161 CXXRecordDecl *FirstRecord = Merge.first;
10162 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010163 for (auto &RecordPair : Merge.second) {
10164 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010165 // Multiple different declarations got merged together; tell the user
10166 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010167 if (FirstRecord == SecondRecord)
10168 continue;
10169
10170 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010171
10172 auto *FirstDD = FirstRecord->DefinitionData;
10173 auto *SecondDD = RecordPair.second;
10174
10175 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10176
10177 // Diagnostics from DefinitionData are emitted here.
10178 if (FirstDD != SecondDD) {
10179 enum ODRDefinitionDataDifference {
10180 NumBases,
10181 NumVBases,
10182 BaseType,
10183 BaseVirtual,
10184 BaseAccess,
10185 };
10186 auto ODRDiagError = [FirstRecord, &FirstModule,
10187 this](SourceLocation Loc, SourceRange Range,
10188 ODRDefinitionDataDifference DiffType) {
10189 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10190 << FirstRecord << FirstModule.empty() << FirstModule << Range
10191 << DiffType;
10192 };
10193 auto ODRDiagNote = [&SecondModule,
10194 this](SourceLocation Loc, SourceRange Range,
10195 ODRDefinitionDataDifference DiffType) {
10196 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10197 << SecondModule << Range << DiffType;
10198 };
10199
Richard Trieue13eabe2017-09-30 02:19:17 +000010200 unsigned FirstNumBases = FirstDD->NumBases;
10201 unsigned FirstNumVBases = FirstDD->NumVBases;
10202 unsigned SecondNumBases = SecondDD->NumBases;
10203 unsigned SecondNumVBases = SecondDD->NumVBases;
10204
10205 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10206 unsigned NumBases = DD->NumBases;
10207 if (NumBases == 0) return SourceRange();
10208 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010209 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010210 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010211 };
10212
10213 if (FirstNumBases != SecondNumBases) {
10214 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10215 NumBases)
10216 << FirstNumBases;
10217 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10218 NumBases)
10219 << SecondNumBases;
10220 Diagnosed = true;
10221 break;
10222 }
10223
10224 if (FirstNumVBases != SecondNumVBases) {
10225 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10226 NumVBases)
10227 << FirstNumVBases;
10228 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10229 NumVBases)
10230 << SecondNumVBases;
10231 Diagnosed = true;
10232 break;
10233 }
10234
10235 auto FirstBases = FirstDD->bases();
10236 auto SecondBases = SecondDD->bases();
10237 unsigned i = 0;
10238 for (i = 0; i < FirstNumBases; ++i) {
10239 auto FirstBase = FirstBases[i];
10240 auto SecondBase = SecondBases[i];
10241 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10242 ComputeQualTypeODRHash(SecondBase.getType())) {
10243 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10244 BaseType)
10245 << (i + 1) << FirstBase.getType();
10246 ODRDiagNote(SecondRecord->getLocation(),
10247 SecondBase.getSourceRange(), BaseType)
10248 << (i + 1) << SecondBase.getType();
10249 break;
10250 }
10251
10252 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10253 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10254 BaseVirtual)
10255 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10256 ODRDiagNote(SecondRecord->getLocation(),
10257 SecondBase.getSourceRange(), BaseVirtual)
10258 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10259 break;
10260 }
10261
10262 if (FirstBase.getAccessSpecifierAsWritten() !=
10263 SecondBase.getAccessSpecifierAsWritten()) {
10264 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10265 BaseAccess)
10266 << (i + 1) << FirstBase.getType()
10267 << (int)FirstBase.getAccessSpecifierAsWritten();
10268 ODRDiagNote(SecondRecord->getLocation(),
10269 SecondBase.getSourceRange(), BaseAccess)
10270 << (i + 1) << SecondBase.getType()
10271 << (int)SecondBase.getAccessSpecifierAsWritten();
10272 break;
10273 }
10274 }
10275
10276 if (i != FirstNumBases) {
10277 Diagnosed = true;
10278 break;
10279 }
10280 }
10281
Richard Trieue7f7ed22017-02-22 01:11:25 +000010282 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +000010283
10284 const ClassTemplateDecl *FirstTemplate =
10285 FirstRecord->getDescribedClassTemplate();
10286 const ClassTemplateDecl *SecondTemplate =
10287 SecondRecord->getDescribedClassTemplate();
10288
10289 assert(!FirstTemplate == !SecondTemplate &&
10290 "Both pointers should be null or non-null");
10291
10292 enum ODRTemplateDifference {
10293 ParamEmptyName,
10294 ParamName,
10295 ParamSingleDefaultArgument,
10296 ParamDifferentDefaultArgument,
10297 };
10298
10299 if (FirstTemplate && SecondTemplate) {
10300 DeclHashes FirstTemplateHashes;
10301 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010302
10303 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010304 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10305 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010306 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010307 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010308 }
10309 };
10310
10311 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10312 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10313
10314 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10315 "Number of template parameters should be equal.");
10316
10317 auto FirstIt = FirstTemplateHashes.begin();
10318 auto FirstEnd = FirstTemplateHashes.end();
10319 auto SecondIt = SecondTemplateHashes.begin();
10320 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10321 if (FirstIt->second == SecondIt->second)
10322 continue;
10323
10324 auto ODRDiagError = [FirstRecord, &FirstModule,
10325 this](SourceLocation Loc, SourceRange Range,
10326 ODRTemplateDifference DiffType) {
10327 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10328 << FirstRecord << FirstModule.empty() << FirstModule << Range
10329 << DiffType;
10330 };
10331 auto ODRDiagNote = [&SecondModule,
10332 this](SourceLocation Loc, SourceRange Range,
10333 ODRTemplateDifference DiffType) {
10334 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10335 << SecondModule << Range << DiffType;
10336 };
10337
Vedant Kumar48b4f762018-04-14 01:40:48 +000010338 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10339 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010340
10341 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10342 "Parameter Decl's should be the same kind.");
10343
10344 DeclarationName FirstName = FirstDecl->getDeclName();
10345 DeclarationName SecondName = SecondDecl->getDeclName();
10346
10347 if (FirstName != SecondName) {
10348 const bool FirstNameEmpty =
10349 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10350 const bool SecondNameEmpty =
10351 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10352 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10353 "Both template parameters cannot be unnamed.");
10354 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10355 FirstNameEmpty ? ParamEmptyName : ParamName)
10356 << FirstName;
10357 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10358 SecondNameEmpty ? ParamEmptyName : ParamName)
10359 << SecondName;
10360 break;
10361 }
10362
10363 switch (FirstDecl->getKind()) {
10364 default:
10365 llvm_unreachable("Invalid template parameter type.");
10366 case Decl::TemplateTypeParm: {
10367 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10368 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10369 const bool HasFirstDefaultArgument =
10370 FirstParam->hasDefaultArgument() &&
10371 !FirstParam->defaultArgumentWasInherited();
10372 const bool HasSecondDefaultArgument =
10373 SecondParam->hasDefaultArgument() &&
10374 !SecondParam->defaultArgumentWasInherited();
10375
10376 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10377 ODRDiagError(FirstDecl->getLocation(),
10378 FirstDecl->getSourceRange(),
10379 ParamSingleDefaultArgument)
10380 << HasFirstDefaultArgument;
10381 ODRDiagNote(SecondDecl->getLocation(),
10382 SecondDecl->getSourceRange(),
10383 ParamSingleDefaultArgument)
10384 << HasSecondDefaultArgument;
10385 break;
10386 }
10387
10388 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10389 "Expecting default arguments.");
10390
10391 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10392 ParamDifferentDefaultArgument);
10393 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10394 ParamDifferentDefaultArgument);
10395
10396 break;
10397 }
10398 case Decl::NonTypeTemplateParm: {
10399 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10400 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10401 const bool HasFirstDefaultArgument =
10402 FirstParam->hasDefaultArgument() &&
10403 !FirstParam->defaultArgumentWasInherited();
10404 const bool HasSecondDefaultArgument =
10405 SecondParam->hasDefaultArgument() &&
10406 !SecondParam->defaultArgumentWasInherited();
10407
10408 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10409 ODRDiagError(FirstDecl->getLocation(),
10410 FirstDecl->getSourceRange(),
10411 ParamSingleDefaultArgument)
10412 << HasFirstDefaultArgument;
10413 ODRDiagNote(SecondDecl->getLocation(),
10414 SecondDecl->getSourceRange(),
10415 ParamSingleDefaultArgument)
10416 << HasSecondDefaultArgument;
10417 break;
10418 }
10419
10420 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10421 "Expecting default arguments.");
10422
10423 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10424 ParamDifferentDefaultArgument);
10425 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10426 ParamDifferentDefaultArgument);
10427
10428 break;
10429 }
10430 case Decl::TemplateTemplateParm: {
10431 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10432 const auto *SecondParam =
10433 cast<TemplateTemplateParmDecl>(SecondDecl);
10434 const bool HasFirstDefaultArgument =
10435 FirstParam->hasDefaultArgument() &&
10436 !FirstParam->defaultArgumentWasInherited();
10437 const bool HasSecondDefaultArgument =
10438 SecondParam->hasDefaultArgument() &&
10439 !SecondParam->defaultArgumentWasInherited();
10440
10441 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10442 ODRDiagError(FirstDecl->getLocation(),
10443 FirstDecl->getSourceRange(),
10444 ParamSingleDefaultArgument)
10445 << HasFirstDefaultArgument;
10446 ODRDiagNote(SecondDecl->getLocation(),
10447 SecondDecl->getSourceRange(),
10448 ParamSingleDefaultArgument)
10449 << HasSecondDefaultArgument;
10450 break;
10451 }
10452
10453 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10454 "Expecting default arguments.");
10455
10456 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10457 ParamDifferentDefaultArgument);
10458 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10459 ParamDifferentDefaultArgument);
10460
10461 break;
10462 }
10463 }
10464
10465 break;
10466 }
10467
10468 if (FirstIt != FirstEnd) {
10469 Diagnosed = true;
10470 break;
10471 }
10472 }
10473
Richard Trieue7f7ed22017-02-22 01:11:25 +000010474 DeclHashes FirstHashes;
10475 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010476
Richard Trieue6caa262017-12-23 00:41:01 +000010477 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10478 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010479 for (auto *D : Record->decls()) {
10480 // Due to decl merging, the first CXXRecordDecl is the parent of
10481 // Decls in both records.
10482 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10483 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010484 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010485 }
10486 };
10487 PopulateHashes(FirstHashes, FirstRecord);
10488 PopulateHashes(SecondHashes, SecondRecord);
10489
10490 // Used with err_module_odr_violation_mismatch_decl and
10491 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010492 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010493 enum {
10494 EndOfClass,
10495 PublicSpecifer,
10496 PrivateSpecifer,
10497 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010498 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010499 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010500 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010501 TypeAlias,
10502 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010503 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010504 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010505 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010506 Other
10507 } FirstDiffType = Other,
10508 SecondDiffType = Other;
10509
10510 auto DifferenceSelector = [](Decl *D) {
10511 assert(D && "valid Decl required");
10512 switch (D->getKind()) {
10513 default:
10514 return Other;
10515 case Decl::AccessSpec:
10516 switch (D->getAccess()) {
10517 case AS_public:
10518 return PublicSpecifer;
10519 case AS_private:
10520 return PrivateSpecifer;
10521 case AS_protected:
10522 return ProtectedSpecifer;
10523 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010524 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010525 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010526 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010527 case Decl::StaticAssert:
10528 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010529 case Decl::Field:
10530 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010531 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010532 case Decl::CXXConstructor:
10533 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010534 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010535 case Decl::TypeAlias:
10536 return TypeAlias;
10537 case Decl::Typedef:
10538 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010539 case Decl::Var:
10540 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010541 case Decl::Friend:
10542 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010543 case Decl::FunctionTemplate:
10544 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010545 }
10546 };
10547
10548 Decl *FirstDecl = nullptr;
10549 Decl *SecondDecl = nullptr;
10550 auto FirstIt = FirstHashes.begin();
10551 auto SecondIt = SecondHashes.begin();
10552
10553 // If there is a diagnoseable difference, FirstDiffType and
10554 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10555 // filled in if not EndOfClass.
10556 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010557 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10558 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010559 ++FirstIt;
10560 ++SecondIt;
10561 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010562 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010563
Richard Trieue7f7ed22017-02-22 01:11:25 +000010564 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10565 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10566
10567 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10568 SecondDiffType =
10569 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10570
10571 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010572 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010573
10574 if (FirstDiffType == Other || SecondDiffType == Other) {
10575 // Reaching this point means an unexpected Decl was encountered
10576 // or no difference was detected. This causes a generic error
10577 // message to be emitted.
10578 Diag(FirstRecord->getLocation(),
10579 diag::err_module_odr_violation_different_definitions)
10580 << FirstRecord << FirstModule.empty() << FirstModule;
10581
Richard Trieuca48d362017-06-21 01:43:13 +000010582 if (FirstDecl) {
10583 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10584 << FirstRecord << FirstDecl->getSourceRange();
10585 }
10586
Richard Trieue7f7ed22017-02-22 01:11:25 +000010587 Diag(SecondRecord->getLocation(),
10588 diag::note_module_odr_violation_different_definitions)
10589 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010590
10591 if (SecondDecl) {
10592 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10593 << SecondDecl->getSourceRange();
10594 }
10595
Richard Trieue7f7ed22017-02-22 01:11:25 +000010596 Diagnosed = true;
10597 break;
10598 }
10599
10600 if (FirstDiffType != SecondDiffType) {
10601 SourceLocation FirstLoc;
10602 SourceRange FirstRange;
10603 if (FirstDiffType == EndOfClass) {
10604 FirstLoc = FirstRecord->getBraceRange().getEnd();
10605 } else {
10606 FirstLoc = FirstIt->first->getLocation();
10607 FirstRange = FirstIt->first->getSourceRange();
10608 }
10609 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10610 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10611 << FirstDiffType;
10612
10613 SourceLocation SecondLoc;
10614 SourceRange SecondRange;
10615 if (SecondDiffType == EndOfClass) {
10616 SecondLoc = SecondRecord->getBraceRange().getEnd();
10617 } else {
10618 SecondLoc = SecondDecl->getLocation();
10619 SecondRange = SecondDecl->getSourceRange();
10620 }
10621 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10622 << SecondModule << SecondRange << SecondDiffType;
10623 Diagnosed = true;
10624 break;
10625 }
10626
Richard Trieu639d7b62017-02-22 22:22:42 +000010627 assert(FirstDiffType == SecondDiffType);
10628
10629 // Used with err_module_odr_violation_mismatch_decl_diff and
10630 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010631 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010632 StaticAssertCondition,
10633 StaticAssertMessage,
10634 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010635 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010636 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010637 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010638 FieldDifferentWidthBitField,
10639 FieldSingleMutable,
10640 FieldSingleInitializer,
10641 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010642 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010643 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010644 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010645 MethodVirtual,
10646 MethodStatic,
10647 MethodVolatile,
10648 MethodConst,
10649 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010650 MethodNumberParameters,
10651 MethodParameterType,
10652 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010653 MethodParameterSingleDefaultArgument,
10654 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010655 MethodNoTemplateArguments,
10656 MethodDifferentNumberTemplateArguments,
10657 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010658 MethodSingleBody,
10659 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010660 TypedefName,
10661 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010662 VarName,
10663 VarType,
10664 VarSingleInitializer,
10665 VarDifferentInitializer,
10666 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010667 FriendTypeFunction,
10668 FriendType,
10669 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010670 FunctionTemplateDifferentNumberParameters,
10671 FunctionTemplateParameterDifferentKind,
10672 FunctionTemplateParameterName,
10673 FunctionTemplateParameterSingleDefaultArgument,
10674 FunctionTemplateParameterDifferentDefaultArgument,
10675 FunctionTemplateParameterDifferentType,
10676 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010677 };
10678
10679 // These lambdas have the common portions of the ODR diagnostics. This
10680 // has the same return as Diag(), so addition parameters can be passed
10681 // in with operator<<
10682 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10683 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10684 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10685 << FirstRecord << FirstModule.empty() << FirstModule << Range
10686 << DiffType;
10687 };
10688 auto ODRDiagNote = [&SecondModule, this](
10689 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10690 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10691 << SecondModule << Range << DiffType;
10692 };
10693
Richard Trieu639d7b62017-02-22 22:22:42 +000010694 switch (FirstDiffType) {
10695 case Other:
10696 case EndOfClass:
10697 case PublicSpecifer:
10698 case PrivateSpecifer:
10699 case ProtectedSpecifer:
10700 llvm_unreachable("Invalid diff type");
10701
10702 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010703 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10704 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010705
10706 Expr *FirstExpr = FirstSA->getAssertExpr();
10707 Expr *SecondExpr = SecondSA->getAssertExpr();
10708 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10709 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10710 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010711 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010712 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010713 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10714 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010715 Diagnosed = true;
10716 break;
10717 }
10718
10719 StringLiteral *FirstStr = FirstSA->getMessage();
10720 StringLiteral *SecondStr = SecondSA->getMessage();
10721 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10722 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10723 SourceLocation FirstLoc, SecondLoc;
10724 SourceRange FirstRange, SecondRange;
10725 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010726 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010727 FirstRange = FirstStr->getSourceRange();
10728 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010729 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010730 FirstRange = FirstSA->getSourceRange();
10731 }
10732 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010733 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010734 SecondRange = SecondStr->getSourceRange();
10735 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010736 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010737 SecondRange = SecondSA->getSourceRange();
10738 }
10739 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10740 << (FirstStr == nullptr);
10741 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10742 << (SecondStr == nullptr);
10743 Diagnosed = true;
10744 break;
10745 }
10746
10747 if (FirstStr && SecondStr &&
10748 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010749 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010750 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010751 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010752 StaticAssertMessage);
10753 Diagnosed = true;
10754 break;
10755 }
10756 break;
10757 }
Richard Trieud0786092017-02-23 00:23:01 +000010758 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010759 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10760 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010761 IdentifierInfo *FirstII = FirstField->getIdentifier();
10762 IdentifierInfo *SecondII = SecondField->getIdentifier();
10763 if (FirstII->getName() != SecondII->getName()) {
10764 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10765 FieldName)
10766 << FirstII;
10767 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10768 FieldName)
10769 << SecondII;
10770
10771 Diagnosed = true;
10772 break;
10773 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010774
Richard Smithdbafb6c2017-06-29 23:23:46 +000010775 assert(getContext().hasSameType(FirstField->getType(),
10776 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010777
10778 QualType FirstType = FirstField->getType();
10779 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010780 if (ComputeQualTypeODRHash(FirstType) !=
10781 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010782 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10783 FieldTypeName)
10784 << FirstII << FirstType;
10785 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10786 FieldTypeName)
10787 << SecondII << SecondType;
10788
10789 Diagnosed = true;
10790 break;
10791 }
10792
Richard Trieu93772fc2017-02-24 20:59:28 +000010793 const bool IsFirstBitField = FirstField->isBitField();
10794 const bool IsSecondBitField = SecondField->isBitField();
10795 if (IsFirstBitField != IsSecondBitField) {
10796 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10797 FieldSingleBitField)
10798 << FirstII << IsFirstBitField;
10799 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10800 FieldSingleBitField)
10801 << SecondII << IsSecondBitField;
10802 Diagnosed = true;
10803 break;
10804 }
10805
10806 if (IsFirstBitField && IsSecondBitField) {
10807 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10808 FieldDifferentWidthBitField)
10809 << FirstII << FirstField->getBitWidth()->getSourceRange();
10810 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10811 FieldDifferentWidthBitField)
10812 << SecondII << SecondField->getBitWidth()->getSourceRange();
10813 Diagnosed = true;
10814 break;
10815 }
10816
Richard Trieu8d543e22017-02-24 23:35:37 +000010817 const bool IsFirstMutable = FirstField->isMutable();
10818 const bool IsSecondMutable = SecondField->isMutable();
10819 if (IsFirstMutable != IsSecondMutable) {
10820 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10821 FieldSingleMutable)
10822 << FirstII << IsFirstMutable;
10823 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10824 FieldSingleMutable)
10825 << SecondII << IsSecondMutable;
10826 Diagnosed = true;
10827 break;
10828 }
10829
10830 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10831 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10832 if ((!FirstInitializer && SecondInitializer) ||
10833 (FirstInitializer && !SecondInitializer)) {
10834 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10835 FieldSingleInitializer)
10836 << FirstII << (FirstInitializer != nullptr);
10837 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10838 FieldSingleInitializer)
10839 << SecondII << (SecondInitializer != nullptr);
10840 Diagnosed = true;
10841 break;
10842 }
10843
10844 if (FirstInitializer && SecondInitializer) {
10845 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10846 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10847 if (FirstInitHash != SecondInitHash) {
10848 ODRDiagError(FirstField->getLocation(),
10849 FirstField->getSourceRange(),
10850 FieldDifferentInitializers)
10851 << FirstII << FirstInitializer->getSourceRange();
10852 ODRDiagNote(SecondField->getLocation(),
10853 SecondField->getSourceRange(),
10854 FieldDifferentInitializers)
10855 << SecondII << SecondInitializer->getSourceRange();
10856 Diagnosed = true;
10857 break;
10858 }
10859 }
10860
Richard Trieud0786092017-02-23 00:23:01 +000010861 break;
10862 }
Richard Trieu48143742017-02-28 21:24:38 +000010863 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010864 enum {
10865 DiagMethod,
10866 DiagConstructor,
10867 DiagDestructor,
10868 } FirstMethodType,
10869 SecondMethodType;
10870 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10871 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10872 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10873 return DiagMethod;
10874 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010875 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10876 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010877 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10878 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010879 auto FirstName = FirstMethod->getDeclName();
10880 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010881 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010882 ODRDiagError(FirstMethod->getLocation(),
10883 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010884 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010885 ODRDiagNote(SecondMethod->getLocation(),
10886 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010887 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010888
10889 Diagnosed = true;
10890 break;
10891 }
10892
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010893 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10894 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010895 if (FirstDeleted != SecondDeleted) {
10896 ODRDiagError(FirstMethod->getLocation(),
10897 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010898 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010899
10900 ODRDiagNote(SecondMethod->getLocation(),
10901 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010902 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010903 Diagnosed = true;
10904 break;
10905 }
10906
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010907 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10908 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10909 if (FirstDefaulted != SecondDefaulted) {
10910 ODRDiagError(FirstMethod->getLocation(),
10911 FirstMethod->getSourceRange(), MethodDefaulted)
10912 << FirstMethodType << FirstName << FirstDefaulted;
10913
10914 ODRDiagNote(SecondMethod->getLocation(),
10915 SecondMethod->getSourceRange(), MethodDefaulted)
10916 << SecondMethodType << SecondName << SecondDefaulted;
10917 Diagnosed = true;
10918 break;
10919 }
10920
Richard Trieu583e2c12017-03-04 00:08:58 +000010921 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10922 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10923 const bool FirstPure = FirstMethod->isPure();
10924 const bool SecondPure = SecondMethod->isPure();
10925 if ((FirstVirtual || SecondVirtual) &&
10926 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10927 ODRDiagError(FirstMethod->getLocation(),
10928 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010929 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010930 ODRDiagNote(SecondMethod->getLocation(),
10931 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010932 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010933 Diagnosed = true;
10934 break;
10935 }
10936
10937 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10938 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10939 // class needs to be checked instead.
10940 const auto FirstStorage = FirstMethod->getStorageClass();
10941 const auto SecondStorage = SecondMethod->getStorageClass();
10942 const bool FirstStatic = FirstStorage == SC_Static;
10943 const bool SecondStatic = SecondStorage == SC_Static;
10944 if (FirstStatic != SecondStatic) {
10945 ODRDiagError(FirstMethod->getLocation(),
10946 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010947 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010948 ODRDiagNote(SecondMethod->getLocation(),
10949 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010950 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010951 Diagnosed = true;
10952 break;
10953 }
10954
10955 const bool FirstVolatile = FirstMethod->isVolatile();
10956 const bool SecondVolatile = SecondMethod->isVolatile();
10957 if (FirstVolatile != SecondVolatile) {
10958 ODRDiagError(FirstMethod->getLocation(),
10959 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010960 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010961 ODRDiagNote(SecondMethod->getLocation(),
10962 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010963 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010964 Diagnosed = true;
10965 break;
10966 }
10967
10968 const bool FirstConst = FirstMethod->isConst();
10969 const bool SecondConst = SecondMethod->isConst();
10970 if (FirstConst != SecondConst) {
10971 ODRDiagError(FirstMethod->getLocation(),
10972 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010973 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010974 ODRDiagNote(SecondMethod->getLocation(),
10975 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010976 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010977 Diagnosed = true;
10978 break;
10979 }
10980
10981 const bool FirstInline = FirstMethod->isInlineSpecified();
10982 const bool SecondInline = SecondMethod->isInlineSpecified();
10983 if (FirstInline != SecondInline) {
10984 ODRDiagError(FirstMethod->getLocation(),
10985 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010986 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010987 ODRDiagNote(SecondMethod->getLocation(),
10988 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010989 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010990 Diagnosed = true;
10991 break;
10992 }
10993
Richard Trieu02552272017-05-02 23:58:52 +000010994 const unsigned FirstNumParameters = FirstMethod->param_size();
10995 const unsigned SecondNumParameters = SecondMethod->param_size();
10996 if (FirstNumParameters != SecondNumParameters) {
10997 ODRDiagError(FirstMethod->getLocation(),
10998 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010999 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011000 ODRDiagNote(SecondMethod->getLocation(),
11001 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011002 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011003 Diagnosed = true;
11004 break;
11005 }
11006
11007 // Need this status boolean to know when break out of the switch.
11008 bool ParameterMismatch = false;
11009 for (unsigned I = 0; I < FirstNumParameters; ++I) {
11010 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
11011 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
11012
11013 QualType FirstParamType = FirstParam->getType();
11014 QualType SecondParamType = SecondParam->getType();
11015 if (FirstParamType != SecondParamType &&
11016 ComputeQualTypeODRHash(FirstParamType) !=
11017 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011018 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011019 FirstParamType->getAs<DecayedType>()) {
11020 ODRDiagError(FirstMethod->getLocation(),
11021 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011022 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11023 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000011024 } else {
11025 ODRDiagError(FirstMethod->getLocation(),
11026 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011027 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11028 << false;
Richard Trieu02552272017-05-02 23:58:52 +000011029 }
11030
Vedant Kumar48b4f762018-04-14 01:40:48 +000011031 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011032 SecondParamType->getAs<DecayedType>()) {
11033 ODRDiagNote(SecondMethod->getLocation(),
11034 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011035 << SecondMethodType << SecondName << (I + 1)
11036 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000011037 << ParamDecayedType->getOriginalType();
11038 } else {
11039 ODRDiagNote(SecondMethod->getLocation(),
11040 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011041 << SecondMethodType << SecondName << (I + 1)
11042 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000011043 }
11044 ParameterMismatch = true;
11045 break;
11046 }
11047
11048 DeclarationName FirstParamName = FirstParam->getDeclName();
11049 DeclarationName SecondParamName = SecondParam->getDeclName();
11050 if (FirstParamName != SecondParamName) {
11051 ODRDiagError(FirstMethod->getLocation(),
11052 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011053 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011054 ODRDiagNote(SecondMethod->getLocation(),
11055 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011056 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011057 ParameterMismatch = true;
11058 break;
11059 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011060
11061 const Expr *FirstInit = FirstParam->getInit();
11062 const Expr *SecondInit = SecondParam->getInit();
11063 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11064 ODRDiagError(FirstMethod->getLocation(),
11065 FirstMethod->getSourceRange(),
11066 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011067 << FirstMethodType << FirstName << (I + 1)
11068 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011069 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11070 ODRDiagNote(SecondMethod->getLocation(),
11071 SecondMethod->getSourceRange(),
11072 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011073 << SecondMethodType << SecondName << (I + 1)
11074 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011075 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11076 ParameterMismatch = true;
11077 break;
11078 }
11079
11080 if (FirstInit && SecondInit &&
11081 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11082 ODRDiagError(FirstMethod->getLocation(),
11083 FirstMethod->getSourceRange(),
11084 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011085 << FirstMethodType << FirstName << (I + 1)
11086 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011087 ODRDiagNote(SecondMethod->getLocation(),
11088 SecondMethod->getSourceRange(),
11089 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011090 << SecondMethodType << SecondName << (I + 1)
11091 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011092 ParameterMismatch = true;
11093 break;
11094
11095 }
Richard Trieu02552272017-05-02 23:58:52 +000011096 }
11097
11098 if (ParameterMismatch) {
11099 Diagnosed = true;
11100 break;
11101 }
11102
Richard Trieu7282d322018-04-25 00:31:15 +000011103 const auto *FirstTemplateArgs =
11104 FirstMethod->getTemplateSpecializationArgs();
11105 const auto *SecondTemplateArgs =
11106 SecondMethod->getTemplateSpecializationArgs();
11107
11108 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
11109 (!FirstTemplateArgs && SecondTemplateArgs)) {
11110 ODRDiagError(FirstMethod->getLocation(),
11111 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
11112 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
11113 ODRDiagNote(SecondMethod->getLocation(),
11114 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
11115 << SecondMethodType << SecondName
11116 << (SecondTemplateArgs != nullptr);
11117
11118 Diagnosed = true;
11119 break;
11120 }
11121
11122 if (FirstTemplateArgs && SecondTemplateArgs) {
11123 // Remove pack expansions from argument list.
11124 auto ExpandTemplateArgumentList =
11125 [](const TemplateArgumentList *TAL) {
11126 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
11127 for (const TemplateArgument &TA : TAL->asArray()) {
11128 if (TA.getKind() != TemplateArgument::Pack) {
11129 ExpandedList.push_back(&TA);
11130 continue;
11131 }
11132 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
11133 ExpandedList.push_back(&PackTA);
11134 }
11135 }
11136 return ExpandedList;
11137 };
11138 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
11139 ExpandTemplateArgumentList(FirstTemplateArgs);
11140 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
11141 ExpandTemplateArgumentList(SecondTemplateArgs);
11142
11143 if (FirstExpandedList.size() != SecondExpandedList.size()) {
11144 ODRDiagError(FirstMethod->getLocation(),
11145 FirstMethod->getSourceRange(),
11146 MethodDifferentNumberTemplateArguments)
11147 << FirstMethodType << FirstName
11148 << (unsigned)FirstExpandedList.size();
11149 ODRDiagNote(SecondMethod->getLocation(),
11150 SecondMethod->getSourceRange(),
11151 MethodDifferentNumberTemplateArguments)
11152 << SecondMethodType << SecondName
11153 << (unsigned)SecondExpandedList.size();
11154
11155 Diagnosed = true;
11156 break;
11157 }
11158
11159 bool TemplateArgumentMismatch = false;
11160 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
11161 const TemplateArgument &FirstTA = *FirstExpandedList[i],
11162 &SecondTA = *SecondExpandedList[i];
11163 if (ComputeTemplateArgumentODRHash(FirstTA) ==
11164 ComputeTemplateArgumentODRHash(SecondTA)) {
11165 continue;
11166 }
11167
11168 ODRDiagError(FirstMethod->getLocation(),
11169 FirstMethod->getSourceRange(),
11170 MethodDifferentTemplateArgument)
11171 << FirstMethodType << FirstName << FirstTA << i + 1;
11172 ODRDiagNote(SecondMethod->getLocation(),
11173 SecondMethod->getSourceRange(),
11174 MethodDifferentTemplateArgument)
11175 << SecondMethodType << SecondName << SecondTA << i + 1;
11176
11177 TemplateArgumentMismatch = true;
11178 break;
11179 }
11180
11181 if (TemplateArgumentMismatch) {
11182 Diagnosed = true;
11183 break;
11184 }
11185 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000011186
11187 // Compute the hash of the method as if it has no body.
11188 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
11189 Hash.clear();
11190 Hash.AddFunctionDecl(D, true /*SkipBody*/);
11191 return Hash.CalculateHash();
11192 };
11193
11194 // Compare the hash generated to the hash stored. A difference means
11195 // that a body was present in the original source. Due to merging,
11196 // the stardard way of detecting a body will not work.
11197 const bool HasFirstBody =
11198 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
11199 const bool HasSecondBody =
11200 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
11201
11202 if (HasFirstBody != HasSecondBody) {
11203 ODRDiagError(FirstMethod->getLocation(),
11204 FirstMethod->getSourceRange(), MethodSingleBody)
11205 << FirstMethodType << FirstName << HasFirstBody;
11206 ODRDiagNote(SecondMethod->getLocation(),
11207 SecondMethod->getSourceRange(), MethodSingleBody)
11208 << SecondMethodType << SecondName << HasSecondBody;
11209 Diagnosed = true;
11210 break;
11211 }
11212
11213 if (HasFirstBody && HasSecondBody) {
11214 ODRDiagError(FirstMethod->getLocation(),
11215 FirstMethod->getSourceRange(), MethodDifferentBody)
11216 << FirstMethodType << FirstName;
11217 ODRDiagNote(SecondMethod->getLocation(),
11218 SecondMethod->getSourceRange(), MethodDifferentBody)
11219 << SecondMethodType << SecondName;
11220 Diagnosed = true;
11221 break;
11222 }
11223
Richard Trieu48143742017-02-28 21:24:38 +000011224 break;
11225 }
Richard Trieu11d566a2017-06-12 21:58:22 +000011226 case TypeAlias:
11227 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011228 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
11229 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000011230 auto FirstName = FirstTD->getDeclName();
11231 auto SecondName = SecondTD->getDeclName();
11232 if (FirstName != SecondName) {
11233 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11234 TypedefName)
11235 << (FirstDiffType == TypeAlias) << FirstName;
11236 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11237 TypedefName)
11238 << (FirstDiffType == TypeAlias) << SecondName;
11239 Diagnosed = true;
11240 break;
11241 }
11242
11243 QualType FirstType = FirstTD->getUnderlyingType();
11244 QualType SecondType = SecondTD->getUnderlyingType();
11245 if (ComputeQualTypeODRHash(FirstType) !=
11246 ComputeQualTypeODRHash(SecondType)) {
11247 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11248 TypedefType)
11249 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
11250 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11251 TypedefType)
11252 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
11253 Diagnosed = true;
11254 break;
11255 }
11256 break;
11257 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011258 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011259 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
11260 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000011261 auto FirstName = FirstVD->getDeclName();
11262 auto SecondName = SecondVD->getDeclName();
11263 if (FirstName != SecondName) {
11264 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11265 VarName)
11266 << FirstName;
11267 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11268 VarName)
11269 << SecondName;
11270 Diagnosed = true;
11271 break;
11272 }
11273
11274 QualType FirstType = FirstVD->getType();
11275 QualType SecondType = SecondVD->getType();
11276 if (ComputeQualTypeODRHash(FirstType) !=
11277 ComputeQualTypeODRHash(SecondType)) {
11278 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11279 VarType)
11280 << FirstName << FirstType;
11281 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11282 VarType)
11283 << SecondName << SecondType;
11284 Diagnosed = true;
11285 break;
11286 }
11287
11288 const Expr *FirstInit = FirstVD->getInit();
11289 const Expr *SecondInit = SecondVD->getInit();
11290 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11291 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11292 VarSingleInitializer)
11293 << FirstName << (FirstInit == nullptr)
11294 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
11295 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11296 VarSingleInitializer)
11297 << SecondName << (SecondInit == nullptr)
11298 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11299 Diagnosed = true;
11300 break;
11301 }
11302
11303 if (FirstInit && SecondInit &&
11304 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11305 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11306 VarDifferentInitializer)
11307 << FirstName << FirstInit->getSourceRange();
11308 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11309 VarDifferentInitializer)
11310 << SecondName << SecondInit->getSourceRange();
11311 Diagnosed = true;
11312 break;
11313 }
11314
11315 const bool FirstIsConstexpr = FirstVD->isConstexpr();
11316 const bool SecondIsConstexpr = SecondVD->isConstexpr();
11317 if (FirstIsConstexpr != SecondIsConstexpr) {
11318 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11319 VarConstexpr)
11320 << FirstName << FirstIsConstexpr;
11321 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11322 VarConstexpr)
11323 << SecondName << SecondIsConstexpr;
11324 Diagnosed = true;
11325 break;
11326 }
11327 break;
11328 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000011329 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011330 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
11331 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000011332
11333 NamedDecl *FirstND = FirstFriend->getFriendDecl();
11334 NamedDecl *SecondND = SecondFriend->getFriendDecl();
11335
11336 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
11337 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
11338
11339 if (FirstND && SecondND) {
11340 ODRDiagError(FirstFriend->getFriendLoc(),
11341 FirstFriend->getSourceRange(), FriendFunction)
11342 << FirstND;
11343 ODRDiagNote(SecondFriend->getFriendLoc(),
11344 SecondFriend->getSourceRange(), FriendFunction)
11345 << SecondND;
11346
11347 Diagnosed = true;
11348 break;
11349 }
11350
11351 if (FirstTSI && SecondTSI) {
11352 QualType FirstFriendType = FirstTSI->getType();
11353 QualType SecondFriendType = SecondTSI->getType();
11354 assert(ComputeQualTypeODRHash(FirstFriendType) !=
11355 ComputeQualTypeODRHash(SecondFriendType));
11356 ODRDiagError(FirstFriend->getFriendLoc(),
11357 FirstFriend->getSourceRange(), FriendType)
11358 << FirstFriendType;
11359 ODRDiagNote(SecondFriend->getFriendLoc(),
11360 SecondFriend->getSourceRange(), FriendType)
11361 << SecondFriendType;
11362 Diagnosed = true;
11363 break;
11364 }
11365
11366 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
11367 FriendTypeFunction)
11368 << (FirstTSI == nullptr);
11369 ODRDiagNote(SecondFriend->getFriendLoc(),
11370 SecondFriend->getSourceRange(), FriendTypeFunction)
11371 << (SecondTSI == nullptr);
11372
11373 Diagnosed = true;
11374 break;
11375 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000011376 case FunctionTemplate: {
11377 FunctionTemplateDecl *FirstTemplate =
11378 cast<FunctionTemplateDecl>(FirstDecl);
11379 FunctionTemplateDecl *SecondTemplate =
11380 cast<FunctionTemplateDecl>(SecondDecl);
11381
11382 TemplateParameterList *FirstTPL =
11383 FirstTemplate->getTemplateParameters();
11384 TemplateParameterList *SecondTPL =
11385 SecondTemplate->getTemplateParameters();
11386
11387 if (FirstTPL->size() != SecondTPL->size()) {
11388 ODRDiagError(FirstTemplate->getLocation(),
11389 FirstTemplate->getSourceRange(),
11390 FunctionTemplateDifferentNumberParameters)
11391 << FirstTemplate << FirstTPL->size();
11392 ODRDiagNote(SecondTemplate->getLocation(),
11393 SecondTemplate->getSourceRange(),
11394 FunctionTemplateDifferentNumberParameters)
11395 << SecondTemplate << SecondTPL->size();
11396
11397 Diagnosed = true;
11398 break;
11399 }
11400
11401 bool ParameterMismatch = false;
11402 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
11403 NamedDecl *FirstParam = FirstTPL->getParam(i);
11404 NamedDecl *SecondParam = SecondTPL->getParam(i);
11405
11406 if (FirstParam->getKind() != SecondParam->getKind()) {
11407 enum {
11408 TemplateTypeParameter,
11409 NonTypeTemplateParameter,
11410 TemplateTemplateParameter,
11411 };
11412 auto GetParamType = [](NamedDecl *D) {
11413 switch (D->getKind()) {
11414 default:
11415 llvm_unreachable("Unexpected template parameter type");
11416 case Decl::TemplateTypeParm:
11417 return TemplateTypeParameter;
11418 case Decl::NonTypeTemplateParm:
11419 return NonTypeTemplateParameter;
11420 case Decl::TemplateTemplateParm:
11421 return TemplateTemplateParameter;
11422 }
11423 };
11424
11425 ODRDiagError(FirstTemplate->getLocation(),
11426 FirstTemplate->getSourceRange(),
11427 FunctionTemplateParameterDifferentKind)
11428 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11429 ODRDiagNote(SecondTemplate->getLocation(),
11430 SecondTemplate->getSourceRange(),
11431 FunctionTemplateParameterDifferentKind)
11432 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11433
11434 ParameterMismatch = true;
11435 break;
11436 }
11437
11438 if (FirstParam->getName() != SecondParam->getName()) {
11439 ODRDiagError(FirstTemplate->getLocation(),
11440 FirstTemplate->getSourceRange(),
11441 FunctionTemplateParameterName)
11442 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11443 << FirstParam;
11444 ODRDiagNote(SecondTemplate->getLocation(),
11445 SecondTemplate->getSourceRange(),
11446 FunctionTemplateParameterName)
11447 << SecondTemplate << (i + 1)
11448 << (bool)SecondParam->getIdentifier() << SecondParam;
11449 ParameterMismatch = true;
11450 break;
11451 }
11452
11453 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11454 isa<TemplateTypeParmDecl>(SecondParam)) {
11455 TemplateTypeParmDecl *FirstTTPD =
11456 cast<TemplateTypeParmDecl>(FirstParam);
11457 TemplateTypeParmDecl *SecondTTPD =
11458 cast<TemplateTypeParmDecl>(SecondParam);
11459 bool HasFirstDefaultArgument =
11460 FirstTTPD->hasDefaultArgument() &&
11461 !FirstTTPD->defaultArgumentWasInherited();
11462 bool HasSecondDefaultArgument =
11463 SecondTTPD->hasDefaultArgument() &&
11464 !SecondTTPD->defaultArgumentWasInherited();
11465 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11466 ODRDiagError(FirstTemplate->getLocation(),
11467 FirstTemplate->getSourceRange(),
11468 FunctionTemplateParameterSingleDefaultArgument)
11469 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11470 ODRDiagNote(SecondTemplate->getLocation(),
11471 SecondTemplate->getSourceRange(),
11472 FunctionTemplateParameterSingleDefaultArgument)
11473 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11474 ParameterMismatch = true;
11475 break;
11476 }
11477
11478 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11479 QualType FirstType = FirstTTPD->getDefaultArgument();
11480 QualType SecondType = SecondTTPD->getDefaultArgument();
11481 if (ComputeQualTypeODRHash(FirstType) !=
11482 ComputeQualTypeODRHash(SecondType)) {
11483 ODRDiagError(FirstTemplate->getLocation(),
11484 FirstTemplate->getSourceRange(),
11485 FunctionTemplateParameterDifferentDefaultArgument)
11486 << FirstTemplate << (i + 1) << FirstType;
11487 ODRDiagNote(SecondTemplate->getLocation(),
11488 SecondTemplate->getSourceRange(),
11489 FunctionTemplateParameterDifferentDefaultArgument)
11490 << SecondTemplate << (i + 1) << SecondType;
11491 ParameterMismatch = true;
11492 break;
11493 }
11494 }
11495
11496 if (FirstTTPD->isParameterPack() !=
11497 SecondTTPD->isParameterPack()) {
11498 ODRDiagError(FirstTemplate->getLocation(),
11499 FirstTemplate->getSourceRange(),
11500 FunctionTemplatePackParameter)
11501 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11502 ODRDiagNote(SecondTemplate->getLocation(),
11503 SecondTemplate->getSourceRange(),
11504 FunctionTemplatePackParameter)
11505 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11506 ParameterMismatch = true;
11507 break;
11508 }
11509 }
11510
11511 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11512 isa<TemplateTemplateParmDecl>(SecondParam)) {
11513 TemplateTemplateParmDecl *FirstTTPD =
11514 cast<TemplateTemplateParmDecl>(FirstParam);
11515 TemplateTemplateParmDecl *SecondTTPD =
11516 cast<TemplateTemplateParmDecl>(SecondParam);
11517
11518 TemplateParameterList *FirstTPL =
11519 FirstTTPD->getTemplateParameters();
11520 TemplateParameterList *SecondTPL =
11521 SecondTTPD->getTemplateParameters();
11522
11523 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11524 ComputeTemplateParameterListODRHash(SecondTPL)) {
11525 ODRDiagError(FirstTemplate->getLocation(),
11526 FirstTemplate->getSourceRange(),
11527 FunctionTemplateParameterDifferentType)
11528 << FirstTemplate << (i + 1);
11529 ODRDiagNote(SecondTemplate->getLocation(),
11530 SecondTemplate->getSourceRange(),
11531 FunctionTemplateParameterDifferentType)
11532 << SecondTemplate << (i + 1);
11533 ParameterMismatch = true;
11534 break;
11535 }
11536
11537 bool HasFirstDefaultArgument =
11538 FirstTTPD->hasDefaultArgument() &&
11539 !FirstTTPD->defaultArgumentWasInherited();
11540 bool HasSecondDefaultArgument =
11541 SecondTTPD->hasDefaultArgument() &&
11542 !SecondTTPD->defaultArgumentWasInherited();
11543 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11544 ODRDiagError(FirstTemplate->getLocation(),
11545 FirstTemplate->getSourceRange(),
11546 FunctionTemplateParameterSingleDefaultArgument)
11547 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11548 ODRDiagNote(SecondTemplate->getLocation(),
11549 SecondTemplate->getSourceRange(),
11550 FunctionTemplateParameterSingleDefaultArgument)
11551 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11552 ParameterMismatch = true;
11553 break;
11554 }
11555
11556 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11557 TemplateArgument FirstTA =
11558 FirstTTPD->getDefaultArgument().getArgument();
11559 TemplateArgument SecondTA =
11560 SecondTTPD->getDefaultArgument().getArgument();
11561 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11562 ComputeTemplateArgumentODRHash(SecondTA)) {
11563 ODRDiagError(FirstTemplate->getLocation(),
11564 FirstTemplate->getSourceRange(),
11565 FunctionTemplateParameterDifferentDefaultArgument)
11566 << FirstTemplate << (i + 1) << FirstTA;
11567 ODRDiagNote(SecondTemplate->getLocation(),
11568 SecondTemplate->getSourceRange(),
11569 FunctionTemplateParameterDifferentDefaultArgument)
11570 << SecondTemplate << (i + 1) << SecondTA;
11571 ParameterMismatch = true;
11572 break;
11573 }
11574 }
11575
11576 if (FirstTTPD->isParameterPack() !=
11577 SecondTTPD->isParameterPack()) {
11578 ODRDiagError(FirstTemplate->getLocation(),
11579 FirstTemplate->getSourceRange(),
11580 FunctionTemplatePackParameter)
11581 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11582 ODRDiagNote(SecondTemplate->getLocation(),
11583 SecondTemplate->getSourceRange(),
11584 FunctionTemplatePackParameter)
11585 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11586 ParameterMismatch = true;
11587 break;
11588 }
11589 }
11590
11591 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11592 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11593 NonTypeTemplateParmDecl *FirstNTTPD =
11594 cast<NonTypeTemplateParmDecl>(FirstParam);
11595 NonTypeTemplateParmDecl *SecondNTTPD =
11596 cast<NonTypeTemplateParmDecl>(SecondParam);
11597
11598 QualType FirstType = FirstNTTPD->getType();
11599 QualType SecondType = SecondNTTPD->getType();
11600 if (ComputeQualTypeODRHash(FirstType) !=
11601 ComputeQualTypeODRHash(SecondType)) {
11602 ODRDiagError(FirstTemplate->getLocation(),
11603 FirstTemplate->getSourceRange(),
11604 FunctionTemplateParameterDifferentType)
11605 << FirstTemplate << (i + 1);
11606 ODRDiagNote(SecondTemplate->getLocation(),
11607 SecondTemplate->getSourceRange(),
11608 FunctionTemplateParameterDifferentType)
11609 << SecondTemplate << (i + 1);
11610 ParameterMismatch = true;
11611 break;
11612 }
11613
11614 bool HasFirstDefaultArgument =
11615 FirstNTTPD->hasDefaultArgument() &&
11616 !FirstNTTPD->defaultArgumentWasInherited();
11617 bool HasSecondDefaultArgument =
11618 SecondNTTPD->hasDefaultArgument() &&
11619 !SecondNTTPD->defaultArgumentWasInherited();
11620 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11621 ODRDiagError(FirstTemplate->getLocation(),
11622 FirstTemplate->getSourceRange(),
11623 FunctionTemplateParameterSingleDefaultArgument)
11624 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11625 ODRDiagNote(SecondTemplate->getLocation(),
11626 SecondTemplate->getSourceRange(),
11627 FunctionTemplateParameterSingleDefaultArgument)
11628 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11629 ParameterMismatch = true;
11630 break;
11631 }
11632
11633 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11634 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11635 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11636 if (ComputeODRHash(FirstDefaultArgument) !=
11637 ComputeODRHash(SecondDefaultArgument)) {
11638 ODRDiagError(FirstTemplate->getLocation(),
11639 FirstTemplate->getSourceRange(),
11640 FunctionTemplateParameterDifferentDefaultArgument)
11641 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11642 ODRDiagNote(SecondTemplate->getLocation(),
11643 SecondTemplate->getSourceRange(),
11644 FunctionTemplateParameterDifferentDefaultArgument)
11645 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11646 ParameterMismatch = true;
11647 break;
11648 }
11649 }
11650
11651 if (FirstNTTPD->isParameterPack() !=
11652 SecondNTTPD->isParameterPack()) {
11653 ODRDiagError(FirstTemplate->getLocation(),
11654 FirstTemplate->getSourceRange(),
11655 FunctionTemplatePackParameter)
11656 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11657 ODRDiagNote(SecondTemplate->getLocation(),
11658 SecondTemplate->getSourceRange(),
11659 FunctionTemplatePackParameter)
11660 << SecondTemplate << (i + 1)
11661 << SecondNTTPD->isParameterPack();
11662 ParameterMismatch = true;
11663 break;
11664 }
11665 }
11666 }
11667
11668 if (ParameterMismatch) {
11669 Diagnosed = true;
11670 break;
11671 }
11672
11673 break;
11674 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011675 }
11676
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011677 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011678 continue;
11679
Richard Trieu708859a2017-06-08 00:56:21 +000011680 Diag(FirstDecl->getLocation(),
11681 diag::err_module_odr_violation_mismatch_decl_unknown)
11682 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11683 << FirstDecl->getSourceRange();
11684 Diag(SecondDecl->getLocation(),
11685 diag::note_module_odr_violation_mismatch_decl_unknown)
11686 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011687 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011688 }
11689
11690 if (!Diagnosed) {
11691 // All definitions are updates to the same declaration. This happens if a
11692 // module instantiates the declaration of a class template specialization
11693 // and two or more other modules instantiate its definition.
11694 //
11695 // FIXME: Indicate which modules had instantiations of this definition.
11696 // FIXME: How can this even happen?
11697 Diag(Merge.first->getLocation(),
11698 diag::err_module_odr_violation_different_instantiations)
11699 << Merge.first;
11700 }
11701 }
Richard Trieue6caa262017-12-23 00:41:01 +000011702
11703 // Issue ODR failures diagnostics for functions.
11704 for (auto &Merge : FunctionOdrMergeFailures) {
11705 enum ODRFunctionDifference {
11706 ReturnType,
11707 ParameterName,
11708 ParameterType,
11709 ParameterSingleDefaultArgument,
11710 ParameterDifferentDefaultArgument,
11711 FunctionBody,
11712 };
11713
11714 FunctionDecl *FirstFunction = Merge.first;
11715 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11716
11717 bool Diagnosed = false;
11718 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011719
Richard Trieue6caa262017-12-23 00:41:01 +000011720 if (FirstFunction == SecondFunction)
11721 continue;
11722
11723 std::string SecondModule =
11724 getOwningModuleNameForDiagnostic(SecondFunction);
11725
11726 auto ODRDiagError = [FirstFunction, &FirstModule,
11727 this](SourceLocation Loc, SourceRange Range,
11728 ODRFunctionDifference DiffType) {
11729 return Diag(Loc, diag::err_module_odr_violation_function)
11730 << FirstFunction << FirstModule.empty() << FirstModule << Range
11731 << DiffType;
11732 };
11733 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11734 SourceRange Range,
11735 ODRFunctionDifference DiffType) {
11736 return Diag(Loc, diag::note_module_odr_violation_function)
11737 << SecondModule << Range << DiffType;
11738 };
11739
11740 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11741 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11742 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11743 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11744 << FirstFunction->getReturnType();
11745 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11746 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11747 << SecondFunction->getReturnType();
11748 Diagnosed = true;
11749 break;
11750 }
11751
11752 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11753 "Merged functions with different number of parameters");
11754
11755 auto ParamSize = FirstFunction->param_size();
11756 bool ParameterMismatch = false;
11757 for (unsigned I = 0; I < ParamSize; ++I) {
11758 auto *FirstParam = FirstFunction->getParamDecl(I);
11759 auto *SecondParam = SecondFunction->getParamDecl(I);
11760
11761 assert(getContext().hasSameType(FirstParam->getType(),
11762 SecondParam->getType()) &&
11763 "Merged function has different parameter types.");
11764
11765 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11766 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11767 ParameterName)
11768 << I + 1 << FirstParam->getDeclName();
11769 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11770 ParameterName)
11771 << I + 1 << SecondParam->getDeclName();
11772 ParameterMismatch = true;
11773 break;
11774 };
11775
11776 QualType FirstParamType = FirstParam->getType();
11777 QualType SecondParamType = SecondParam->getType();
11778 if (FirstParamType != SecondParamType &&
11779 ComputeQualTypeODRHash(FirstParamType) !=
11780 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011781 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011782 FirstParamType->getAs<DecayedType>()) {
11783 ODRDiagError(FirstParam->getLocation(),
11784 FirstParam->getSourceRange(), ParameterType)
11785 << (I + 1) << FirstParamType << true
11786 << ParamDecayedType->getOriginalType();
11787 } else {
11788 ODRDiagError(FirstParam->getLocation(),
11789 FirstParam->getSourceRange(), ParameterType)
11790 << (I + 1) << FirstParamType << false;
11791 }
11792
Vedant Kumar48b4f762018-04-14 01:40:48 +000011793 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011794 SecondParamType->getAs<DecayedType>()) {
11795 ODRDiagNote(SecondParam->getLocation(),
11796 SecondParam->getSourceRange(), ParameterType)
11797 << (I + 1) << SecondParamType << true
11798 << ParamDecayedType->getOriginalType();
11799 } else {
11800 ODRDiagNote(SecondParam->getLocation(),
11801 SecondParam->getSourceRange(), ParameterType)
11802 << (I + 1) << SecondParamType << false;
11803 }
11804 ParameterMismatch = true;
11805 break;
11806 }
11807
11808 const Expr *FirstInit = FirstParam->getInit();
11809 const Expr *SecondInit = SecondParam->getInit();
11810 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11811 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11812 ParameterSingleDefaultArgument)
11813 << (I + 1) << (FirstInit == nullptr)
11814 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11815 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11816 ParameterSingleDefaultArgument)
11817 << (I + 1) << (SecondInit == nullptr)
11818 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11819 ParameterMismatch = true;
11820 break;
11821 }
11822
11823 if (FirstInit && SecondInit &&
11824 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11825 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11826 ParameterDifferentDefaultArgument)
11827 << (I + 1) << FirstInit->getSourceRange();
11828 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11829 ParameterDifferentDefaultArgument)
11830 << (I + 1) << SecondInit->getSourceRange();
11831 ParameterMismatch = true;
11832 break;
11833 }
11834
11835 assert(ComputeSubDeclODRHash(FirstParam) ==
11836 ComputeSubDeclODRHash(SecondParam) &&
11837 "Undiagnosed parameter difference.");
11838 }
11839
11840 if (ParameterMismatch) {
11841 Diagnosed = true;
11842 break;
11843 }
11844
11845 // If no error has been generated before now, assume the problem is in
11846 // the body and generate a message.
11847 ODRDiagError(FirstFunction->getLocation(),
11848 FirstFunction->getSourceRange(), FunctionBody);
11849 ODRDiagNote(SecondFunction->getLocation(),
11850 SecondFunction->getSourceRange(), FunctionBody);
11851 Diagnosed = true;
11852 break;
11853 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011854 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011855 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11856 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011857
11858 // Issue ODR failures diagnostics for enums.
11859 for (auto &Merge : EnumOdrMergeFailures) {
11860 enum ODREnumDifference {
11861 SingleScopedEnum,
11862 EnumTagKeywordMismatch,
11863 SingleSpecifiedType,
11864 DifferentSpecifiedTypes,
11865 DifferentNumberEnumConstants,
11866 EnumConstantName,
11867 EnumConstantSingleInitilizer,
11868 EnumConstantDifferentInitilizer,
11869 };
11870
11871 // If we've already pointed out a specific problem with this enum, don't
11872 // bother issuing a general "something's different" diagnostic.
11873 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11874 continue;
11875
11876 EnumDecl *FirstEnum = Merge.first;
11877 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11878
11879 using DeclHashes =
11880 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11881 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11882 DeclHashes &Hashes, EnumDecl *Enum) {
11883 for (auto *D : Enum->decls()) {
11884 // Due to decl merging, the first EnumDecl is the parent of
11885 // Decls in both records.
11886 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11887 continue;
11888 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11889 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11890 ComputeSubDeclODRHash(D));
11891 }
11892 };
11893 DeclHashes FirstHashes;
11894 PopulateHashes(FirstHashes, FirstEnum);
11895 bool Diagnosed = false;
11896 for (auto &SecondEnum : Merge.second) {
11897
11898 if (FirstEnum == SecondEnum)
11899 continue;
11900
11901 std::string SecondModule =
11902 getOwningModuleNameForDiagnostic(SecondEnum);
11903
11904 auto ODRDiagError = [FirstEnum, &FirstModule,
11905 this](SourceLocation Loc, SourceRange Range,
11906 ODREnumDifference DiffType) {
11907 return Diag(Loc, diag::err_module_odr_violation_enum)
11908 << FirstEnum << FirstModule.empty() << FirstModule << Range
11909 << DiffType;
11910 };
11911 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11912 SourceRange Range,
11913 ODREnumDifference DiffType) {
11914 return Diag(Loc, diag::note_module_odr_violation_enum)
11915 << SecondModule << Range << DiffType;
11916 };
11917
11918 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11919 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11920 SingleScopedEnum)
11921 << FirstEnum->isScoped();
11922 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11923 SingleScopedEnum)
11924 << SecondEnum->isScoped();
11925 Diagnosed = true;
11926 continue;
11927 }
11928
11929 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11930 if (FirstEnum->isScopedUsingClassTag() !=
11931 SecondEnum->isScopedUsingClassTag()) {
11932 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11933 EnumTagKeywordMismatch)
11934 << FirstEnum->isScopedUsingClassTag();
11935 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11936 EnumTagKeywordMismatch)
11937 << SecondEnum->isScopedUsingClassTag();
11938 Diagnosed = true;
11939 continue;
11940 }
11941 }
11942
11943 QualType FirstUnderlyingType =
11944 FirstEnum->getIntegerTypeSourceInfo()
11945 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11946 : QualType();
11947 QualType SecondUnderlyingType =
11948 SecondEnum->getIntegerTypeSourceInfo()
11949 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11950 : QualType();
11951 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11952 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11953 SingleSpecifiedType)
11954 << !FirstUnderlyingType.isNull();
11955 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11956 SingleSpecifiedType)
11957 << !SecondUnderlyingType.isNull();
11958 Diagnosed = true;
11959 continue;
11960 }
11961
11962 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11963 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11964 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11965 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11966 DifferentSpecifiedTypes)
11967 << FirstUnderlyingType;
11968 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11969 DifferentSpecifiedTypes)
11970 << SecondUnderlyingType;
11971 Diagnosed = true;
11972 continue;
11973 }
11974 }
11975
11976 DeclHashes SecondHashes;
11977 PopulateHashes(SecondHashes, SecondEnum);
11978
11979 if (FirstHashes.size() != SecondHashes.size()) {
11980 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11981 DifferentNumberEnumConstants)
11982 << (int)FirstHashes.size();
11983 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11984 DifferentNumberEnumConstants)
11985 << (int)SecondHashes.size();
11986 Diagnosed = true;
11987 continue;
11988 }
11989
11990 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11991 if (FirstHashes[I].second == SecondHashes[I].second)
11992 continue;
11993 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11994 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11995
11996 if (FirstEnumConstant->getDeclName() !=
11997 SecondEnumConstant->getDeclName()) {
11998
11999 ODRDiagError(FirstEnumConstant->getLocation(),
12000 FirstEnumConstant->getSourceRange(), EnumConstantName)
12001 << I + 1 << FirstEnumConstant;
12002 ODRDiagNote(SecondEnumConstant->getLocation(),
12003 SecondEnumConstant->getSourceRange(), EnumConstantName)
12004 << I + 1 << SecondEnumConstant;
12005 Diagnosed = true;
12006 break;
12007 }
12008
12009 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
12010 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
12011 if (!FirstInit && !SecondInit)
12012 continue;
12013
12014 if (!FirstInit || !SecondInit) {
12015 ODRDiagError(FirstEnumConstant->getLocation(),
12016 FirstEnumConstant->getSourceRange(),
12017 EnumConstantSingleInitilizer)
12018 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
12019 ODRDiagNote(SecondEnumConstant->getLocation(),
12020 SecondEnumConstant->getSourceRange(),
12021 EnumConstantSingleInitilizer)
12022 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
12023 Diagnosed = true;
12024 break;
12025 }
12026
12027 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
12028 ODRDiagError(FirstEnumConstant->getLocation(),
12029 FirstEnumConstant->getSourceRange(),
12030 EnumConstantDifferentInitilizer)
12031 << I + 1 << FirstEnumConstant;
12032 ODRDiagNote(SecondEnumConstant->getLocation(),
12033 SecondEnumConstant->getSourceRange(),
12034 EnumConstantDifferentInitilizer)
12035 << I + 1 << SecondEnumConstant;
12036 Diagnosed = true;
12037 break;
12038 }
12039 }
12040 }
12041
12042 (void)Diagnosed;
12043 assert(Diagnosed && "Unable to emit ODR diagnostic.");
12044 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012045}
12046
Richard Smithce18a182015-07-14 00:26:00 +000012047void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000012048 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000012049 ReadTimer->startTimer();
12050}
12051
Guy Benyei11169dd2012-12-18 14:30:41 +000012052void ASTReader::FinishedDeserializing() {
12053 assert(NumCurrentElementsDeserializing &&
12054 "FinishedDeserializing not paired with StartedDeserializing");
12055 if (NumCurrentElementsDeserializing == 1) {
12056 // We decrease NumCurrentElementsDeserializing only after pending actions
12057 // are finished, to avoid recursively re-calling finishPendingActions().
12058 finishPendingActions();
12059 }
12060 --NumCurrentElementsDeserializing;
12061
Richard Smitha0ce9c42014-07-29 23:23:27 +000012062 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000012063 // Propagate exception specification and deduced type updates along
12064 // redeclaration chains.
12065 //
12066 // We do this now rather than in finishPendingActions because we want to
12067 // be able to walk the complete redeclaration chains of the updated decls.
12068 while (!PendingExceptionSpecUpdates.empty() ||
12069 !PendingDeducedTypeUpdates.empty()) {
12070 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000012071 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000012072 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000012073 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000012074 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000012075 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000012076 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000012077 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000012078 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000012079 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000012080 }
Richard Smitha62d1982018-08-03 01:00:01 +000012081
12082 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
12083 PendingDeducedTypeUpdates.clear();
12084 for (auto Update : DTUpdates) {
12085 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
12086 // FIXME: If the return type is already deduced, check that it matches.
12087 getContext().adjustDeducedFunctionResultType(Update.first,
12088 Update.second);
12089 }
Richard Smith9e2341d2015-03-23 03:25:59 +000012090 }
12091
Richard Smithce18a182015-07-14 00:26:00 +000012092 if (ReadTimer)
12093 ReadTimer->stopTimer();
12094
Richard Smith0f4e2c42015-08-06 04:23:48 +000012095 diagnoseOdrViolations();
12096
Richard Smith04d05b52014-03-23 00:27:18 +000012097 // We are not in recursive loading, so it's safe to pass the "interesting"
12098 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000012099 if (Consumer)
12100 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000012101 }
12102}
12103
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012104void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000012105 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
12106 // Remove any fake results before adding any real ones.
12107 auto It = PendingFakeLookupResults.find(II);
12108 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000012109 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000012110 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000012111 // FIXME: this works around module+PCH performance issue.
12112 // Rather than erase the result from the map, which is O(n), just clear
12113 // the vector of NamedDecls.
12114 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000012115 }
12116 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012117
12118 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
12119 SemaObj->TUScope->AddDecl(D);
12120 } else if (SemaObj->TUScope) {
12121 // Adding the decl to IdResolver may have failed because it was already in
12122 // (even though it was not added in scope). If it is already in, make sure
12123 // it gets in the scope as well.
12124 if (std::find(SemaObj->IdResolver.begin(Name),
12125 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
12126 SemaObj->TUScope->AddDecl(D);
12127 }
12128}
12129
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012130ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
12131 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000012132 const PCHContainerReader &PCHContainerRdr,
12133 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
12134 StringRef isysroot, bool DisableValidation,
12135 bool AllowASTWithCompilerErrors,
12136 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
12137 bool UseGlobalIndex,
12138 std::unique_ptr<llvm::Timer> ReadTimer)
12139 : Listener(DisableValidation
12140 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
12141 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000012142 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012143 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012144 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
12145 PCHContainerRdr, PP.getHeaderSearchInfo()),
12146 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000012147 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000012148 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
12149 AllowConfigurationMismatch(AllowConfigurationMismatch),
12150 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012151 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000012152 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000012153
12154 for (const auto &Ext : Extensions) {
12155 auto BlockName = Ext->getExtensionMetadata().BlockName;
12156 auto Known = ModuleFileExtensions.find(BlockName);
12157 if (Known != ModuleFileExtensions.end()) {
12158 Diags.Report(diag::warn_duplicate_module_file_extension)
12159 << BlockName;
12160 continue;
12161 }
12162
12163 ModuleFileExtensions.insert({BlockName, Ext});
12164 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012165}
12166
12167ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000012168 if (OwnsDeserializationListener)
12169 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000012170}
Richard Smith10379092016-05-06 23:14:07 +000012171
12172IdentifierResolver &ASTReader::getIdResolver() {
12173 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
12174}
David L. Jonesbe1557a2016-12-21 00:17:49 +000012175
JF Bastien0e828952019-06-26 19:50:12 +000012176Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
12177 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000012178 Idx = 0;
12179 Record.clear();
12180 return Cursor.readRecord(AbbrevID, Record);
12181}
Kelvin Libe286f52018-09-15 13:54:15 +000012182//===----------------------------------------------------------------------===//
12183//// OMPClauseReader implementation
12184////===----------------------------------------------------------------------===//
12185
12186OMPClause *OMPClauseReader::readClause() {
12187 OMPClause *C;
12188 switch (Record.readInt()) {
12189 case OMPC_if:
12190 C = new (Context) OMPIfClause();
12191 break;
12192 case OMPC_final:
12193 C = new (Context) OMPFinalClause();
12194 break;
12195 case OMPC_num_threads:
12196 C = new (Context) OMPNumThreadsClause();
12197 break;
12198 case OMPC_safelen:
12199 C = new (Context) OMPSafelenClause();
12200 break;
12201 case OMPC_simdlen:
12202 C = new (Context) OMPSimdlenClause();
12203 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012204 case OMPC_allocator:
12205 C = new (Context) OMPAllocatorClause();
12206 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012207 case OMPC_collapse:
12208 C = new (Context) OMPCollapseClause();
12209 break;
12210 case OMPC_default:
12211 C = new (Context) OMPDefaultClause();
12212 break;
12213 case OMPC_proc_bind:
12214 C = new (Context) OMPProcBindClause();
12215 break;
12216 case OMPC_schedule:
12217 C = new (Context) OMPScheduleClause();
12218 break;
12219 case OMPC_ordered:
12220 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
12221 break;
12222 case OMPC_nowait:
12223 C = new (Context) OMPNowaitClause();
12224 break;
12225 case OMPC_untied:
12226 C = new (Context) OMPUntiedClause();
12227 break;
12228 case OMPC_mergeable:
12229 C = new (Context) OMPMergeableClause();
12230 break;
12231 case OMPC_read:
12232 C = new (Context) OMPReadClause();
12233 break;
12234 case OMPC_write:
12235 C = new (Context) OMPWriteClause();
12236 break;
12237 case OMPC_update:
12238 C = new (Context) OMPUpdateClause();
12239 break;
12240 case OMPC_capture:
12241 C = new (Context) OMPCaptureClause();
12242 break;
12243 case OMPC_seq_cst:
12244 C = new (Context) OMPSeqCstClause();
12245 break;
12246 case OMPC_threads:
12247 C = new (Context) OMPThreadsClause();
12248 break;
12249 case OMPC_simd:
12250 C = new (Context) OMPSIMDClause();
12251 break;
12252 case OMPC_nogroup:
12253 C = new (Context) OMPNogroupClause();
12254 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012255 case OMPC_unified_address:
12256 C = new (Context) OMPUnifiedAddressClause();
12257 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012258 case OMPC_unified_shared_memory:
12259 C = new (Context) OMPUnifiedSharedMemoryClause();
12260 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012261 case OMPC_reverse_offload:
12262 C = new (Context) OMPReverseOffloadClause();
12263 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012264 case OMPC_dynamic_allocators:
12265 C = new (Context) OMPDynamicAllocatorsClause();
12266 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012267 case OMPC_atomic_default_mem_order:
12268 C = new (Context) OMPAtomicDefaultMemOrderClause();
12269 break;
12270 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000012271 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
12272 break;
12273 case OMPC_firstprivate:
12274 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
12275 break;
12276 case OMPC_lastprivate:
12277 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
12278 break;
12279 case OMPC_shared:
12280 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
12281 break;
12282 case OMPC_reduction:
12283 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
12284 break;
12285 case OMPC_task_reduction:
12286 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
12287 break;
12288 case OMPC_in_reduction:
12289 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
12290 break;
12291 case OMPC_linear:
12292 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
12293 break;
12294 case OMPC_aligned:
12295 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
12296 break;
12297 case OMPC_copyin:
12298 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
12299 break;
12300 case OMPC_copyprivate:
12301 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
12302 break;
12303 case OMPC_flush:
12304 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
12305 break;
12306 case OMPC_depend: {
12307 unsigned NumVars = Record.readInt();
12308 unsigned NumLoops = Record.readInt();
12309 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
12310 break;
12311 }
12312 case OMPC_device:
12313 C = new (Context) OMPDeviceClause();
12314 break;
12315 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012316 OMPMappableExprListSizeTy Sizes;
12317 Sizes.NumVars = Record.readInt();
12318 Sizes.NumUniqueDeclarations = Record.readInt();
12319 Sizes.NumComponentLists = Record.readInt();
12320 Sizes.NumComponents = Record.readInt();
12321 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012322 break;
12323 }
12324 case OMPC_num_teams:
12325 C = new (Context) OMPNumTeamsClause();
12326 break;
12327 case OMPC_thread_limit:
12328 C = new (Context) OMPThreadLimitClause();
12329 break;
12330 case OMPC_priority:
12331 C = new (Context) OMPPriorityClause();
12332 break;
12333 case OMPC_grainsize:
12334 C = new (Context) OMPGrainsizeClause();
12335 break;
12336 case OMPC_num_tasks:
12337 C = new (Context) OMPNumTasksClause();
12338 break;
12339 case OMPC_hint:
12340 C = new (Context) OMPHintClause();
12341 break;
12342 case OMPC_dist_schedule:
12343 C = new (Context) OMPDistScheduleClause();
12344 break;
12345 case OMPC_defaultmap:
12346 C = new (Context) OMPDefaultmapClause();
12347 break;
12348 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012349 OMPMappableExprListSizeTy Sizes;
12350 Sizes.NumVars = Record.readInt();
12351 Sizes.NumUniqueDeclarations = Record.readInt();
12352 Sizes.NumComponentLists = Record.readInt();
12353 Sizes.NumComponents = Record.readInt();
12354 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012355 break;
12356 }
12357 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012358 OMPMappableExprListSizeTy Sizes;
12359 Sizes.NumVars = Record.readInt();
12360 Sizes.NumUniqueDeclarations = Record.readInt();
12361 Sizes.NumComponentLists = Record.readInt();
12362 Sizes.NumComponents = Record.readInt();
12363 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012364 break;
12365 }
12366 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012367 OMPMappableExprListSizeTy Sizes;
12368 Sizes.NumVars = Record.readInt();
12369 Sizes.NumUniqueDeclarations = Record.readInt();
12370 Sizes.NumComponentLists = Record.readInt();
12371 Sizes.NumComponents = Record.readInt();
12372 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012373 break;
12374 }
12375 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012376 OMPMappableExprListSizeTy Sizes;
12377 Sizes.NumVars = Record.readInt();
12378 Sizes.NumUniqueDeclarations = Record.readInt();
12379 Sizes.NumComponentLists = Record.readInt();
12380 Sizes.NumComponents = Record.readInt();
12381 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012382 break;
12383 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000012384 case OMPC_allocate:
12385 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
12386 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012387 }
12388 Visit(C);
12389 C->setLocStart(Record.readSourceLocation());
12390 C->setLocEnd(Record.readSourceLocation());
12391
12392 return C;
12393}
12394
12395void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12396 C->setPreInitStmt(Record.readSubStmt(),
12397 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12398}
12399
12400void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12401 VisitOMPClauseWithPreInit(C);
12402 C->setPostUpdateExpr(Record.readSubExpr());
12403}
12404
12405void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12406 VisitOMPClauseWithPreInit(C);
12407 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12408 C->setNameModifierLoc(Record.readSourceLocation());
12409 C->setColonLoc(Record.readSourceLocation());
12410 C->setCondition(Record.readSubExpr());
12411 C->setLParenLoc(Record.readSourceLocation());
12412}
12413
12414void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12415 C->setCondition(Record.readSubExpr());
12416 C->setLParenLoc(Record.readSourceLocation());
12417}
12418
12419void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12420 VisitOMPClauseWithPreInit(C);
12421 C->setNumThreads(Record.readSubExpr());
12422 C->setLParenLoc(Record.readSourceLocation());
12423}
12424
12425void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12426 C->setSafelen(Record.readSubExpr());
12427 C->setLParenLoc(Record.readSourceLocation());
12428}
12429
12430void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12431 C->setSimdlen(Record.readSubExpr());
12432 C->setLParenLoc(Record.readSourceLocation());
12433}
12434
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012435void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12436 C->setAllocator(Record.readExpr());
12437 C->setLParenLoc(Record.readSourceLocation());
12438}
12439
Kelvin Libe286f52018-09-15 13:54:15 +000012440void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12441 C->setNumForLoops(Record.readSubExpr());
12442 C->setLParenLoc(Record.readSourceLocation());
12443}
12444
12445void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12446 C->setDefaultKind(
12447 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12448 C->setLParenLoc(Record.readSourceLocation());
12449 C->setDefaultKindKwLoc(Record.readSourceLocation());
12450}
12451
12452void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12453 C->setProcBindKind(
12454 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12455 C->setLParenLoc(Record.readSourceLocation());
12456 C->setProcBindKindKwLoc(Record.readSourceLocation());
12457}
12458
12459void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12460 VisitOMPClauseWithPreInit(C);
12461 C->setScheduleKind(
12462 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12463 C->setFirstScheduleModifier(
12464 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12465 C->setSecondScheduleModifier(
12466 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12467 C->setChunkSize(Record.readSubExpr());
12468 C->setLParenLoc(Record.readSourceLocation());
12469 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12470 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12471 C->setScheduleKindLoc(Record.readSourceLocation());
12472 C->setCommaLoc(Record.readSourceLocation());
12473}
12474
12475void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12476 C->setNumForLoops(Record.readSubExpr());
12477 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12478 C->setLoopNumIterations(I, Record.readSubExpr());
12479 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12480 C->setLoopCounter(I, Record.readSubExpr());
12481 C->setLParenLoc(Record.readSourceLocation());
12482}
12483
12484void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12485
12486void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12487
12488void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12489
12490void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12491
12492void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12493
12494void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12495
12496void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12497
12498void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12499
12500void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12501
12502void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12503
12504void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12505
Kelvin Li1408f912018-09-26 04:28:39 +000012506void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12507
Patrick Lyster4a370b92018-10-01 13:47:43 +000012508void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12509 OMPUnifiedSharedMemoryClause *) {}
12510
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012511void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12512
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012513void
12514OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12515}
12516
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012517void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12518 OMPAtomicDefaultMemOrderClause *C) {
12519 C->setAtomicDefaultMemOrderKind(
12520 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12521 C->setLParenLoc(Record.readSourceLocation());
12522 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12523}
12524
Kelvin Libe286f52018-09-15 13:54:15 +000012525void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12526 C->setLParenLoc(Record.readSourceLocation());
12527 unsigned NumVars = C->varlist_size();
12528 SmallVector<Expr *, 16> Vars;
12529 Vars.reserve(NumVars);
12530 for (unsigned i = 0; i != NumVars; ++i)
12531 Vars.push_back(Record.readSubExpr());
12532 C->setVarRefs(Vars);
12533 Vars.clear();
12534 for (unsigned i = 0; i != NumVars; ++i)
12535 Vars.push_back(Record.readSubExpr());
12536 C->setPrivateCopies(Vars);
12537}
12538
12539void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12540 VisitOMPClauseWithPreInit(C);
12541 C->setLParenLoc(Record.readSourceLocation());
12542 unsigned NumVars = C->varlist_size();
12543 SmallVector<Expr *, 16> Vars;
12544 Vars.reserve(NumVars);
12545 for (unsigned i = 0; i != NumVars; ++i)
12546 Vars.push_back(Record.readSubExpr());
12547 C->setVarRefs(Vars);
12548 Vars.clear();
12549 for (unsigned i = 0; i != NumVars; ++i)
12550 Vars.push_back(Record.readSubExpr());
12551 C->setPrivateCopies(Vars);
12552 Vars.clear();
12553 for (unsigned i = 0; i != NumVars; ++i)
12554 Vars.push_back(Record.readSubExpr());
12555 C->setInits(Vars);
12556}
12557
12558void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12559 VisitOMPClauseWithPostUpdate(C);
12560 C->setLParenLoc(Record.readSourceLocation());
12561 unsigned NumVars = C->varlist_size();
12562 SmallVector<Expr *, 16> Vars;
12563 Vars.reserve(NumVars);
12564 for (unsigned i = 0; i != NumVars; ++i)
12565 Vars.push_back(Record.readSubExpr());
12566 C->setVarRefs(Vars);
12567 Vars.clear();
12568 for (unsigned i = 0; i != NumVars; ++i)
12569 Vars.push_back(Record.readSubExpr());
12570 C->setPrivateCopies(Vars);
12571 Vars.clear();
12572 for (unsigned i = 0; i != NumVars; ++i)
12573 Vars.push_back(Record.readSubExpr());
12574 C->setSourceExprs(Vars);
12575 Vars.clear();
12576 for (unsigned i = 0; i != NumVars; ++i)
12577 Vars.push_back(Record.readSubExpr());
12578 C->setDestinationExprs(Vars);
12579 Vars.clear();
12580 for (unsigned i = 0; i != NumVars; ++i)
12581 Vars.push_back(Record.readSubExpr());
12582 C->setAssignmentOps(Vars);
12583}
12584
12585void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12586 C->setLParenLoc(Record.readSourceLocation());
12587 unsigned NumVars = C->varlist_size();
12588 SmallVector<Expr *, 16> Vars;
12589 Vars.reserve(NumVars);
12590 for (unsigned i = 0; i != NumVars; ++i)
12591 Vars.push_back(Record.readSubExpr());
12592 C->setVarRefs(Vars);
12593}
12594
12595void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12596 VisitOMPClauseWithPostUpdate(C);
12597 C->setLParenLoc(Record.readSourceLocation());
12598 C->setColonLoc(Record.readSourceLocation());
12599 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12600 DeclarationNameInfo DNI;
12601 Record.readDeclarationNameInfo(DNI);
12602 C->setQualifierLoc(NNSL);
12603 C->setNameInfo(DNI);
12604
12605 unsigned NumVars = C->varlist_size();
12606 SmallVector<Expr *, 16> Vars;
12607 Vars.reserve(NumVars);
12608 for (unsigned i = 0; i != NumVars; ++i)
12609 Vars.push_back(Record.readSubExpr());
12610 C->setVarRefs(Vars);
12611 Vars.clear();
12612 for (unsigned i = 0; i != NumVars; ++i)
12613 Vars.push_back(Record.readSubExpr());
12614 C->setPrivates(Vars);
12615 Vars.clear();
12616 for (unsigned i = 0; i != NumVars; ++i)
12617 Vars.push_back(Record.readSubExpr());
12618 C->setLHSExprs(Vars);
12619 Vars.clear();
12620 for (unsigned i = 0; i != NumVars; ++i)
12621 Vars.push_back(Record.readSubExpr());
12622 C->setRHSExprs(Vars);
12623 Vars.clear();
12624 for (unsigned i = 0; i != NumVars; ++i)
12625 Vars.push_back(Record.readSubExpr());
12626 C->setReductionOps(Vars);
12627}
12628
12629void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12630 VisitOMPClauseWithPostUpdate(C);
12631 C->setLParenLoc(Record.readSourceLocation());
12632 C->setColonLoc(Record.readSourceLocation());
12633 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12634 DeclarationNameInfo DNI;
12635 Record.readDeclarationNameInfo(DNI);
12636 C->setQualifierLoc(NNSL);
12637 C->setNameInfo(DNI);
12638
12639 unsigned NumVars = C->varlist_size();
12640 SmallVector<Expr *, 16> Vars;
12641 Vars.reserve(NumVars);
12642 for (unsigned I = 0; I != NumVars; ++I)
12643 Vars.push_back(Record.readSubExpr());
12644 C->setVarRefs(Vars);
12645 Vars.clear();
12646 for (unsigned I = 0; I != NumVars; ++I)
12647 Vars.push_back(Record.readSubExpr());
12648 C->setPrivates(Vars);
12649 Vars.clear();
12650 for (unsigned I = 0; I != NumVars; ++I)
12651 Vars.push_back(Record.readSubExpr());
12652 C->setLHSExprs(Vars);
12653 Vars.clear();
12654 for (unsigned I = 0; I != NumVars; ++I)
12655 Vars.push_back(Record.readSubExpr());
12656 C->setRHSExprs(Vars);
12657 Vars.clear();
12658 for (unsigned I = 0; I != NumVars; ++I)
12659 Vars.push_back(Record.readSubExpr());
12660 C->setReductionOps(Vars);
12661}
12662
12663void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12664 VisitOMPClauseWithPostUpdate(C);
12665 C->setLParenLoc(Record.readSourceLocation());
12666 C->setColonLoc(Record.readSourceLocation());
12667 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12668 DeclarationNameInfo DNI;
12669 Record.readDeclarationNameInfo(DNI);
12670 C->setQualifierLoc(NNSL);
12671 C->setNameInfo(DNI);
12672
12673 unsigned NumVars = C->varlist_size();
12674 SmallVector<Expr *, 16> Vars;
12675 Vars.reserve(NumVars);
12676 for (unsigned I = 0; I != NumVars; ++I)
12677 Vars.push_back(Record.readSubExpr());
12678 C->setVarRefs(Vars);
12679 Vars.clear();
12680 for (unsigned I = 0; I != NumVars; ++I)
12681 Vars.push_back(Record.readSubExpr());
12682 C->setPrivates(Vars);
12683 Vars.clear();
12684 for (unsigned I = 0; I != NumVars; ++I)
12685 Vars.push_back(Record.readSubExpr());
12686 C->setLHSExprs(Vars);
12687 Vars.clear();
12688 for (unsigned I = 0; I != NumVars; ++I)
12689 Vars.push_back(Record.readSubExpr());
12690 C->setRHSExprs(Vars);
12691 Vars.clear();
12692 for (unsigned I = 0; I != NumVars; ++I)
12693 Vars.push_back(Record.readSubExpr());
12694 C->setReductionOps(Vars);
12695 Vars.clear();
12696 for (unsigned I = 0; I != NumVars; ++I)
12697 Vars.push_back(Record.readSubExpr());
12698 C->setTaskgroupDescriptors(Vars);
12699}
12700
12701void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12702 VisitOMPClauseWithPostUpdate(C);
12703 C->setLParenLoc(Record.readSourceLocation());
12704 C->setColonLoc(Record.readSourceLocation());
12705 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12706 C->setModifierLoc(Record.readSourceLocation());
12707 unsigned NumVars = C->varlist_size();
12708 SmallVector<Expr *, 16> Vars;
12709 Vars.reserve(NumVars);
12710 for (unsigned i = 0; i != NumVars; ++i)
12711 Vars.push_back(Record.readSubExpr());
12712 C->setVarRefs(Vars);
12713 Vars.clear();
12714 for (unsigned i = 0; i != NumVars; ++i)
12715 Vars.push_back(Record.readSubExpr());
12716 C->setPrivates(Vars);
12717 Vars.clear();
12718 for (unsigned i = 0; i != NumVars; ++i)
12719 Vars.push_back(Record.readSubExpr());
12720 C->setInits(Vars);
12721 Vars.clear();
12722 for (unsigned i = 0; i != NumVars; ++i)
12723 Vars.push_back(Record.readSubExpr());
12724 C->setUpdates(Vars);
12725 Vars.clear();
12726 for (unsigned i = 0; i != NumVars; ++i)
12727 Vars.push_back(Record.readSubExpr());
12728 C->setFinals(Vars);
12729 C->setStep(Record.readSubExpr());
12730 C->setCalcStep(Record.readSubExpr());
12731}
12732
12733void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12734 C->setLParenLoc(Record.readSourceLocation());
12735 C->setColonLoc(Record.readSourceLocation());
12736 unsigned NumVars = C->varlist_size();
12737 SmallVector<Expr *, 16> Vars;
12738 Vars.reserve(NumVars);
12739 for (unsigned i = 0; i != NumVars; ++i)
12740 Vars.push_back(Record.readSubExpr());
12741 C->setVarRefs(Vars);
12742 C->setAlignment(Record.readSubExpr());
12743}
12744
12745void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12746 C->setLParenLoc(Record.readSourceLocation());
12747 unsigned NumVars = C->varlist_size();
12748 SmallVector<Expr *, 16> Exprs;
12749 Exprs.reserve(NumVars);
12750 for (unsigned i = 0; i != NumVars; ++i)
12751 Exprs.push_back(Record.readSubExpr());
12752 C->setVarRefs(Exprs);
12753 Exprs.clear();
12754 for (unsigned i = 0; i != NumVars; ++i)
12755 Exprs.push_back(Record.readSubExpr());
12756 C->setSourceExprs(Exprs);
12757 Exprs.clear();
12758 for (unsigned i = 0; i != NumVars; ++i)
12759 Exprs.push_back(Record.readSubExpr());
12760 C->setDestinationExprs(Exprs);
12761 Exprs.clear();
12762 for (unsigned i = 0; i != NumVars; ++i)
12763 Exprs.push_back(Record.readSubExpr());
12764 C->setAssignmentOps(Exprs);
12765}
12766
12767void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12768 C->setLParenLoc(Record.readSourceLocation());
12769 unsigned NumVars = C->varlist_size();
12770 SmallVector<Expr *, 16> Exprs;
12771 Exprs.reserve(NumVars);
12772 for (unsigned i = 0; i != NumVars; ++i)
12773 Exprs.push_back(Record.readSubExpr());
12774 C->setVarRefs(Exprs);
12775 Exprs.clear();
12776 for (unsigned i = 0; i != NumVars; ++i)
12777 Exprs.push_back(Record.readSubExpr());
12778 C->setSourceExprs(Exprs);
12779 Exprs.clear();
12780 for (unsigned i = 0; i != NumVars; ++i)
12781 Exprs.push_back(Record.readSubExpr());
12782 C->setDestinationExprs(Exprs);
12783 Exprs.clear();
12784 for (unsigned i = 0; i != NumVars; ++i)
12785 Exprs.push_back(Record.readSubExpr());
12786 C->setAssignmentOps(Exprs);
12787}
12788
12789void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12790 C->setLParenLoc(Record.readSourceLocation());
12791 unsigned NumVars = C->varlist_size();
12792 SmallVector<Expr *, 16> Vars;
12793 Vars.reserve(NumVars);
12794 for (unsigned i = 0; i != NumVars; ++i)
12795 Vars.push_back(Record.readSubExpr());
12796 C->setVarRefs(Vars);
12797}
12798
12799void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12800 C->setLParenLoc(Record.readSourceLocation());
12801 C->setDependencyKind(
12802 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12803 C->setDependencyLoc(Record.readSourceLocation());
12804 C->setColonLoc(Record.readSourceLocation());
12805 unsigned NumVars = C->varlist_size();
12806 SmallVector<Expr *, 16> Vars;
12807 Vars.reserve(NumVars);
12808 for (unsigned I = 0; I != NumVars; ++I)
12809 Vars.push_back(Record.readSubExpr());
12810 C->setVarRefs(Vars);
12811 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12812 C->setLoopData(I, Record.readSubExpr());
12813}
12814
12815void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12816 VisitOMPClauseWithPreInit(C);
12817 C->setDevice(Record.readSubExpr());
12818 C->setLParenLoc(Record.readSourceLocation());
12819}
12820
12821void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12822 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012823 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12824 C->setMapTypeModifier(
12825 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12826 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12827 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012828 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12829 DeclarationNameInfo DNI;
12830 Record.readDeclarationNameInfo(DNI);
12831 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012832 C->setMapType(
12833 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12834 C->setMapLoc(Record.readSourceLocation());
12835 C->setColonLoc(Record.readSourceLocation());
12836 auto NumVars = C->varlist_size();
12837 auto UniqueDecls = C->getUniqueDeclarationsNum();
12838 auto TotalLists = C->getTotalComponentListNum();
12839 auto TotalComponents = C->getTotalComponentsNum();
12840
12841 SmallVector<Expr *, 16> Vars;
12842 Vars.reserve(NumVars);
12843 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012844 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012845 C->setVarRefs(Vars);
12846
Michael Kruse4304e9d2019-02-19 16:38:20 +000012847 SmallVector<Expr *, 16> UDMappers;
12848 UDMappers.reserve(NumVars);
12849 for (unsigned I = 0; I < NumVars; ++I)
12850 UDMappers.push_back(Record.readExpr());
12851 C->setUDMapperRefs(UDMappers);
12852
Kelvin Libe286f52018-09-15 13:54:15 +000012853 SmallVector<ValueDecl *, 16> Decls;
12854 Decls.reserve(UniqueDecls);
12855 for (unsigned i = 0; i < UniqueDecls; ++i)
12856 Decls.push_back(Record.readDeclAs<ValueDecl>());
12857 C->setUniqueDecls(Decls);
12858
12859 SmallVector<unsigned, 16> ListsPerDecl;
12860 ListsPerDecl.reserve(UniqueDecls);
12861 for (unsigned i = 0; i < UniqueDecls; ++i)
12862 ListsPerDecl.push_back(Record.readInt());
12863 C->setDeclNumLists(ListsPerDecl);
12864
12865 SmallVector<unsigned, 32> ListSizes;
12866 ListSizes.reserve(TotalLists);
12867 for (unsigned i = 0; i < TotalLists; ++i)
12868 ListSizes.push_back(Record.readInt());
12869 C->setComponentListSizes(ListSizes);
12870
12871 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12872 Components.reserve(TotalComponents);
12873 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012874 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012875 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12876 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12877 AssociatedExpr, AssociatedDecl));
12878 }
12879 C->setComponents(Components, ListSizes);
12880}
12881
Alexey Bataeve04483e2019-03-27 14:14:31 +000012882void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12883 C->setLParenLoc(Record.readSourceLocation());
12884 C->setColonLoc(Record.readSourceLocation());
12885 C->setAllocator(Record.readSubExpr());
12886 unsigned NumVars = C->varlist_size();
12887 SmallVector<Expr *, 16> Vars;
12888 Vars.reserve(NumVars);
12889 for (unsigned i = 0; i != NumVars; ++i)
12890 Vars.push_back(Record.readSubExpr());
12891 C->setVarRefs(Vars);
12892}
12893
Kelvin Libe286f52018-09-15 13:54:15 +000012894void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12895 VisitOMPClauseWithPreInit(C);
12896 C->setNumTeams(Record.readSubExpr());
12897 C->setLParenLoc(Record.readSourceLocation());
12898}
12899
12900void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12901 VisitOMPClauseWithPreInit(C);
12902 C->setThreadLimit(Record.readSubExpr());
12903 C->setLParenLoc(Record.readSourceLocation());
12904}
12905
12906void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12907 C->setPriority(Record.readSubExpr());
12908 C->setLParenLoc(Record.readSourceLocation());
12909}
12910
12911void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12912 C->setGrainsize(Record.readSubExpr());
12913 C->setLParenLoc(Record.readSourceLocation());
12914}
12915
12916void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12917 C->setNumTasks(Record.readSubExpr());
12918 C->setLParenLoc(Record.readSourceLocation());
12919}
12920
12921void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12922 C->setHint(Record.readSubExpr());
12923 C->setLParenLoc(Record.readSourceLocation());
12924}
12925
12926void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12927 VisitOMPClauseWithPreInit(C);
12928 C->setDistScheduleKind(
12929 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12930 C->setChunkSize(Record.readSubExpr());
12931 C->setLParenLoc(Record.readSourceLocation());
12932 C->setDistScheduleKindLoc(Record.readSourceLocation());
12933 C->setCommaLoc(Record.readSourceLocation());
12934}
12935
12936void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12937 C->setDefaultmapKind(
12938 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12939 C->setDefaultmapModifier(
12940 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12941 C->setLParenLoc(Record.readSourceLocation());
12942 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12943 C->setDefaultmapKindLoc(Record.readSourceLocation());
12944}
12945
12946void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12947 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012948 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12949 DeclarationNameInfo DNI;
12950 Record.readDeclarationNameInfo(DNI);
12951 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012952 auto NumVars = C->varlist_size();
12953 auto UniqueDecls = C->getUniqueDeclarationsNum();
12954 auto TotalLists = C->getTotalComponentListNum();
12955 auto TotalComponents = C->getTotalComponentsNum();
12956
12957 SmallVector<Expr *, 16> Vars;
12958 Vars.reserve(NumVars);
12959 for (unsigned i = 0; i != NumVars; ++i)
12960 Vars.push_back(Record.readSubExpr());
12961 C->setVarRefs(Vars);
12962
Michael Kruse01f670d2019-02-22 22:29:42 +000012963 SmallVector<Expr *, 16> UDMappers;
12964 UDMappers.reserve(NumVars);
12965 for (unsigned I = 0; I < NumVars; ++I)
12966 UDMappers.push_back(Record.readSubExpr());
12967 C->setUDMapperRefs(UDMappers);
12968
Kelvin Libe286f52018-09-15 13:54:15 +000012969 SmallVector<ValueDecl *, 16> Decls;
12970 Decls.reserve(UniqueDecls);
12971 for (unsigned i = 0; i < UniqueDecls; ++i)
12972 Decls.push_back(Record.readDeclAs<ValueDecl>());
12973 C->setUniqueDecls(Decls);
12974
12975 SmallVector<unsigned, 16> ListsPerDecl;
12976 ListsPerDecl.reserve(UniqueDecls);
12977 for (unsigned i = 0; i < UniqueDecls; ++i)
12978 ListsPerDecl.push_back(Record.readInt());
12979 C->setDeclNumLists(ListsPerDecl);
12980
12981 SmallVector<unsigned, 32> ListSizes;
12982 ListSizes.reserve(TotalLists);
12983 for (unsigned i = 0; i < TotalLists; ++i)
12984 ListSizes.push_back(Record.readInt());
12985 C->setComponentListSizes(ListSizes);
12986
12987 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12988 Components.reserve(TotalComponents);
12989 for (unsigned i = 0; i < TotalComponents; ++i) {
12990 Expr *AssociatedExpr = Record.readSubExpr();
12991 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12992 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12993 AssociatedExpr, AssociatedDecl));
12994 }
12995 C->setComponents(Components, ListSizes);
12996}
12997
12998void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12999 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000013000 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13001 DeclarationNameInfo DNI;
13002 Record.readDeclarationNameInfo(DNI);
13003 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013004 auto NumVars = C->varlist_size();
13005 auto UniqueDecls = C->getUniqueDeclarationsNum();
13006 auto TotalLists = C->getTotalComponentListNum();
13007 auto TotalComponents = C->getTotalComponentsNum();
13008
13009 SmallVector<Expr *, 16> Vars;
13010 Vars.reserve(NumVars);
13011 for (unsigned i = 0; i != NumVars; ++i)
13012 Vars.push_back(Record.readSubExpr());
13013 C->setVarRefs(Vars);
13014
Michael Kruse0336c752019-02-25 20:34:15 +000013015 SmallVector<Expr *, 16> UDMappers;
13016 UDMappers.reserve(NumVars);
13017 for (unsigned I = 0; I < NumVars; ++I)
13018 UDMappers.push_back(Record.readSubExpr());
13019 C->setUDMapperRefs(UDMappers);
13020
Kelvin Libe286f52018-09-15 13:54:15 +000013021 SmallVector<ValueDecl *, 16> Decls;
13022 Decls.reserve(UniqueDecls);
13023 for (unsigned i = 0; i < UniqueDecls; ++i)
13024 Decls.push_back(Record.readDeclAs<ValueDecl>());
13025 C->setUniqueDecls(Decls);
13026
13027 SmallVector<unsigned, 16> ListsPerDecl;
13028 ListsPerDecl.reserve(UniqueDecls);
13029 for (unsigned i = 0; i < UniqueDecls; ++i)
13030 ListsPerDecl.push_back(Record.readInt());
13031 C->setDeclNumLists(ListsPerDecl);
13032
13033 SmallVector<unsigned, 32> ListSizes;
13034 ListSizes.reserve(TotalLists);
13035 for (unsigned i = 0; i < TotalLists; ++i)
13036 ListSizes.push_back(Record.readInt());
13037 C->setComponentListSizes(ListSizes);
13038
13039 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13040 Components.reserve(TotalComponents);
13041 for (unsigned i = 0; i < TotalComponents; ++i) {
13042 Expr *AssociatedExpr = Record.readSubExpr();
13043 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13044 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13045 AssociatedExpr, AssociatedDecl));
13046 }
13047 C->setComponents(Components, ListSizes);
13048}
13049
13050void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13051 C->setLParenLoc(Record.readSourceLocation());
13052 auto NumVars = C->varlist_size();
13053 auto UniqueDecls = C->getUniqueDeclarationsNum();
13054 auto TotalLists = C->getTotalComponentListNum();
13055 auto TotalComponents = C->getTotalComponentsNum();
13056
13057 SmallVector<Expr *, 16> Vars;
13058 Vars.reserve(NumVars);
13059 for (unsigned i = 0; i != NumVars; ++i)
13060 Vars.push_back(Record.readSubExpr());
13061 C->setVarRefs(Vars);
13062 Vars.clear();
13063 for (unsigned i = 0; i != NumVars; ++i)
13064 Vars.push_back(Record.readSubExpr());
13065 C->setPrivateCopies(Vars);
13066 Vars.clear();
13067 for (unsigned i = 0; i != NumVars; ++i)
13068 Vars.push_back(Record.readSubExpr());
13069 C->setInits(Vars);
13070
13071 SmallVector<ValueDecl *, 16> Decls;
13072 Decls.reserve(UniqueDecls);
13073 for (unsigned i = 0; i < UniqueDecls; ++i)
13074 Decls.push_back(Record.readDeclAs<ValueDecl>());
13075 C->setUniqueDecls(Decls);
13076
13077 SmallVector<unsigned, 16> ListsPerDecl;
13078 ListsPerDecl.reserve(UniqueDecls);
13079 for (unsigned i = 0; i < UniqueDecls; ++i)
13080 ListsPerDecl.push_back(Record.readInt());
13081 C->setDeclNumLists(ListsPerDecl);
13082
13083 SmallVector<unsigned, 32> ListSizes;
13084 ListSizes.reserve(TotalLists);
13085 for (unsigned i = 0; i < TotalLists; ++i)
13086 ListSizes.push_back(Record.readInt());
13087 C->setComponentListSizes(ListSizes);
13088
13089 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13090 Components.reserve(TotalComponents);
13091 for (unsigned i = 0; i < TotalComponents; ++i) {
13092 Expr *AssociatedExpr = Record.readSubExpr();
13093 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13094 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13095 AssociatedExpr, AssociatedDecl));
13096 }
13097 C->setComponents(Components, ListSizes);
13098}
13099
13100void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13101 C->setLParenLoc(Record.readSourceLocation());
13102 auto NumVars = C->varlist_size();
13103 auto UniqueDecls = C->getUniqueDeclarationsNum();
13104 auto TotalLists = C->getTotalComponentListNum();
13105 auto TotalComponents = C->getTotalComponentsNum();
13106
13107 SmallVector<Expr *, 16> Vars;
13108 Vars.reserve(NumVars);
13109 for (unsigned i = 0; i != NumVars; ++i)
13110 Vars.push_back(Record.readSubExpr());
13111 C->setVarRefs(Vars);
13112 Vars.clear();
13113
13114 SmallVector<ValueDecl *, 16> Decls;
13115 Decls.reserve(UniqueDecls);
13116 for (unsigned i = 0; i < UniqueDecls; ++i)
13117 Decls.push_back(Record.readDeclAs<ValueDecl>());
13118 C->setUniqueDecls(Decls);
13119
13120 SmallVector<unsigned, 16> ListsPerDecl;
13121 ListsPerDecl.reserve(UniqueDecls);
13122 for (unsigned i = 0; i < UniqueDecls; ++i)
13123 ListsPerDecl.push_back(Record.readInt());
13124 C->setDeclNumLists(ListsPerDecl);
13125
13126 SmallVector<unsigned, 32> ListSizes;
13127 ListSizes.reserve(TotalLists);
13128 for (unsigned i = 0; i < TotalLists; ++i)
13129 ListSizes.push_back(Record.readInt());
13130 C->setComponentListSizes(ListSizes);
13131
13132 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13133 Components.reserve(TotalComponents);
13134 for (unsigned i = 0; i < TotalComponents; ++i) {
13135 Expr *AssociatedExpr = Record.readSubExpr();
13136 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13137 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13138 AssociatedExpr, AssociatedDecl));
13139 }
13140 C->setComponents(Components, ListSizes);
13141}