blob: b8b390afc42bdd257c6ed0d407ad3b0b047113c5 [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"
95#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000096#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000097#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +000098#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000099#include "llvm/ADT/StringMap.h"
100#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000101#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000102#include "llvm/ADT/iterator_range.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000103#include "llvm/Bitcode/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000104#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000105#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000106#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000107#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000108#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000109#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000110#include "llvm/Support/ErrorHandling.h"
111#include "llvm/Support/FileSystem.h"
112#include "llvm/Support/MemoryBuffer.h"
113#include "llvm/Support/Path.h"
114#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000115#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000116#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000117#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000118#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000119#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000120#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000121#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000122#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000124#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000125#include <limits>
126#include <map>
127#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000128#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000129#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000130#include <tuple>
131#include <utility>
132#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000133
134using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000135using namespace clang::serialization;
136using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000137using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000138
Ben Langmuircb69b572014-03-07 06:40:32 +0000139//===----------------------------------------------------------------------===//
140// ChainedASTReaderListener implementation
141//===----------------------------------------------------------------------===//
142
143bool
144ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
145 return First->ReadFullVersionInformation(FullVersion) ||
146 Second->ReadFullVersionInformation(FullVersion);
147}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000149void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
150 First->ReadModuleName(ModuleName);
151 Second->ReadModuleName(ModuleName);
152}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000153
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000154void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
155 First->ReadModuleMapFile(ModuleMapPath);
156 Second->ReadModuleMapFile(ModuleMapPath);
157}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000158
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000159bool
160ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
161 bool Complain,
162 bool AllowCompatibleDifferences) {
163 return First->ReadLanguageOptions(LangOpts, Complain,
164 AllowCompatibleDifferences) ||
165 Second->ReadLanguageOptions(LangOpts, Complain,
166 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000167}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000168
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000169bool ChainedASTReaderListener::ReadTargetOptions(
170 const TargetOptions &TargetOpts, bool Complain,
171 bool AllowCompatibleDifferences) {
172 return First->ReadTargetOptions(TargetOpts, Complain,
173 AllowCompatibleDifferences) ||
174 Second->ReadTargetOptions(TargetOpts, Complain,
175 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000176}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000177
Ben Langmuircb69b572014-03-07 06:40:32 +0000178bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000179 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000180 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
181 Second->ReadDiagnosticOptions(DiagOpts, Complain);
182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000183
Ben Langmuircb69b572014-03-07 06:40:32 +0000184bool
185ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
186 bool Complain) {
187 return First->ReadFileSystemOptions(FSOpts, Complain) ||
188 Second->ReadFileSystemOptions(FSOpts, Complain);
189}
190
191bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000192 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
193 bool Complain) {
194 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
195 Complain) ||
196 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
197 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000198}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000199
Ben Langmuircb69b572014-03-07 06:40:32 +0000200bool ChainedASTReaderListener::ReadPreprocessorOptions(
201 const PreprocessorOptions &PPOpts, bool Complain,
202 std::string &SuggestedPredefines) {
203 return First->ReadPreprocessorOptions(PPOpts, Complain,
204 SuggestedPredefines) ||
205 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
206}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000207
Ben Langmuircb69b572014-03-07 06:40:32 +0000208void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
209 unsigned Value) {
210 First->ReadCounter(M, Value);
211 Second->ReadCounter(M, Value);
212}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000213
Ben Langmuircb69b572014-03-07 06:40:32 +0000214bool ChainedASTReaderListener::needsInputFileVisitation() {
215 return First->needsInputFileVisitation() ||
216 Second->needsInputFileVisitation();
217}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000218
Ben Langmuircb69b572014-03-07 06:40:32 +0000219bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
220 return First->needsSystemInputFileVisitation() ||
221 Second->needsSystemInputFileVisitation();
222}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000223
Richard Smith216a3bd2015-08-13 17:57:10 +0000224void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
225 ModuleKind Kind) {
226 First->visitModuleFile(Filename, Kind);
227 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000228}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000229
Ben Langmuircb69b572014-03-07 06:40:32 +0000230bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000231 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000232 bool isOverridden,
233 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000234 bool Continue = false;
235 if (First->needsInputFileVisitation() &&
236 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000237 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
238 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000239 if (Second->needsInputFileVisitation() &&
240 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000241 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
242 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000243 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000244}
245
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000246void ChainedASTReaderListener::readModuleFileExtension(
247 const ModuleFileExtensionMetadata &Metadata) {
248 First->readModuleFileExtension(Metadata);
249 Second->readModuleFileExtension(Metadata);
250}
251
Guy Benyei11169dd2012-12-18 14:30:41 +0000252//===----------------------------------------------------------------------===//
253// PCH validator implementation
254//===----------------------------------------------------------------------===//
255
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000256ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000258/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000259/// language options.
260///
261/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000262/// \param AllowCompatibleDifferences If true, differences between compatible
263/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000264///
265/// \returns true if the languagae options mis-match, false otherwise.
266static bool checkLanguageOptions(const LangOptions &LangOpts,
267 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000268 DiagnosticsEngine *Diags,
269 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000270#define LANGOPT(Name, Bits, Default, Description) \
271 if (ExistingLangOpts.Name != LangOpts.Name) { \
272 if (Diags) \
273 Diags->Report(diag::err_pch_langopt_mismatch) \
274 << Description << LangOpts.Name << ExistingLangOpts.Name; \
275 return true; \
276 }
277
278#define VALUE_LANGOPT(Name, Bits, Default, Description) \
279 if (ExistingLangOpts.Name != LangOpts.Name) { \
280 if (Diags) \
281 Diags->Report(diag::err_pch_langopt_value_mismatch) \
282 << Description; \
283 return true; \
284 }
285
286#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
287 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
288 if (Diags) \
289 Diags->Report(diag::err_pch_langopt_value_mismatch) \
290 << Description; \
291 return true; \
292 }
293
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000294#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
295 if (!AllowCompatibleDifferences) \
296 LANGOPT(Name, Bits, Default, Description)
297
298#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
299 if (!AllowCompatibleDifferences) \
300 ENUM_LANGOPT(Name, Bits, Default, Description)
301
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000302#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
303 if (!AllowCompatibleDifferences) \
304 VALUE_LANGOPT(Name, Bits, Default, Description)
305
Guy Benyei11169dd2012-12-18 14:30:41 +0000306#define BENIGN_LANGOPT(Name, Bits, Default, Description)
307#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000308#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000309#include "clang/Basic/LangOptions.def"
310
Ben Langmuircd98cb72015-06-23 18:20:18 +0000311 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
312 if (Diags)
313 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
314 return true;
315 }
316
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
318 if (Diags)
319 Diags->Report(diag::err_pch_langopt_value_mismatch)
320 << "target Objective-C runtime";
321 return true;
322 }
323
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000324 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
325 LangOpts.CommentOpts.BlockCommandNames) {
326 if (Diags)
327 Diags->Report(diag::err_pch_langopt_value_mismatch)
328 << "block command names";
329 return true;
330 }
331
Vedant Kumar85a83c22017-06-01 20:01:01 +0000332 // Sanitizer feature mismatches are treated as compatible differences. If
333 // compatible differences aren't allowed, we still only want to check for
334 // mismatches of non-modular sanitizers (the only ones which can affect AST
335 // generation).
336 if (!AllowCompatibleDifferences) {
337 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
338 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
339 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
340 ExistingSanitizers.clear(ModularSanitizers);
341 ImportedSanitizers.clear(ModularSanitizers);
342 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
343 const std::string Flag = "-fsanitize=";
344 if (Diags) {
345#define SANITIZER(NAME, ID) \
346 { \
347 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
348 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
349 if (InExistingModule != InImportedModule) \
350 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
351 << InExistingModule << (Flag + NAME); \
352 }
353#include "clang/Basic/Sanitizers.def"
354 }
355 return true;
356 }
357 }
358
Guy Benyei11169dd2012-12-18 14:30:41 +0000359 return false;
360}
361
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000363/// target options.
364///
365/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
366///
367/// \returns true if the target options mis-match, false otherwise.
368static bool checkTargetOptions(const TargetOptions &TargetOpts,
369 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000370 DiagnosticsEngine *Diags,
371 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000372#define CHECK_TARGET_OPT(Field, Name) \
373 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
374 if (Diags) \
375 Diags->Report(diag::err_pch_targetopt_mismatch) \
376 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
377 return true; \
378 }
379
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000380 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000381 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000383
384 // We can tolerate different CPUs in many cases, notably when one CPU
385 // supports a strict superset of another. When allowing compatible
386 // differences skip this check.
387 if (!AllowCompatibleDifferences)
388 CHECK_TARGET_OPT(CPU, "target CPU");
389
Guy Benyei11169dd2012-12-18 14:30:41 +0000390#undef CHECK_TARGET_OPT
391
392 // Compare feature sets.
393 SmallVector<StringRef, 4> ExistingFeatures(
394 ExistingTargetOpts.FeaturesAsWritten.begin(),
395 ExistingTargetOpts.FeaturesAsWritten.end());
396 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
397 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000398 llvm::sort(ExistingFeatures);
399 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000400
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000401 // We compute the set difference in both directions explicitly so that we can
402 // diagnose the differences differently.
403 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
404 std::set_difference(
405 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
406 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
407 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
408 ExistingFeatures.begin(), ExistingFeatures.end(),
409 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000410
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000411 // If we are allowing compatible differences and the read feature set is
412 // a strict subset of the existing feature set, there is nothing to diagnose.
413 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
414 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000415
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000416 if (Diags) {
417 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000419 << /* is-existing-feature */ false << Feature;
420 for (StringRef Feature : UnmatchedExistingFeatures)
421 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
422 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 }
424
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000425 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000426}
427
428bool
429PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000430 bool Complain,
431 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 const LangOptions &ExistingLangOpts = PP.getLangOpts();
433 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000434 Complain ? &Reader.Diags : nullptr,
435 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000436}
437
438bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000439 bool Complain,
440 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
442 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000443 Complain ? &Reader.Diags : nullptr,
444 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000445}
446
447namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000448
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000449using MacroDefinitionsMap =
450 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
451using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000452
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000453} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000454
Ben Langmuirb92de022014-04-29 16:25:26 +0000455static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
456 DiagnosticsEngine &Diags,
457 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000458 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000459
460 // Check current mappings for new -Werror mappings, and the stored mappings
461 // for cases that were explicitly mapped to *not* be errors that are now
462 // errors because of options like -Werror.
463 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
464
Vedant Kumar48b4f762018-04-14 01:40:48 +0000465 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000466 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
467 diag::kind DiagID = DiagIDMappingPair.first;
468 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
469 if (CurLevel < DiagnosticsEngine::Error)
470 continue; // not significant
471 Level StoredLevel =
472 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
473 if (StoredLevel < DiagnosticsEngine::Error) {
474 if (Complain)
475 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
476 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
477 return true;
478 }
479 }
480 }
481
482 return false;
483}
484
Alp Tokerac4e8e52014-06-22 21:58:33 +0000485static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
486 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
487 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
488 return true;
489 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000490}
491
492static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
493 DiagnosticsEngine &Diags,
494 bool IsSystem, bool Complain) {
495 // Top-level options
496 if (IsSystem) {
497 if (Diags.getSuppressSystemWarnings())
498 return false;
499 // If -Wsystem-headers was not enabled before, be conservative
500 if (StoredDiags.getSuppressSystemWarnings()) {
501 if (Complain)
502 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
503 return true;
504 }
505 }
506
507 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
508 if (Complain)
509 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
510 return true;
511 }
512
513 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
514 !StoredDiags.getEnableAllWarnings()) {
515 if (Complain)
516 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
517 return true;
518 }
519
520 if (isExtHandlingFromDiagsError(Diags) &&
521 !isExtHandlingFromDiagsError(StoredDiags)) {
522 if (Complain)
523 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
524 return true;
525 }
526
527 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
528}
529
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000530/// Return the top import module if it is implicit, nullptr otherwise.
531static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
532 Preprocessor &PP) {
533 // If the original import came from a file explicitly generated by the user,
534 // don't check the diagnostic mappings.
535 // FIXME: currently this is approximated by checking whether this is not a
536 // module import of an implicitly-loaded module file.
537 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
538 // the transitive closure of its imports, since unrelated modules cannot be
539 // imported until after this module finishes validation.
540 ModuleFile *TopImport = &*ModuleMgr.rbegin();
541 while (!TopImport->ImportedBy.empty())
542 TopImport = TopImport->ImportedBy[0];
543 if (TopImport->Kind != MK_ImplicitModule)
544 return nullptr;
545
546 StringRef ModuleName = TopImport->ModuleName;
547 assert(!ModuleName.empty() && "diagnostic options read before module name");
548
549 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
550 assert(M && "missing module");
551 return M;
552}
553
Ben Langmuirb92de022014-04-29 16:25:26 +0000554bool PCHValidator::ReadDiagnosticOptions(
555 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
556 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
557 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
558 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000559 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000560 // This should never fail, because we would have processed these options
561 // before writing them to an ASTFile.
562 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
563
564 ModuleManager &ModuleMgr = Reader.getModuleManager();
565 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
566
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000567 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
568 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000569 return false;
570
Ben Langmuirb92de022014-04-29 16:25:26 +0000571 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
572 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000573 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
574 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000575}
576
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000577/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000578/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000579static void
580collectMacroDefinitions(const PreprocessorOptions &PPOpts,
581 MacroDefinitionsMap &Macros,
582 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000583 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
584 StringRef Macro = PPOpts.Macros[I].first;
585 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586
587 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
588 StringRef MacroName = MacroPair.first;
589 StringRef MacroBody = MacroPair.second;
590
591 // For an #undef'd macro, we only care about the name.
592 if (IsUndef) {
593 if (MacroNames && !Macros.count(MacroName))
594 MacroNames->push_back(MacroName);
595
596 Macros[MacroName] = std::make_pair("", true);
597 continue;
598 }
599
600 // For a #define'd macro, figure out the actual definition.
601 if (MacroName.size() == Macro.size())
602 MacroBody = "1";
603 else {
604 // Note: GCC drops anything following an end-of-line character.
605 StringRef::size_type End = MacroBody.find_first_of("\n\r");
606 MacroBody = MacroBody.substr(0, End);
607 }
608
609 if (MacroNames && !Macros.count(MacroName))
610 MacroNames->push_back(MacroName);
611 Macros[MacroName] = std::make_pair(MacroBody, false);
612 }
613}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000615/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000616/// against the preprocessor options in an existing preprocessor.
617///
618/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000619/// \param Validate If true, validate preprocessor options. If false, allow
620/// macros defined by \p ExistingPPOpts to override those defined by
621/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000622static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
623 const PreprocessorOptions &ExistingPPOpts,
624 DiagnosticsEngine *Diags,
625 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000626 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000627 const LangOptions &LangOpts,
628 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 // Check macro definitions.
630 MacroDefinitionsMap ASTFileMacros;
631 collectMacroDefinitions(PPOpts, ASTFileMacros);
632 MacroDefinitionsMap ExistingMacros;
633 SmallVector<StringRef, 4> ExistingMacroNames;
634 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
635
Vedant Kumar48b4f762018-04-14 01:40:48 +0000636 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000638 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
640
641 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000642 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
643 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000644 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 // FIXME: Check whether this identifier was referenced anywhere in the
646 // AST file. If so, we should reject the AST file. Unfortunately, this
647 // information isn't in the control block. What shall we do about it?
648
649 if (Existing.second) {
650 SuggestedPredefines += "#undef ";
651 SuggestedPredefines += MacroName.str();
652 SuggestedPredefines += '\n';
653 } else {
654 SuggestedPredefines += "#define ";
655 SuggestedPredefines += MacroName.str();
656 SuggestedPredefines += ' ';
657 SuggestedPredefines += Existing.first.str();
658 SuggestedPredefines += '\n';
659 }
660 continue;
661 }
662
663 // If the macro was defined in one but undef'd in the other, we have a
664 // conflict.
665 if (Existing.second != Known->second.second) {
666 if (Diags) {
667 Diags->Report(diag::err_pch_macro_def_undef)
668 << MacroName << Known->second.second;
669 }
670 return true;
671 }
672
673 // If the macro was #undef'd in both, or if the macro bodies are identical,
674 // it's fine.
675 if (Existing.second || Existing.first == Known->second.first)
676 continue;
677
678 // The macro bodies differ; complain.
679 if (Diags) {
680 Diags->Report(diag::err_pch_macro_def_conflict)
681 << MacroName << Known->second.first << Existing.first;
682 }
683 return true;
684 }
685
686 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000687 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 if (Diags) {
689 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
690 }
691 return true;
692 }
693
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000694 // Detailed record is important since it is used for the module cache hash.
695 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000696 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000697 if (Diags) {
698 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
699 }
700 return true;
701 }
702
Guy Benyei11169dd2012-12-18 14:30:41 +0000703 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000704 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
705 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000706
707 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
708 !ExistingPPOpts.PCHThroughHeader.empty()) {
709 // In case the through header is an include, we must add all the includes
710 // to the predefines so the start point can be determined.
711 SuggestedPredefines += "#include \"";
712 SuggestedPredefines += File;
713 SuggestedPredefines += "\"\n";
714 continue;
715 }
716
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 if (File == ExistingPPOpts.ImplicitPCHInclude)
718 continue;
719
720 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
721 != PPOpts.Includes.end())
722 continue;
723
724 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000725 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 SuggestedPredefines += "\"\n";
727 }
728
Vedant Kumar48b4f762018-04-14 01:40:48 +0000729 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
730 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000731 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
732 File)
733 != PPOpts.MacroIncludes.end())
734 continue;
735
736 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000737 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 SuggestedPredefines += "\"\n##\n";
739 }
740
741 return false;
742}
743
744bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
745 bool Complain,
746 std::string &SuggestedPredefines) {
747 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
748
749 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000750 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000752 SuggestedPredefines,
753 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000754}
755
Yaxun Liu43712e02016-09-07 18:40:20 +0000756bool SimpleASTReaderListener::ReadPreprocessorOptions(
757 const PreprocessorOptions &PPOpts,
758 bool Complain,
759 std::string &SuggestedPredefines) {
760 return checkPreprocessorOptions(PPOpts,
761 PP.getPreprocessorOpts(),
762 nullptr,
763 PP.getFileManager(),
764 SuggestedPredefines,
765 PP.getLangOpts(),
766 false);
767}
768
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000769/// Check the header search options deserialized from the control block
770/// against the header search options in an existing preprocessor.
771///
772/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
773static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
774 StringRef SpecificModuleCachePath,
775 StringRef ExistingModuleCachePath,
776 DiagnosticsEngine *Diags,
777 const LangOptions &LangOpts) {
778 if (LangOpts.Modules) {
779 if (SpecificModuleCachePath != ExistingModuleCachePath) {
780 if (Diags)
781 Diags->Report(diag::err_pch_modulecache_mismatch)
782 << SpecificModuleCachePath << ExistingModuleCachePath;
783 return true;
784 }
785 }
786
787 return false;
788}
789
790bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
791 StringRef SpecificModuleCachePath,
792 bool Complain) {
793 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
794 PP.getHeaderSearchInfo().getModuleCachePath(),
795 Complain ? &Reader.Diags : nullptr,
796 PP.getLangOpts());
797}
798
Guy Benyei11169dd2012-12-18 14:30:41 +0000799void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
800 PP.setCounterValue(Value);
801}
802
803//===----------------------------------------------------------------------===//
804// AST reader implementation
805//===----------------------------------------------------------------------===//
806
Nico Weber824285e2014-05-08 04:26:47 +0000807void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
808 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000810 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000811}
812
Guy Benyei11169dd2012-12-18 14:30:41 +0000813unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
814 return serialization::ComputeHash(Sel);
815}
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817std::pair<unsigned, unsigned>
818ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000819 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000820
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
822 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 return std::make_pair(KeyLen, DataLen);
824}
825
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000826ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000827ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000828 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000829
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000831 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
832 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
833 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 if (N == 0)
835 return SelTable.getNullarySelector(FirstII);
836 else if (N == 1)
837 return SelTable.getUnarySelector(FirstII);
838
839 SmallVector<IdentifierInfo *, 16> Args;
840 Args.push_back(FirstII);
841 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000842 Args.push_back(Reader.getLocalIdentifier(
843 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000844
845 return SelTable.getSelector(N, Args.data());
846}
847
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000848ASTSelectorLookupTrait::data_type
849ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000851 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000852
853 data_type Result;
854
Justin Bogner57ba0b22014-03-28 22:03:24 +0000855 Result.ID = Reader.getGlobalSelectorID(
856 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000857 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
858 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
859 Result.InstanceBits = FullInstanceBits & 0x3;
860 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
861 Result.FactoryBits = FullFactoryBits & 0x3;
862 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
863 unsigned NumInstanceMethods = FullInstanceBits >> 3;
864 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000865
866 // Load instance methods
867 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000868 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000869 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 Result.Instance.push_back(Method);
871 }
872
873 // Load factory methods
874 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000875 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000876 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 Result.Factory.push_back(Method);
878 }
879
880 return Result;
881}
882
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000883unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000884 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000885}
886
887std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000888ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000889 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000890
Justin Bogner57ba0b22014-03-28 22:03:24 +0000891 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
892 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 return std::make_pair(KeyLen, DataLen);
894}
895
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000896ASTIdentifierLookupTraitBase::internal_key_type
897ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000898 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000899 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000900}
901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000902/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000903static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
904 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000905 return II.hadMacroDefinition() ||
906 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000907 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000908 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000909 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000910 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000911}
912
Richard Smith76c2f2c2015-07-17 20:09:43 +0000913static bool readBit(unsigned &Bits) {
914 bool Value = Bits & 0x1;
915 Bits >>= 1;
916 return Value;
917}
918
Richard Smith79bf9202015-08-24 03:33:22 +0000919IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
920 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000921
Richard Smith79bf9202015-08-24 03:33:22 +0000922 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
923 return Reader.getGlobalIdentifierID(F, RawID >> 1);
924}
925
Richard Smitheb4b58f62016-02-05 01:40:54 +0000926static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
927 if (!II.isFromAST()) {
928 II.setIsFromAST();
929 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
930 if (isInterestingIdentifier(Reader, II, IsModule))
931 II.setChangedSinceDeserialization();
932 }
933}
934
Guy Benyei11169dd2012-12-18 14:30:41 +0000935IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
936 const unsigned char* d,
937 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000938 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000939
Justin Bogner57ba0b22014-03-28 22:03:24 +0000940 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 bool IsInteresting = RawID & 0x01;
942
943 // Wipe out the "is interesting" bit.
944 RawID = RawID >> 1;
945
Richard Smith76c2f2c2015-07-17 20:09:43 +0000946 // Build the IdentifierInfo and link the identifier ID with it.
947 IdentifierInfo *II = KnownII;
948 if (!II) {
949 II = &Reader.getIdentifierTable().getOwn(k);
950 KnownII = II;
951 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000952 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000953 Reader.markIdentifierUpToDate(II);
954
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
956 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000957 // For uninteresting identifiers, there's nothing else to do. Just notify
958 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 return II;
961 }
962
Justin Bogner57ba0b22014-03-28 22:03:24 +0000963 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
964 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000965 bool CPlusPlusOperatorKeyword = readBit(Bits);
966 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000967 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000968 bool Poisoned = readBit(Bits);
969 bool ExtensionToken = readBit(Bits);
970 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971
972 assert(Bits == 0 && "Extra bits in the identifier?");
973 DataLen -= 8;
974
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 // Set or check the various bits in the IdentifierInfo structure.
976 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000977 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000978 II->revertTokenIDToIdentifier();
979 if (!F.isModule())
980 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
981 else if (HasRevertedBuiltin && II->getBuiltinID()) {
982 II->revertBuiltin();
983 assert((II->hasRevertedBuiltin() ||
984 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
985 "Incorrect ObjC keyword or builtin ID");
986 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 assert(II->isExtensionToken() == ExtensionToken &&
988 "Incorrect extension token flag");
989 (void)ExtensionToken;
990 if (Poisoned)
991 II->setIsPoisoned(true);
992 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
993 "Incorrect C++ operator keyword flag");
994 (void)CPlusPlusOperatorKeyword;
995
996 // If this identifier is a macro, deserialize the macro
997 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000998 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000999 uint32_t MacroDirectivesOffset =
1000 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001001 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001002
Richard Smithd7329392015-04-21 21:46:32 +00001003 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 Reader.SetIdentifierInfo(ID, II);
1007
1008 // Read all of the declarations visible at global scope with this
1009 // name.
1010 if (DataLen > 0) {
1011 SmallVector<uint32_t, 4> DeclIDs;
1012 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001013 DeclIDs.push_back(Reader.getGlobalDeclID(
1014 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1016 }
1017
1018 return II;
1019}
1020
Richard Smitha06c7e62015-08-26 23:55:49 +00001021DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1022 : Kind(Name.getNameKind()) {
1023 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 break;
1027 case DeclarationName::ObjCZeroArgSelector:
1028 case DeclarationName::ObjCOneArgSelector:
1029 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001030 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 break;
1032 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001033 Data = Name.getCXXOverloadedOperator();
1034 break;
1035 case DeclarationName::CXXLiteralOperatorName:
1036 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1037 break;
Richard Smith35845152017-02-07 01:37:30 +00001038 case DeclarationName::CXXDeductionGuideName:
1039 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1040 ->getDeclName().getAsIdentifierInfo();
1041 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001042 case DeclarationName::CXXConstructorName:
1043 case DeclarationName::CXXDestructorName:
1044 case DeclarationName::CXXConversionFunctionName:
1045 case DeclarationName::CXXUsingDirective:
1046 Data = 0;
1047 break;
1048 }
1049}
1050
1051unsigned DeclarationNameKey::getHash() const {
1052 llvm::FoldingSetNodeID ID;
1053 ID.AddInteger(Kind);
1054
1055 switch (Kind) {
1056 case DeclarationName::Identifier:
1057 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001058 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001059 ID.AddString(((IdentifierInfo*)Data)->getName());
1060 break;
1061 case DeclarationName::ObjCZeroArgSelector:
1062 case DeclarationName::ObjCOneArgSelector:
1063 case DeclarationName::ObjCMultiArgSelector:
1064 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1065 break;
1066 case DeclarationName::CXXOperatorName:
1067 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001068 break;
1069 case DeclarationName::CXXConstructorName:
1070 case DeclarationName::CXXDestructorName:
1071 case DeclarationName::CXXConversionFunctionName:
1072 case DeclarationName::CXXUsingDirective:
1073 break;
1074 }
1075
1076 return ID.ComputeHash();
1077}
1078
Richard Smithd88a7f12015-09-01 20:35:42 +00001079ModuleFile *
1080ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1081 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001082
Richard Smithd88a7f12015-09-01 20:35:42 +00001083 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1084 return Reader.getLocalModuleFile(F, ModuleFileID);
1085}
1086
Guy Benyei11169dd2012-12-18 14:30:41 +00001087std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001088ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001089 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001090
Justin Bogner57ba0b22014-03-28 22:03:24 +00001091 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1092 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 return std::make_pair(KeyLen, DataLen);
1094}
1095
Richard Smitha06c7e62015-08-26 23:55:49 +00001096ASTDeclContextNameLookupTrait::internal_key_type
1097ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001098 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001099
Vedant Kumar48b4f762018-04-14 01:40:48 +00001100 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001101 uint64_t Data;
1102 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001104 case DeclarationName::CXXLiteralOperatorName:
1105 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001106 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001107 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 break;
1109 case DeclarationName::ObjCZeroArgSelector:
1110 case DeclarationName::ObjCOneArgSelector:
1111 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001112 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001113 (uint64_t)Reader.getLocalSelector(
1114 F, endian::readNext<uint32_t, little, unaligned>(
1115 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 break;
1117 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001118 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 case DeclarationName::CXXConstructorName:
1121 case DeclarationName::CXXDestructorName:
1122 case DeclarationName::CXXConversionFunctionName:
1123 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001124 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 break;
1126 }
1127
Richard Smitha06c7e62015-08-26 23:55:49 +00001128 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001129}
1130
Richard Smithd88a7f12015-09-01 20:35:42 +00001131void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1132 const unsigned char *d,
1133 unsigned DataLen,
1134 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001135 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001136
Richard Smithd88a7f12015-09-01 20:35:42 +00001137 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1138 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1139 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1140 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001141}
1142
Richard Smith0f4e2c42015-08-06 04:23:48 +00001143bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1144 BitstreamCursor &Cursor,
1145 uint64_t Offset,
1146 DeclContext *DC) {
1147 assert(Offset != 0);
1148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001150 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001151
Richard Smith0f4e2c42015-08-06 04:23:48 +00001152 RecordData Record;
1153 StringRef Blob;
1154 unsigned Code = Cursor.ReadCode();
1155 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1156 if (RecCode != DECL_CONTEXT_LEXICAL) {
1157 Error("Expected lexical block");
1158 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 }
1160
Richard Smith82f8fcd2015-08-06 22:07:25 +00001161 assert(!isa<TranslationUnitDecl>(DC) &&
1162 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001163 // If we are handling a C++ class template instantiation, we can see multiple
1164 // lexical updates for the same record. It's important that we select only one
1165 // of them, so that field numbering works properly. Just pick the first one we
1166 // see.
1167 auto &Lex = LexicalDecls[DC];
1168 if (!Lex.first) {
1169 Lex = std::make_pair(
1170 &M, llvm::makeArrayRef(
1171 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1172 Blob.data()),
1173 Blob.size() / 4));
1174 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001175 DC->setHasExternalLexicalStorage(true);
1176 return false;
1177}
Guy Benyei11169dd2012-12-18 14:30:41 +00001178
Richard Smith0f4e2c42015-08-06 04:23:48 +00001179bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1180 BitstreamCursor &Cursor,
1181 uint64_t Offset,
1182 DeclID ID) {
1183 assert(Offset != 0);
1184
1185 SavedStreamPosition SavedPosition(Cursor);
1186 Cursor.JumpToBit(Offset);
1187
1188 RecordData Record;
1189 StringRef Blob;
1190 unsigned Code = Cursor.ReadCode();
1191 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1192 if (RecCode != DECL_CONTEXT_VISIBLE) {
1193 Error("Expected visible lookup table block");
1194 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 }
1196
Richard Smith0f4e2c42015-08-06 04:23:48 +00001197 // We can't safely determine the primary context yet, so delay attaching the
1198 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001199 auto *Data = (const unsigned char*)Blob.data();
1200 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 return false;
1202}
1203
Richard Smith37a93df2017-02-18 00:32:02 +00001204void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001206 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001207 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001208 Diag(diag::note_module_cache_path)
1209 << PP.getHeaderSearchInfo().getModuleCachePath();
1210 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001211}
1212
1213void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001214 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 if (Diags.isDiagnosticInFlight())
1216 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1217 else
1218 Diag(DiagID) << Arg1 << Arg2;
1219}
1220
1221//===----------------------------------------------------------------------===//
1222// Source Manager Deserialization
1223//===----------------------------------------------------------------------===//
1224
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001225/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001226/// \returns true if there was an error.
1227bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001228 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 unsigned Idx = 0;
1230 LineTableInfo &LineTable = SourceMgr.getLineTable();
1231
1232 // Parse the file names
1233 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001234 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001235 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001236 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001237 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1239 }
Richard Smith63078492015-09-01 07:41:55 +00001240 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001241
1242 // Parse the line entries
1243 std::vector<LineEntry> Entries;
1244 while (Idx < Record.size()) {
1245 int FID = Record[Idx++];
1246 assert(FID >= 0 && "Serialized line entries for non-local file.");
1247 // Remap FileID from 1-based old view.
1248 FID += F.SLocEntryBaseID - 1;
1249
1250 // Extract the line entries
1251 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001252 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 Entries.clear();
1254 Entries.reserve(NumEntries);
1255 for (unsigned I = 0; I != NumEntries; ++I) {
1256 unsigned FileOffset = Record[Idx++];
1257 unsigned LineNo = Record[Idx++];
1258 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001259 SrcMgr::CharacteristicKind FileKind
1260 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001261 unsigned IncludeOffset = Record[Idx++];
1262 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1263 FileKind, IncludeOffset));
1264 }
1265 LineTable.AddEntry(FileID::get(FID), Entries);
1266 }
1267
1268 return false;
1269}
1270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001271/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001272bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1273 using namespace SrcMgr;
1274
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001275 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001276
1277 // Set the source-location entry cursor to the current position in
1278 // the stream. This cursor will be used to read the contents of the
1279 // source manager block initially, and then lazily read
1280 // source-location entries as needed.
1281 SLocEntryCursor = F.Stream;
1282
1283 // The stream itself is going to skip over the source manager block.
1284 if (F.Stream.SkipBlock()) {
1285 Error("malformed block record in AST file");
1286 return true;
1287 }
1288
1289 // Enter the source manager block.
1290 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1291 Error("malformed source manager block record in AST file");
1292 return true;
1293 }
1294
1295 RecordData Record;
1296 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001297 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001298
Chris Lattnere7b154b2013-01-19 21:39:22 +00001299 switch (E.Kind) {
1300 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1301 case llvm::BitstreamEntry::Error:
1302 Error("malformed block record in AST file");
1303 return true;
1304 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001306 case llvm::BitstreamEntry::Record:
1307 // The interesting case.
1308 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001313 StringRef Blob;
1314 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 default: // Default behavior: ignore.
1316 break;
1317
1318 case SM_SLOC_FILE_ENTRY:
1319 case SM_SLOC_BUFFER_ENTRY:
1320 case SM_SLOC_EXPANSION_ENTRY:
1321 // Once we hit one of the source location entries, we're done.
1322 return false;
1323 }
1324 }
1325}
1326
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001327/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001328/// and the PCH file was moved from its original location, try to resolve the
1329/// file by assuming that header+PCH were moved together and the header is in
1330/// the same place relative to the PCH.
1331static std::string
1332resolveFileRelativeToOriginalDir(const std::string &Filename,
1333 const std::string &OriginalDir,
1334 const std::string &CurrDir) {
1335 assert(OriginalDir != CurrDir &&
1336 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001337
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001339
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 SmallString<128> filePath(Filename);
1341 fs::make_absolute(filePath);
1342 assert(path::is_absolute(OriginalDir));
1343 SmallString<128> currPCHPath(CurrDir);
1344
1345 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1346 fileDirE = path::end(path::parent_path(filePath));
1347 path::const_iterator origDirI = path::begin(OriginalDir),
1348 origDirE = path::end(OriginalDir);
1349 // Skip the common path components from filePath and OriginalDir.
1350 while (fileDirI != fileDirE && origDirI != origDirE &&
1351 *fileDirI == *origDirI) {
1352 ++fileDirI;
1353 ++origDirI;
1354 }
1355 for (; origDirI != origDirE; ++origDirI)
1356 path::append(currPCHPath, "..");
1357 path::append(currPCHPath, fileDirI, fileDirE);
1358 path::append(currPCHPath, path::filename(Filename));
1359 return currPCHPath.str();
1360}
1361
1362bool ASTReader::ReadSLocEntry(int ID) {
1363 if (ID == 0)
1364 return false;
1365
1366 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1367 Error("source location entry ID out-of-range for AST file");
1368 return true;
1369 }
1370
Richard Smithaada85c2016-02-06 02:06:43 +00001371 // Local helper to read the (possibly-compressed) buffer data following the
1372 // entry record.
1373 auto ReadBuffer = [this](
1374 BitstreamCursor &SLocEntryCursor,
1375 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1376 RecordData Record;
1377 StringRef Blob;
1378 unsigned Code = SLocEntryCursor.ReadCode();
1379 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1380
1381 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001382 if (!llvm::zlib::isAvailable()) {
1383 Error("zlib is not available");
1384 return nullptr;
1385 }
Richard Smithaada85c2016-02-06 02:06:43 +00001386 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001387 if (llvm::Error E =
1388 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1389 Error("could not decompress embedded file contents: " +
1390 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001391 return nullptr;
1392 }
1393 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1394 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1395 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1396 } else {
1397 Error("AST record has invalid code");
1398 return nullptr;
1399 }
1400 };
1401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1403 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001404 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 unsigned BaseOffset = F->SLocEntryBaseOffset;
1406
1407 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001408 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1409 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 Error("incorrectly-formatted source location entry in AST file");
1411 return true;
1412 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001413
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001415 StringRef Blob;
1416 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 default:
1418 Error("incorrectly-formatted source location entry in AST file");
1419 return true;
1420
1421 case SM_SLOC_FILE_ENTRY: {
1422 // We will detect whether a file changed and return 'Failure' for it, but
1423 // we will also try to fail gracefully by setting up the SLocEntry.
1424 unsigned InputID = Record[4];
1425 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001426 const FileEntry *File = IF.getFile();
1427 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001428
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001429 // Note that we only check if a File was returned. If it was out-of-date
1430 // we have complained but we will continue creating a FileID to recover
1431 // gracefully.
1432 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 return true;
1434
1435 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1436 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1437 // This is the module's main file.
1438 IncludeLoc = getImportLocation(F);
1439 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001440 SrcMgr::CharacteristicKind
1441 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1443 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001444 SrcMgr::FileInfo &FileInfo =
1445 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 FileInfo.NumCreatedFIDs = Record[5];
1447 if (Record[3])
1448 FileInfo.setHasLineDirectives();
1449
1450 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1451 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001452 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1454 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1455 NumFileDecls));
1456 }
Richard Smithaada85c2016-02-06 02:06:43 +00001457
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001459 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001461 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1462 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001463 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1464 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001465 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001466 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 }
1468
1469 break;
1470 }
1471
1472 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001473 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001475 SrcMgr::CharacteristicKind
1476 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001478 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 IncludeLoc = getImportLocation(F);
1480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Richard Smithaada85c2016-02-06 02:06:43 +00001482 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1483 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001485 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001486 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001487 break;
1488 }
1489
1490 case SM_SLOC_EXPANSION_ENTRY: {
1491 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1492 SourceMgr.createExpansionLoc(SpellingLoc,
1493 ReadSourceLocation(*F, Record[2]),
1494 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001495 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 Record[4],
1497 ID,
1498 BaseOffset + Record[0]);
1499 break;
1500 }
1501 }
1502
1503 return false;
1504}
1505
1506std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1507 if (ID == 0)
1508 return std::make_pair(SourceLocation(), "");
1509
1510 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1511 Error("source location entry ID out-of-range for AST file");
1512 return std::make_pair(SourceLocation(), "");
1513 }
1514
1515 // Find which module file this entry lands in.
1516 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001517 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 return std::make_pair(SourceLocation(), "");
1519
1520 // FIXME: Can we map this down to a particular submodule? That would be
1521 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001522 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001523}
1524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001525/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001526SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1527 if (F->ImportLoc.isValid())
1528 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001529
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 // Otherwise we have a PCH. It's considered to be "imported" at the first
1531 // location of its includer.
1532 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001533 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001534 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001535 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 return F->ImportedBy[0]->FirstLoc;
1538}
1539
1540/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1541/// specified cursor. Read the abbreviations that are at the top of the block
1542/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001543bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001544 if (Cursor.EnterSubBlock(BlockID))
1545 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001546
1547 while (true) {
1548 uint64_t Offset = Cursor.GetCurrentBitNo();
1549 unsigned Code = Cursor.ReadCode();
1550
1551 // We expect all abbrevs to be at the start of the block.
1552 if (Code != llvm::bitc::DEFINE_ABBREV) {
1553 Cursor.JumpToBit(Offset);
1554 return false;
1555 }
1556 Cursor.ReadAbbrevRecord();
1557 }
1558}
1559
Richard Smithe40f2ba2013-08-07 21:41:30 +00001560Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001561 unsigned &Idx) {
1562 Token Tok;
1563 Tok.startToken();
1564 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1565 Tok.setLength(Record[Idx++]);
1566 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1567 Tok.setIdentifierInfo(II);
1568 Tok.setKind((tok::TokenKind)Record[Idx++]);
1569 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1570 return Tok;
1571}
1572
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001573MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001574 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001575
1576 // Keep track of where we are in the stream, then jump back there
1577 // after reading this macro.
1578 SavedStreamPosition SavedPosition(Stream);
1579
1580 Stream.JumpToBit(Offset);
1581 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001582 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001583 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001584
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001586 // Advance to the next record, but if we get to the end of the block, don't
1587 // pop it (removing all the abbreviations from the cursor) since we want to
1588 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001589 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001590 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001591
Chris Lattnerefa77172013-01-20 00:00:22 +00001592 switch (Entry.Kind) {
1593 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1594 case llvm::BitstreamEntry::Error:
1595 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001596 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001597 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001598 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001599 case llvm::BitstreamEntry::Record:
1600 // The interesting case.
1601 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 }
1603
1604 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 Record.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00001606 PreprocessorRecordTypes RecType =
1607 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001608 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001609 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001610 case PP_MACRO_DIRECTIVE_HISTORY:
1611 return Macro;
1612
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 case PP_MACRO_OBJECT_LIKE:
1614 case PP_MACRO_FUNCTION_LIKE: {
1615 // If we already have a macro, that means that we've hit the end
1616 // of the definition of the macro we were looking for. We're
1617 // done.
1618 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001619 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001621 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001623 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001624 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001626 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001627
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1629 // Decode function-like macro info.
1630 bool isC99VarArgs = Record[NextIndex++];
1631 bool isGNUVarArgs = Record[NextIndex++];
1632 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001633 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 unsigned NumArgs = Record[NextIndex++];
1635 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001636 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001637
1638 // Install function-like macro info.
1639 MI->setIsFunctionLike();
1640 if (isC99VarArgs) MI->setIsC99Varargs();
1641 if (isGNUVarArgs) MI->setIsGNUVarargs();
1642 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001643 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 }
1645
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 // Remember that we saw this macro last so that we add the tokens that
1647 // form its body to it.
1648 Macro = MI;
1649
1650 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1651 Record[NextIndex]) {
1652 // We have a macro definition. Register the association
1653 PreprocessedEntityID
1654 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1655 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001656 PreprocessingRecord::PPEntityID PPID =
1657 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001658 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001659 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001660 if (PPDef)
1661 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 }
1663
1664 ++NumMacrosRead;
1665 break;
1666 }
1667
1668 case PP_TOKEN: {
1669 // If we see a TOKEN before a PP_MACRO_*, then the file is
1670 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001671 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001672
John McCallf413f5e2013-05-03 00:10:13 +00001673 unsigned Idx = 0;
1674 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001675 Macro->AddTokenToBody(Tok);
1676 break;
1677 }
1678 }
1679 }
1680}
1681
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001682PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001683ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1684 unsigned LocalID) const {
1685 if (!M.ModuleOffsetMap.empty())
1686 ReadModuleOffsetMap(M);
1687
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001688 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001690 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001691 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 return LocalID + I->second;
1694}
1695
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001696unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1697 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001698}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001699
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001700HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001701HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001702 internal_key_type ikey = {FE->getSize(),
1703 M.HasTimestamps ? FE->getModificationTime() : 0,
1704 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001705 return ikey;
1706}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001707
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001708bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001709 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 return false;
1711
Mehdi Amini004b9c72016-10-10 22:52:47 +00001712 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001713 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001714
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001716 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001717 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1718 if (!Key.Imported)
1719 return FileMgr.getFile(Key.Filename);
1720
1721 std::string Resolved = Key.Filename;
1722 Reader.ResolveImportedPath(M, Resolved);
1723 return FileMgr.getFile(Resolved);
1724 };
1725
1726 const FileEntry *FEA = GetFile(a);
1727 const FileEntry *FEB = GetFile(b);
1728 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001729}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001730
Guy Benyei11169dd2012-12-18 14:30:41 +00001731std::pair<unsigned, unsigned>
1732HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001733 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001734
Vedant Kumar48b4f762018-04-14 01:40:48 +00001735 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1736 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001737 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001738}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001739
1740HeaderFileInfoTrait::internal_key_type
1741HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001742 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001743
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001744 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001745 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1746 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001747 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001748 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001749 return ikey;
1750}
1751
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001752HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001753HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001755 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001756
1757 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 HeaderFileInfo HFI;
1759 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001760 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001761 HFI.isImport |= (Flags >> 5) & 0x01;
1762 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1763 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001765 // FIXME: Find a better way to handle this. Maybe just store a
1766 // "has been included" flag?
1767 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1768 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001769 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1770 M, endian::readNext<uint32_t, little, unaligned>(d));
1771 if (unsigned FrameworkOffset =
1772 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001773 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 // since 0 is used as an indicator for "no framework name".
1775 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1776 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1777 }
Richard Smith386bb072015-08-18 23:42:23 +00001778
1779 assert((End - d) % 4 == 0 &&
1780 "Wrong data length in HeaderFileInfo deserialization");
1781 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001782 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001783 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1784 LocalSMID >>= 2;
1785
1786 // This header is part of a module. Associate it with the module to enable
1787 // implicit module import.
1788 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1789 Module *Mod = Reader.getSubmodule(GlobalSMID);
1790 FileManager &FileMgr = Reader.getFileManager();
1791 ModuleMap &ModMap =
1792 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1793
1794 std::string Filename = key.Filename;
1795 if (key.Imported)
1796 Reader.ResolveImportedPath(M, Filename);
1797 // FIXME: This is not always the right filename-as-written, but we're not
1798 // going to use this information to rebuild the module, so it doesn't make
1799 // a lot of difference.
1800 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001801 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1802 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001803 }
1804
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 // This HeaderFileInfo was externally loaded.
1806 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001807 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return HFI;
1809}
1810
Richard Smithd7329392015-04-21 21:46:32 +00001811void ASTReader::addPendingMacro(IdentifierInfo *II,
1812 ModuleFile *M,
1813 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001814 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1815 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001816}
1817
1818void ASTReader::ReadDefinedMacros() {
1819 // Note that we are loading defined macros.
1820 Deserializing Macros(this);
1821
Vedant Kumar48b4f762018-04-14 01:40:48 +00001822 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001823 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001824
1825 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001826 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 continue;
1828
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001829 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001830 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001831
1832 RecordData Record;
1833 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001834 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001835
Chris Lattnere7b154b2013-01-19 21:39:22 +00001836 switch (E.Kind) {
1837 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1838 case llvm::BitstreamEntry::Error:
1839 Error("malformed block record in AST file");
1840 return;
1841 case llvm::BitstreamEntry::EndBlock:
1842 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001843
Chris Lattnere7b154b2013-01-19 21:39:22 +00001844 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001845 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001846 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001847 default: // Default behavior: ignore.
1848 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001849
Chris Lattnere7b154b2013-01-19 21:39:22 +00001850 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001851 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001852 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001853 if (II->isOutOfDate())
1854 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001855 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001856 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001857
Chris Lattnere7b154b2013-01-19 21:39:22 +00001858 case PP_TOKEN:
1859 // Ignore tokens.
1860 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 break;
1863 }
1864 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001865 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 }
1867}
1868
1869namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001871 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 class IdentifierLookupVisitor {
1873 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001874 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001876 unsigned &NumIdentifierLookups;
1877 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001878 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001879
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001881 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1882 unsigned &NumIdentifierLookups,
1883 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001884 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1885 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001886 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001887 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001888
1889 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001891 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001893
Vedant Kumar48b4f762018-04-14 01:40:48 +00001894 ASTIdentifierLookupTable *IdTable
1895 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 if (!IdTable)
1897 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001898
1899 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001900 Found);
1901 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001902 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001903 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 if (Pos == IdTable->end())
1905 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001906
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 // Dereferencing the iterator has the effect of building the
1908 // IdentifierInfo node and populating it with the various
1909 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001910 ++NumIdentifierLookupHits;
1911 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 return true;
1913 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001914
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001915 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 // files.
1917 IdentifierInfo *getIdentifierInfo() const { return Found; }
1918 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001919
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001920} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001921
1922void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1923 // Note that we are loading an identifier.
1924 Deserializing AnIdentifier(this);
1925
1926 unsigned PriorGeneration = 0;
1927 if (getContext().getLangOpts().Modules)
1928 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001929
1930 // If there is a global index, look there first to determine which modules
1931 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001932 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001933 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001934 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001935 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1936 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001937 }
1938 }
1939
Douglas Gregor7211ac12013-01-25 23:32:03 +00001940 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001941 NumIdentifierLookups,
1942 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001943 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001944 markIdentifierUpToDate(&II);
1945}
1946
1947void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1948 if (!II)
1949 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001950
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 II->setOutOfDate(false);
1952
1953 // Update the generation for this identifier.
1954 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001955 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001956}
1957
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001958void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1959 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001960 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001961
1962 BitstreamCursor &Cursor = M.MacroCursor;
1963 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001964 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001965
Richard Smith713369b2015-04-23 20:40:50 +00001966 struct ModuleMacroRecord {
1967 SubmoduleID SubModID;
1968 MacroInfo *MI;
1969 SmallVector<SubmoduleID, 8> Overrides;
1970 };
1971 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001972
Richard Smithd7329392015-04-21 21:46:32 +00001973 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1974 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1975 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001976 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001977 while (true) {
1978 llvm::BitstreamEntry Entry =
1979 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1980 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1981 Error("malformed block record in AST file");
1982 return;
1983 }
1984
1985 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001986 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001987 case PP_MACRO_DIRECTIVE_HISTORY:
1988 break;
1989
1990 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001991 ModuleMacros.push_back(ModuleMacroRecord());
1992 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001993 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1994 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001995 for (int I = 2, N = Record.size(); I != N; ++I)
1996 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001997 continue;
1998 }
1999
2000 default:
2001 Error("malformed block record in AST file");
2002 return;
2003 }
2004
2005 // We found the macro directive history; that's the last record
2006 // for this macro.
2007 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002008 }
2009
Richard Smithd7329392015-04-21 21:46:32 +00002010 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002011 {
2012 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002013 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002014 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002015 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002016 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002017 Module *Mod = getSubmodule(ModID);
2018 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002019 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002020 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002021 }
2022
2023 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002024 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002025 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002026 }
2027 }
2028
2029 // Don't read the directive history for a module; we don't have anywhere
2030 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002031 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002032 return;
2033
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002034 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002035 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002036 unsigned Idx = 0, N = Record.size();
2037 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002038 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002039 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002040 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002041 switch (K) {
2042 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002043 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002044 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002045 break;
2046 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002047 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002048 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002049 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002050 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002051 bool isPublic = Record[Idx++];
2052 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2053 break;
2054 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002055
2056 if (!Latest)
2057 Latest = MD;
2058 if (Earliest)
2059 Earliest->setPrevious(MD);
2060 Earliest = MD;
2061 }
2062
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002063 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002064 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002065}
2066
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002067ASTReader::InputFileInfo
2068ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002069 // Go find this input file.
2070 BitstreamCursor &Cursor = F.InputFilesCursor;
2071 SavedStreamPosition SavedPosition(Cursor);
2072 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2073
2074 unsigned Code = Cursor.ReadCode();
2075 RecordData Record;
2076 StringRef Blob;
2077
2078 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2079 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2080 "invalid record type for input file");
2081 (void)Result;
2082
2083 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002084 InputFileInfo R;
2085 R.StoredSize = static_cast<off_t>(Record[1]);
2086 R.StoredTime = static_cast<time_t>(Record[2]);
2087 R.Overridden = static_cast<bool>(Record[3]);
2088 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002089 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002090 R.Filename = Blob;
2091 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002092 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002093}
2094
Manman Renc8c94152016-10-21 23:35:03 +00002095static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002096InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 // If this ID is bogus, just return an empty input file.
2098 if (ID == 0 || ID > F.InputFilesLoaded.size())
2099 return InputFile();
2100
2101 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002102 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 return F.InputFilesLoaded[ID-1];
2104
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002105 if (F.InputFilesLoaded[ID-1].isNotFound())
2106 return InputFile();
2107
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002109 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 SavedStreamPosition SavedPosition(Cursor);
2111 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002112
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002113 InputFileInfo FI = readInputFileInfo(F, ID);
2114 off_t StoredSize = FI.StoredSize;
2115 time_t StoredTime = FI.StoredTime;
2116 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002117 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002118 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002119
Richard Smitha8cfffa2015-11-26 02:04:16 +00002120 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002121 // If we didn't find the file, resolve it relative to the
2122 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002123 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2124 F.OriginalDir != F.BaseDirectory) {
2125 std::string Resolved = resolveFileRelativeToOriginalDir(
2126 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002127 if (!Resolved.empty())
2128 File = FileMgr.getFile(Resolved);
2129 }
2130
2131 // For an overridden file, create a virtual file with the stored
2132 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002133 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002135
Craig Toppera13603a2014-05-22 05:54:18 +00002136 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002137 if (Complain) {
2138 std::string ErrorStr = "could not find file '";
2139 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002140 ErrorStr += "' referenced by AST file '";
2141 ErrorStr += F.FileName;
2142 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002143 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 // Record that we didn't find the file.
2146 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2147 return InputFile();
2148 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002149
Ben Langmuir198c1682014-03-07 07:27:49 +00002150 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002151 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002152 // can lead to problems when lexing using the source locations from the
2153 // PCH.
2154 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002155 // FIXME: Reject if the overrides are different.
2156 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002157 if (Complain)
2158 Error(diag::err_fe_pch_file_overridden, Filename);
2159 // After emitting the diagnostic, recover by disabling the override so
2160 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002161 //
2162 // FIXME: This recovery is just as broken as the original state; there may
2163 // be another precompiled module that's using the overridden contents, or
2164 // we might be half way through parsing it. Instead, we should treat the
2165 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002166 SM.disableFileContentsOverride(File);
2167 // The FileEntry is a virtual file entry with the size of the contents
2168 // that would override the original contents. Set it to the original's
2169 // size/time.
2170 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2171 StoredSize, StoredTime);
2172 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002173
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 bool IsOutOfDate = false;
2175
2176 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002177 if (!Overridden && //
2178 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002179 (StoredTime && StoredTime != File->getModificationTime() &&
2180 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002181 )) {
2182 if (Complain) {
2183 // Build a list of the PCH imports that got us here (in reverse).
2184 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002185 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002186 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002187
Ben Langmuir198c1682014-03-07 07:27:49 +00002188 // The top-level PCH is stale.
2189 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002190 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2191 if (DiagnosticKind == 0)
2192 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2193 else if (DiagnosticKind == 1)
2194 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2195 else
2196 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002197
Ben Langmuir198c1682014-03-07 07:27:49 +00002198 // Print the import stack.
2199 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2200 Diag(diag::note_pch_required_by)
2201 << Filename << ImportStack[0]->FileName;
2202 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002203 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002204 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002205 }
2206
Ben Langmuir198c1682014-03-07 07:27:49 +00002207 if (!Diags.isDiagnosticInFlight())
2208 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 }
2210
Ben Langmuir198c1682014-03-07 07:27:49 +00002211 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002213 // FIXME: If the file is overridden and we've already opened it,
2214 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002215
Richard Smitha8cfffa2015-11-26 02:04:16 +00002216 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002217
2218 // Note that we've loaded this input file.
2219 F.InputFilesLoaded[ID-1] = IF;
2220 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221}
2222
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002223/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002224/// is not an absolute path, add the system or module root to the beginning of
2225/// the file name.
2226void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2227 // Resolve relative to the base directory, if we have one.
2228 if (!M.BaseDirectory.empty())
2229 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002230}
2231
Richard Smith7ed1bc92014-12-05 22:42:13 +00002232void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2234 return;
2235
Richard Smith7ed1bc92014-12-05 22:42:13 +00002236 SmallString<128> Buffer;
2237 llvm::sys::path::append(Buffer, Prefix, Filename);
2238 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002239}
2240
Richard Smith0f99d6a2015-08-09 08:48:41 +00002241static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2242 switch (ARR) {
2243 case ASTReader::Failure: return true;
2244 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2245 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2246 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2247 case ASTReader::ConfigurationMismatch:
2248 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2249 case ASTReader::HadErrors: return true;
2250 case ASTReader::Success: return false;
2251 }
2252
2253 llvm_unreachable("unknown ASTReadResult");
2254}
2255
Richard Smith0516b182015-09-08 19:40:14 +00002256ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2257 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2258 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002259 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002260 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2261 return Failure;
2262
2263 // Read all of the records in the options block.
2264 RecordData Record;
2265 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002266 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002267 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002268
Richard Smith0516b182015-09-08 19:40:14 +00002269 switch (Entry.Kind) {
2270 case llvm::BitstreamEntry::Error:
2271 case llvm::BitstreamEntry::SubBlock:
2272 return Failure;
2273
2274 case llvm::BitstreamEntry::EndBlock:
2275 return Result;
2276
2277 case llvm::BitstreamEntry::Record:
2278 // The interesting case.
2279 break;
2280 }
2281
2282 // Read and process a record.
2283 Record.clear();
2284 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2285 case LANGUAGE_OPTIONS: {
2286 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2287 if (ParseLanguageOptions(Record, Complain, Listener,
2288 AllowCompatibleConfigurationMismatch))
2289 Result = ConfigurationMismatch;
2290 break;
2291 }
2292
2293 case TARGET_OPTIONS: {
2294 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2295 if (ParseTargetOptions(Record, Complain, Listener,
2296 AllowCompatibleConfigurationMismatch))
2297 Result = ConfigurationMismatch;
2298 break;
2299 }
2300
Richard Smith0516b182015-09-08 19:40:14 +00002301 case FILE_SYSTEM_OPTIONS: {
2302 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2303 if (!AllowCompatibleConfigurationMismatch &&
2304 ParseFileSystemOptions(Record, Complain, Listener))
2305 Result = ConfigurationMismatch;
2306 break;
2307 }
2308
2309 case HEADER_SEARCH_OPTIONS: {
2310 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2311 if (!AllowCompatibleConfigurationMismatch &&
2312 ParseHeaderSearchOptions(Record, Complain, Listener))
2313 Result = ConfigurationMismatch;
2314 break;
2315 }
2316
2317 case PREPROCESSOR_OPTIONS:
2318 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2319 if (!AllowCompatibleConfigurationMismatch &&
2320 ParsePreprocessorOptions(Record, Complain, Listener,
2321 SuggestedPredefines))
2322 Result = ConfigurationMismatch;
2323 break;
2324 }
2325 }
2326}
2327
Guy Benyei11169dd2012-12-18 14:30:41 +00002328ASTReader::ASTReadResult
2329ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002330 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002331 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002333 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002334 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002335
2336 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2337 Error("malformed block record in AST file");
2338 return Failure;
2339 }
2340
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002341 // Lambda to read the unhashed control block the first time it's called.
2342 //
2343 // For PCM files, the unhashed control block cannot be read until after the
2344 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2345 // need to look ahead before reading the IMPORTS record. For consistency,
2346 // this block is always read somehow (see BitstreamEntry::EndBlock).
2347 bool HasReadUnhashedControlBlock = false;
2348 auto readUnhashedControlBlockOnce = [&]() {
2349 if (!HasReadUnhashedControlBlock) {
2350 HasReadUnhashedControlBlock = true;
2351 if (ASTReadResult Result =
2352 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2353 return Result;
2354 }
2355 return Success;
2356 };
2357
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 // Read all of the records and blocks in the control block.
2359 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002360 unsigned NumInputs = 0;
2361 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002362 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002363 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002364
Chris Lattnere7b154b2013-01-19 21:39:22 +00002365 switch (Entry.Kind) {
2366 case llvm::BitstreamEntry::Error:
2367 Error("malformed block record in AST file");
2368 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002369 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002370 // Validate the module before returning. This call catches an AST with
2371 // no module name and no imports.
2372 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2373 return Result;
2374
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002375 // Validate input files.
2376 const HeaderSearchOptions &HSOpts =
2377 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002378
Richard Smitha1825302014-10-23 22:18:29 +00002379 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002380 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2381 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002382 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2383 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002385
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002386 // If we are reading a module, we will create a verification timestamp,
2387 // so we verify all input files. Otherwise, verify only user input
2388 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002389
2390 unsigned N = NumUserInputs;
2391 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002392 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002393 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002394 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002395 N = NumInputs;
2396
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002397 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002398 InputFile IF = getInputFile(F, I+1, Complain);
2399 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002401 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002403
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002404 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002405 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002406
Ben Langmuircb69b572014-03-07 06:40:32 +00002407 if (Listener && Listener->needsInputFileVisitation()) {
2408 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2409 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002410 for (unsigned I = 0; I < N; ++I) {
2411 bool IsSystem = I >= NumUserInputs;
2412 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002413 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002414 F.Kind == MK_ExplicitModule ||
2415 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002416 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002417 }
2418
Richard Smith8a308ec2015-11-05 00:54:55 +00002419 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002420 }
2421
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 case llvm::BitstreamEntry::SubBlock:
2423 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 case INPUT_FILES_BLOCK_ID:
2425 F.InputFilesCursor = Stream;
2426 if (Stream.SkipBlock() || // Skip with the main cursor
2427 // Read the abbreviations
2428 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2429 Error("malformed block record in AST file");
2430 return Failure;
2431 }
2432 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002433
2434 case OPTIONS_BLOCK_ID:
2435 // If we're reading the first module for this group, check its options
2436 // are compatible with ours. For modules it imports, no further checking
2437 // is required, because we checked them when we built it.
2438 if (Listener && !ImportedBy) {
2439 // Should we allow the configuration of the module file to differ from
2440 // the configuration of the current translation unit in a compatible
2441 // way?
2442 //
2443 // FIXME: Allow this for files explicitly specified with -include-pch.
2444 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002445 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002446
Richard Smith8a308ec2015-11-05 00:54:55 +00002447 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2448 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002449 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002450 if (Result == Failure) {
2451 Error("malformed block record in AST file");
2452 return Result;
2453 }
2454
Richard Smith8a308ec2015-11-05 00:54:55 +00002455 if (DisableValidation ||
2456 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2457 Result = Success;
2458
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002459 // If we can't load the module, exit early since we likely
2460 // will rebuild the module anyway. The stream may be in the
2461 // middle of a block.
2462 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002463 return Result;
2464 } else if (Stream.SkipBlock()) {
2465 Error("malformed block record in AST file");
2466 return Failure;
2467 }
2468 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002469
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002471 if (Stream.SkipBlock()) {
2472 Error("malformed block record in AST file");
2473 return Failure;
2474 }
2475 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002477
Chris Lattnere7b154b2013-01-19 21:39:22 +00002478 case llvm::BitstreamEntry::Record:
2479 // The interesting case.
2480 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 }
2482
2483 // Read and process a record.
2484 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002485 StringRef Blob;
2486 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 case METADATA: {
2488 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2489 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002490 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2491 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 return VersionMismatch;
2493 }
2494
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002495 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2497 Diag(diag::err_pch_with_compiler_errors);
2498 return HadErrors;
2499 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002500 if (hasErrors) {
2501 Diags.ErrorOccurred = true;
2502 Diags.UncompilableErrorOccurred = true;
2503 Diags.UnrecoverableErrorOccurred = true;
2504 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002505
2506 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002507 // Relative paths in a relocatable PCH are relative to our sysroot.
2508 if (F.RelocatablePCH)
2509 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002510
Richard Smithe75ee0f2015-08-17 07:13:32 +00002511 F.HasTimestamps = Record[5];
2512
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002513 F.PCHHasObjectFile = Record[6];
2514
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002516 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2518 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002519 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 return VersionMismatch;
2521 }
2522 break;
2523 }
2524
2525 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002526 // Validate the AST before processing any imports (otherwise, untangling
2527 // them can be error-prone and expensive). A module will have a name and
2528 // will already have been validated, but this catches the PCH case.
2529 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2530 return Result;
2531
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002532 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 unsigned Idx = 0, N = Record.size();
2534 while (Idx < N) {
2535 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002536 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 // The import location will be the local one for now; we will adjust
2538 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002539 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002541 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002542 off_t StoredSize = (off_t)Record[Idx++];
2543 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002544 ASTFileSignature StoredSignature = {
2545 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2546 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2547 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002548
2549 std::string ImportedName = ReadString(Record, Idx);
2550 std::string ImportedFile;
2551
2552 // For prebuilt and explicit modules first consult the file map for
2553 // an override. Note that here we don't search prebuilt module
2554 // directories, only the explicit name to file mappings. Also, we will
2555 // still verify the size/signature making sure it is essentially the
2556 // same file but perhaps in a different location.
2557 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2558 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2559 ImportedName, /*FileMapOnly*/ true);
2560
2561 if (ImportedFile.empty())
2562 ImportedFile = ReadPath(F, Record, Idx);
2563 else
2564 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002565
Richard Smith0f99d6a2015-08-09 08:48:41 +00002566 // If our client can't cope with us being out of date, we can't cope with
2567 // our dependency being missing.
2568 unsigned Capabilities = ClientLoadCapabilities;
2569 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2570 Capabilities &= ~ARR_Missing;
2571
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002573 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2574 Loaded, StoredSize, StoredModTime,
2575 StoredSignature, Capabilities);
2576
2577 // If we diagnosed a problem, produce a backtrace.
2578 if (isDiagnosedResult(Result, Capabilities))
2579 Diag(diag::note_module_file_imported_by)
2580 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2581
2582 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case Failure: return Failure;
2584 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002585 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 case OutOfDate: return OutOfDate;
2587 case VersionMismatch: return VersionMismatch;
2588 case ConfigurationMismatch: return ConfigurationMismatch;
2589 case HadErrors: return HadErrors;
2590 case Success: break;
2591 }
2592 }
2593 break;
2594 }
2595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 case ORIGINAL_FILE:
2597 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002598 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002600 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 break;
2602
2603 case ORIGINAL_FILE_ID:
2604 F.OriginalSourceFileID = FileID::get(Record[0]);
2605 break;
2606
2607 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002608 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 break;
2610
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002611 case MODULE_NAME:
2612 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002613 Diag(diag::remark_module_import)
2614 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2615 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002616 if (Listener)
2617 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002618
2619 // Validate the AST as soon as we have a name so we can exit early on
2620 // failure.
2621 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2622 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002623
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002624 break;
2625
Richard Smith223d3f22014-12-06 03:21:08 +00002626 case MODULE_DIRECTORY: {
2627 assert(!F.ModuleName.empty() &&
2628 "MODULE_DIRECTORY found before MODULE_NAME");
2629 // If we've already loaded a module map file covering this module, we may
2630 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002631 Module *M = PP.getHeaderSearchInfo().lookupModule(
2632 F.ModuleName, /*AllowSearch*/ true,
2633 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002634 if (M && M->Directory) {
2635 // If we're implicitly loading a module, the base directory can't
2636 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002637 // Don't emit module relocation error if we have -fno-validate-pch
2638 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2639 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002640 const DirectoryEntry *BuildDir =
2641 PP.getFileManager().getDirectory(Blob);
2642 if (!BuildDir || BuildDir != M->Directory) {
2643 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2644 Diag(diag::err_imported_module_relocated)
2645 << F.ModuleName << Blob << M->Directory->getName();
2646 return OutOfDate;
2647 }
2648 }
2649 F.BaseDirectory = M->Directory->getName();
2650 } else {
2651 F.BaseDirectory = Blob;
2652 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002653 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002654 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002655
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002656 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002657 if (ASTReadResult Result =
2658 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2659 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002660 break;
2661
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002662 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002663 NumInputs = Record[0];
2664 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002665 F.InputFileOffsets =
2666 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002667 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002668 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 break;
2670 }
2671 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002672}
2673
Ben Langmuir2c9af442014-04-10 17:57:43 +00002674ASTReader::ASTReadResult
2675ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002676 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002677
2678 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2679 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002680 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 }
2682
2683 // Read all of the records and blocks for the AST file.
2684 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002685 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002686 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002687
Chris Lattnere7b154b2013-01-19 21:39:22 +00002688 switch (Entry.Kind) {
2689 case llvm::BitstreamEntry::Error:
2690 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002691 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002692 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002693 // Outside of C++, we do not store a lookup map for the translation unit.
2694 // Instead, mark it as needing a lookup map to be built if this module
2695 // contains any declarations lexically within it (which it always does!).
2696 // This usually has no cost, since we very rarely need the lookup map for
2697 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002698 if (ASTContext *Ctx = ContextObj) {
2699 DeclContext *DC = Ctx->getTranslationUnitDecl();
2700 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2701 DC->setMustBuildLookupTable();
2702 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002703
Ben Langmuir2c9af442014-04-10 17:57:43 +00002704 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002705 case llvm::BitstreamEntry::SubBlock:
2706 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 case DECLTYPES_BLOCK_ID:
2708 // We lazily load the decls block, but we want to set up the
2709 // DeclsCursor cursor to point into it. Clone our current bitcode
2710 // cursor to it, enter the block and read the abbrevs in that block.
2711 // With the main cursor, we just skip over it.
2712 F.DeclsCursor = Stream;
2713 if (Stream.SkipBlock() || // Skip with the main cursor.
2714 // Read the abbrevs.
2715 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2716 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002717 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 }
2719 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002720
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 case PREPROCESSOR_BLOCK_ID:
2722 F.MacroCursor = Stream;
2723 if (!PP.getExternalSource())
2724 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002725
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 if (Stream.SkipBlock() ||
2727 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2728 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002729 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 }
2731 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2732 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002733
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 case PREPROCESSOR_DETAIL_BLOCK_ID:
2735 F.PreprocessorDetailCursor = Stream;
2736 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002737 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002739 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002740 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002741 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002743 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002744
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 if (!PP.getPreprocessingRecord())
2746 PP.createPreprocessingRecord();
2747 if (!PP.getPreprocessingRecord()->getExternalSource())
2748 PP.getPreprocessingRecord()->SetExternalSource(*this);
2749 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 case SOURCE_MANAGER_BLOCK_ID:
2752 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002753 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002755
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002757 if (ASTReadResult Result =
2758 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002759 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002763 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 if (Stream.SkipBlock() ||
2765 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2766 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002767 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 }
2769 CommentsCursors.push_back(std::make_pair(C, &F));
2770 break;
2771 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002772
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002774 if (Stream.SkipBlock()) {
2775 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002776 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002777 }
2778 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 }
2780 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002781
Chris Lattnere7b154b2013-01-19 21:39:22 +00002782 case llvm::BitstreamEntry::Record:
2783 // The interesting case.
2784 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 }
2786
2787 // Read and process a record.
2788 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002789 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002790 auto RecordType =
2791 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2792
2793 // If we're not loading an AST context, we don't care about most records.
2794 if (!ContextObj) {
2795 switch (RecordType) {
2796 case IDENTIFIER_TABLE:
2797 case IDENTIFIER_OFFSET:
2798 case INTERESTING_IDENTIFIERS:
2799 case STATISTICS:
2800 case PP_CONDITIONAL_STACK:
2801 case PP_COUNTER_VALUE:
2802 case SOURCE_LOCATION_OFFSETS:
2803 case MODULE_OFFSET_MAP:
2804 case SOURCE_MANAGER_LINE_TABLE:
2805 case SOURCE_LOCATION_PRELOADS:
2806 case PPD_ENTITIES_OFFSETS:
2807 case HEADER_SEARCH_TABLE:
2808 case IMPORTED_MODULES:
2809 case MACRO_OFFSET:
2810 break;
2811 default:
2812 continue;
2813 }
2814 }
2815
2816 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002817 default: // Default behavior: ignore.
2818 break;
2819
2820 case TYPE_OFFSET: {
2821 if (F.LocalNumTypes != 0) {
2822 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002823 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002825 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 F.LocalNumTypes = Record[0];
2827 unsigned LocalBaseTypeIndex = Record[1];
2828 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002829
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 if (F.LocalNumTypes > 0) {
2831 // Introduce the global -> local mapping for types within this module.
2832 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002833
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 // Introduce the local -> global mapping for types within this module.
2835 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002836 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002838
2839 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 }
2841 break;
2842 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 case DECL_OFFSET: {
2845 if (F.LocalNumDecls != 0) {
2846 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002847 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002849 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 F.LocalNumDecls = Record[0];
2851 unsigned LocalBaseDeclID = Record[1];
2852 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002855 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 // module.
2857 GlobalDeclMap.insert(
2858 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002859
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // Introduce the local -> global mapping for declarations within this
2861 // module.
2862 F.DeclRemap.insertOrReplace(
2863 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002864
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 // Introduce the global -> local mapping for declarations within this
2866 // module.
2867 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002868
Ben Langmuir52ca6782014-10-20 16:27:32 +00002869 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2870 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 break;
2872 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002873
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002875 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002876 LexicalContents Contents(
2877 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2878 Blob.data()),
2879 static_cast<unsigned int>(Blob.size() / 4));
2880 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 TU->setHasExternalLexicalStorage(true);
2882 break;
2883 }
2884
2885 case UPDATE_VISIBLE: {
2886 unsigned Idx = 0;
2887 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002888 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002889 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002890 // If we've already loaded the decl, perform the updates when we finish
2891 // loading this block.
2892 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002893 PendingUpdateRecords.push_back(
2894 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 break;
2896 }
2897
2898 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002899 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002901 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2902 (const unsigned char *)F.IdentifierTableData + Record[0],
2903 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2904 (const unsigned char *)F.IdentifierTableData,
2905 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002906
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2908 }
2909 break;
2910
2911 case IDENTIFIER_OFFSET: {
2912 if (F.LocalNumIdentifiers != 0) {
2913 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002914 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002916 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 F.LocalNumIdentifiers = Record[0];
2918 unsigned LocalBaseIdentifierID = Record[1];
2919 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002920
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 if (F.LocalNumIdentifiers > 0) {
2922 // Introduce the global -> local mapping for identifiers within this
2923 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002924 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002926
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 // Introduce the local -> global mapping for identifiers within this
2928 // module.
2929 F.IdentifierRemap.insertOrReplace(
2930 std::make_pair(LocalBaseIdentifierID,
2931 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002932
Ben Langmuir52ca6782014-10-20 16:27:32 +00002933 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2934 + F.LocalNumIdentifiers);
2935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 break;
2937 }
2938
Richard Smith33e0f7e2015-07-22 02:08:40 +00002939 case INTERESTING_IDENTIFIERS:
2940 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2941 break;
2942
Ben Langmuir332aafe2014-01-31 01:06:56 +00002943 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002944 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2945 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002947 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 break;
2949
David Blaikie9ffe5a32017-01-30 05:00:26 +00002950 case MODULAR_CODEGEN_DECLS:
2951 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2952 // them (ie: if we're not codegenerating this module).
2953 if (F.Kind == MK_MainFile)
2954 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2955 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2956 break;
2957
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002959 if (SpecialTypes.empty()) {
2960 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2961 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2962 break;
2963 }
2964
2965 if (SpecialTypes.size() != Record.size()) {
2966 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002967 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002968 }
2969
2970 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2971 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2972 if (!SpecialTypes[I])
2973 SpecialTypes[I] = ID;
2974 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2975 // merge step?
2976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 break;
2978
2979 case STATISTICS:
2980 TotalNumStatements += Record[0];
2981 TotalNumMacros += Record[1];
2982 TotalLexicalDeclContexts += Record[2];
2983 TotalVisibleDeclContexts += Record[3];
2984 break;
2985
2986 case UNUSED_FILESCOPED_DECLS:
2987 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2988 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2989 break;
2990
2991 case DELEGATING_CTORS:
2992 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2993 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2994 break;
2995
2996 case WEAK_UNDECLARED_IDENTIFIERS:
2997 if (Record.size() % 4 != 0) {
2998 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002999 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003001
3002 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 // files. This isn't the way to do it :)
3004 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003005
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 // Translate the weak, undeclared identifiers into global IDs.
3007 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3008 WeakUndeclaredIdentifiers.push_back(
3009 getGlobalIdentifierID(F, Record[I++]));
3010 WeakUndeclaredIdentifiers.push_back(
3011 getGlobalIdentifierID(F, Record[I++]));
3012 WeakUndeclaredIdentifiers.push_back(
3013 ReadSourceLocation(F, Record, I).getRawEncoding());
3014 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3015 }
3016 break;
3017
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003019 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 F.LocalNumSelectors = Record[0];
3021 unsigned LocalBaseSelectorID = Record[1];
3022 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003023
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003025 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 // module.
3027 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003028
3029 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 // module.
3031 F.SelectorRemap.insertOrReplace(
3032 std::make_pair(LocalBaseSelectorID,
3033 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003034
3035 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 }
3037 break;
3038 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003039
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003041 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 if (Record[0])
3043 F.SelectorLookupTable
3044 = ASTSelectorLookupTable::Create(
3045 F.SelectorLookupTableData + Record[0],
3046 F.SelectorLookupTableData,
3047 ASTSelectorLookupTrait(*this, F));
3048 TotalNumMethodPoolEntries += Record[1];
3049 break;
3050
3051 case REFERENCED_SELECTOR_POOL:
3052 if (!Record.empty()) {
3053 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003054 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 Record[Idx++]));
3056 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3057 getRawEncoding());
3058 }
3059 }
3060 break;
3061
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003062 case PP_CONDITIONAL_STACK:
3063 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003064 unsigned Idx = 0, End = Record.size() - 1;
3065 bool ReachedEOFWhileSkipping = Record[Idx++];
3066 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3067 if (ReachedEOFWhileSkipping) {
3068 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3069 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3070 bool FoundNonSkipPortion = Record[Idx++];
3071 bool FoundElse = Record[Idx++];
3072 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3073 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3074 FoundElse, ElseLoc);
3075 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003076 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003077 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003078 auto Loc = ReadSourceLocation(F, Record, Idx);
3079 bool WasSkipping = Record[Idx++];
3080 bool FoundNonSkip = Record[Idx++];
3081 bool FoundElse = Record[Idx++];
3082 ConditionalStack.push_back(
3083 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3084 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003085 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003086 }
3087 break;
3088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 case PP_COUNTER_VALUE:
3090 if (!Record.empty() && Listener)
3091 Listener->ReadCounter(F, Record[0]);
3092 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003093
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003095 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 F.NumFileSortedDecls = Record[0];
3097 break;
3098
3099 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003100 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 F.LocalNumSLocEntries = Record[0];
3102 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003103 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003104 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003106 if (!F.SLocEntryBaseID) {
3107 Error("ran out of source locations");
3108 break;
3109 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 // Make our entry in the range map. BaseID is negative and growing, so
3111 // we invert it. Because we invert it, though, we need the other end of
3112 // the range.
3113 unsigned RangeStart =
3114 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3115 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3116 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3117
3118 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3119 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3120 GlobalSLocOffsetMap.insert(
3121 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3122 - SLocSpaceSize,&F));
3123
3124 // Initialize the remapping table.
3125 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003126 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003128 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 TotalNumSLocEntries += F.LocalNumSLocEntries;
3132 break;
3133 }
3134
Richard Smith37a93df2017-02-18 00:32:02 +00003135 case MODULE_OFFSET_MAP:
3136 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003138
3139 case SOURCE_MANAGER_LINE_TABLE:
3140 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003141 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 break;
3143
3144 case SOURCE_LOCATION_PRELOADS: {
3145 // Need to transform from the local view (1-based IDs) to the global view,
3146 // which is based off F.SLocEntryBaseID.
3147 if (!F.PreloadSLocEntries.empty()) {
3148 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003149 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 F.PreloadSLocEntries.swap(Record);
3153 break;
3154 }
3155
3156 case EXT_VECTOR_DECLS:
3157 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3158 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3159 break;
3160
3161 case VTABLE_USES:
3162 if (Record.size() % 3 != 0) {
3163 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003164 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003166
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 // Later tables overwrite earlier ones.
3168 // FIXME: Modules will have some trouble with this. This is clearly not
3169 // the right way to do this.
3170 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003171
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3173 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3174 VTableUses.push_back(
3175 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3176 VTableUses.push_back(Record[Idx++]);
3177 }
3178 break;
3179
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 case PENDING_IMPLICIT_INSTANTIATIONS:
3181 if (PendingInstantiations.size() % 2 != 0) {
3182 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003183 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 }
3185
3186 if (Record.size() % 2 != 0) {
3187 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003188 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 }
3190
3191 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3192 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3193 PendingInstantiations.push_back(
3194 ReadSourceLocation(F, Record, I).getRawEncoding());
3195 }
3196 break;
3197
3198 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003199 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003200 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003201 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3204 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3205 break;
3206
3207 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003208 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3209 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3210 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003211
3212 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003213
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 unsigned StartingID;
3215 if (!PP.getPreprocessingRecord())
3216 PP.createPreprocessingRecord();
3217 if (!PP.getPreprocessingRecord()->getExternalSource())
3218 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003219 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003221 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 F.BasePreprocessedEntityID = StartingID;
3223
3224 if (F.NumPreprocessedEntities > 0) {
3225 // Introduce the global -> local mapping for preprocessed entities in
3226 // this module.
3227 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 // Introduce the local -> global mapping for preprocessed entities in
3230 // this module.
3231 F.PreprocessedEntityRemap.insertOrReplace(
3232 std::make_pair(LocalBasePreprocessedEntityID,
3233 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3234 }
3235
3236 break;
3237 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003238
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003239 case PPD_SKIPPED_RANGES: {
3240 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3241 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3242 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3243
3244 if (!PP.getPreprocessingRecord())
3245 PP.createPreprocessingRecord();
3246 if (!PP.getPreprocessingRecord()->getExternalSource())
3247 PP.getPreprocessingRecord()->SetExternalSource(*this);
3248 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3249 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003250
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003251 if (F.NumPreprocessedSkippedRanges > 0)
3252 GlobalSkippedRangeMap.insert(
3253 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3254 break;
3255 }
3256
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003257 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 if (Record.size() % 2 != 0) {
3259 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003260 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003262 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3263 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3264 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3265
3266 // If we've already loaded the decl, perform the updates when we finish
3267 // loading this block.
3268 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003269 PendingUpdateRecords.push_back(
3270 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003271 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003273
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003274 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 if (F.LocalNumObjCCategoriesInMap != 0) {
3276 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003277 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003279
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003281 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003283
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 case OBJC_CATEGORIES:
3285 F.ObjCCategories.swap(Record);
3286 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003287
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 case CUDA_SPECIAL_DECL_REFS:
3289 // Later tables overwrite earlier ones.
3290 // FIXME: Modules will have trouble with this.
3291 CUDASpecialDeclRefs.clear();
3292 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3293 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3294 break;
3295
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003296 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003297 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003298 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 if (Record[0]) {
3300 F.HeaderFileInfoTable
3301 = HeaderFileInfoLookupTable::Create(
3302 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3303 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003304 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003306 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003307
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 PP.getHeaderSearchInfo().SetExternalSource(this);
3309 if (!PP.getHeaderSearchInfo().getExternalLookup())
3310 PP.getHeaderSearchInfo().SetExternalLookup(this);
3311 }
3312 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314 case FP_PRAGMA_OPTIONS:
3315 // Later tables overwrite earlier ones.
3316 FPPragmaOptions.swap(Record);
3317 break;
3318
3319 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003320 for (unsigned I = 0, E = Record.size(); I != E; ) {
3321 auto Name = ReadString(Record, I);
3322 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003323 Opt.Supported = Record[I++] != 0;
3324 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003325 Opt.Avail = Record[I++];
3326 Opt.Core = Record[I++];
3327 }
3328 break;
3329
3330 case OPENCL_EXTENSION_TYPES:
3331 for (unsigned I = 0, E = Record.size(); I != E;) {
3332 auto TypeID = static_cast<::TypeID>(Record[I++]);
3333 auto *Type = GetType(TypeID).getTypePtr();
3334 auto NumExt = static_cast<unsigned>(Record[I++]);
3335 for (unsigned II = 0; II != NumExt; ++II) {
3336 auto Ext = ReadString(Record, I);
3337 OpenCLTypeExtMap[Type].insert(Ext);
3338 }
3339 }
3340 break;
3341
3342 case OPENCL_EXTENSION_DECLS:
3343 for (unsigned I = 0, E = Record.size(); I != E;) {
3344 auto DeclID = static_cast<::DeclID>(Record[I++]);
3345 auto *Decl = GetDecl(DeclID);
3346 auto NumExt = static_cast<unsigned>(Record[I++]);
3347 for (unsigned II = 0; II != NumExt; ++II) {
3348 auto Ext = ReadString(Record, I);
3349 OpenCLDeclExtMap[Decl].insert(Ext);
3350 }
3351 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 break;
3353
3354 case TENTATIVE_DEFINITIONS:
3355 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3356 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3357 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003358
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 case KNOWN_NAMESPACES:
3360 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3361 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3362 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003363
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003364 case UNDEFINED_BUT_USED:
3365 if (UndefinedButUsed.size() % 2 != 0) {
3366 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003367 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003368 }
3369
3370 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003371 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003372 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003373 }
3374 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003375 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3376 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003377 ReadSourceLocation(F, Record, I).getRawEncoding());
3378 }
3379 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003380
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003381 case DELETE_EXPRS_TO_ANALYZE:
3382 for (unsigned I = 0, N = Record.size(); I != N;) {
3383 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3384 const uint64_t Count = Record[I++];
3385 DelayedDeleteExprs.push_back(Count);
3386 for (uint64_t C = 0; C < Count; ++C) {
3387 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3388 bool IsArrayForm = Record[I++] == 1;
3389 DelayedDeleteExprs.push_back(IsArrayForm);
3390 }
3391 }
3392 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003393
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003394 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003395 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003396 // If we aren't loading a module (which has its own exports), make
3397 // all of the imported modules visible.
3398 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003399 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3400 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3401 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003402 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003403 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003404 if (DeserializationListener)
3405 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3406 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 }
3408 }
3409 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003410
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 case MACRO_OFFSET: {
3412 if (F.LocalNumMacros != 0) {
3413 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003414 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003416 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 F.LocalNumMacros = Record[0];
3418 unsigned LocalBaseMacroID = Record[1];
3419 F.BaseMacroID = getTotalNumMacros();
3420
3421 if (F.LocalNumMacros > 0) {
3422 // Introduce the global -> local mapping for macros within this module.
3423 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3424
3425 // Introduce the local -> global mapping for macros within this module.
3426 F.MacroRemap.insertOrReplace(
3427 std::make_pair(LocalBaseMacroID,
3428 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003429
3430 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 }
3432 break;
3433 }
3434
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003435 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003436 LateParsedTemplates.append(Record.begin(), Record.end());
3437 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003438
3439 case OPTIMIZE_PRAGMA_OPTIONS:
3440 if (Record.size() != 1) {
3441 Error("invalid pragma optimize record");
3442 return Failure;
3443 }
3444 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3445 break;
Nico Weber72889432014-09-06 01:25:55 +00003446
Nico Weber779355f2016-03-02 23:22:00 +00003447 case MSSTRUCT_PRAGMA_OPTIONS:
3448 if (Record.size() != 1) {
3449 Error("invalid pragma ms_struct record");
3450 return Failure;
3451 }
3452 PragmaMSStructState = Record[0];
3453 break;
3454
Nico Weber42932312016-03-03 00:17:35 +00003455 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3456 if (Record.size() != 2) {
3457 Error("invalid pragma ms_struct record");
3458 return Failure;
3459 }
3460 PragmaMSPointersToMembersState = Record[0];
3461 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3462 break;
3463
Nico Weber72889432014-09-06 01:25:55 +00003464 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3465 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3466 UnusedLocalTypedefNameCandidates.push_back(
3467 getGlobalDeclID(F, Record[I]));
3468 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003469
3470 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3471 if (Record.size() != 1) {
3472 Error("invalid cuda pragma options record");
3473 return Failure;
3474 }
3475 ForceCUDAHostDeviceDepth = Record[0];
3476 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003477
3478 case PACK_PRAGMA_OPTIONS: {
3479 if (Record.size() < 3) {
3480 Error("invalid pragma pack record");
3481 return Failure;
3482 }
3483 PragmaPackCurrentValue = Record[0];
3484 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3485 unsigned NumStackEntries = Record[2];
3486 unsigned Idx = 3;
3487 // Reset the stack when importing a new module.
3488 PragmaPackStack.clear();
3489 for (unsigned I = 0; I < NumStackEntries; ++I) {
3490 PragmaPackStackEntry Entry;
3491 Entry.Value = Record[Idx++];
3492 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003493 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003494 PragmaPackStrings.push_back(ReadString(Record, Idx));
3495 Entry.SlotLabel = PragmaPackStrings.back();
3496 PragmaPackStack.push_back(Entry);
3497 }
3498 break;
3499 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 }
3501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003502}
3503
Richard Smith37a93df2017-02-18 00:32:02 +00003504void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3505 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3506
3507 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003508 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003509 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3510 F.ModuleOffsetMap = StringRef();
3511
3512 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3513 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3514 F.SLocRemap.insert(std::make_pair(0U, 0));
3515 F.SLocRemap.insert(std::make_pair(2U, 1));
3516 }
3517
3518 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003519 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003520 RemapBuilder SLocRemap(F.SLocRemap);
3521 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3522 RemapBuilder MacroRemap(F.MacroRemap);
3523 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3524 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3525 RemapBuilder SelectorRemap(F.SelectorRemap);
3526 RemapBuilder DeclRemap(F.DeclRemap);
3527 RemapBuilder TypeRemap(F.TypeRemap);
3528
3529 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003530 // FIXME: Looking up dependency modules by filename is horrible. Let's
3531 // start fixing this with prebuilt and explicit modules and see how it
3532 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003533 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003534 ModuleKind Kind = static_cast<ModuleKind>(
3535 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003536 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3537 StringRef Name = StringRef((const char*)Data, Len);
3538 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003539 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3540 ? ModuleMgr.lookupByModuleName(Name)
3541 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003542 if (!OM) {
3543 std::string Msg =
3544 "SourceLocation remap refers to unknown module, cannot find ";
3545 Msg.append(Name);
3546 Error(Msg);
3547 return;
3548 }
3549
3550 uint32_t SLocOffset =
3551 endian::readNext<uint32_t, little, unaligned>(Data);
3552 uint32_t IdentifierIDOffset =
3553 endian::readNext<uint32_t, little, unaligned>(Data);
3554 uint32_t MacroIDOffset =
3555 endian::readNext<uint32_t, little, unaligned>(Data);
3556 uint32_t PreprocessedEntityIDOffset =
3557 endian::readNext<uint32_t, little, unaligned>(Data);
3558 uint32_t SubmoduleIDOffset =
3559 endian::readNext<uint32_t, little, unaligned>(Data);
3560 uint32_t SelectorIDOffset =
3561 endian::readNext<uint32_t, little, unaligned>(Data);
3562 uint32_t DeclIDOffset =
3563 endian::readNext<uint32_t, little, unaligned>(Data);
3564 uint32_t TypeIndexOffset =
3565 endian::readNext<uint32_t, little, unaligned>(Data);
3566
3567 uint32_t None = std::numeric_limits<uint32_t>::max();
3568
3569 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3570 RemapBuilder &Remap) {
3571 if (Offset != None)
3572 Remap.insert(std::make_pair(Offset,
3573 static_cast<int>(BaseOffset - Offset)));
3574 };
3575 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3576 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3577 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3578 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3579 PreprocessedEntityRemap);
3580 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3581 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3582 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3583 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3584
3585 // Global -> local mappings.
3586 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3587 }
3588}
3589
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003590ASTReader::ASTReadResult
3591ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3592 const ModuleFile *ImportedBy,
3593 unsigned ClientLoadCapabilities) {
3594 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003595 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003596
3597 // Try to resolve ModuleName in the current header search context and
3598 // verify that it is found in the same module map file as we saved. If the
3599 // top-level AST file is a main file, skip this check because there is no
3600 // usable header search context.
3601 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003602 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003603 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003604 // An implicitly-loaded module file should have its module listed in some
3605 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003606 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003607 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3608 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003609 // Don't emit module relocation error if we have -fno-validate-pch
3610 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003611 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003612 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003613 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003614 // This module was defined by an imported (explicit) module.
3615 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3616 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003617 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003618 // This module was built with a different module map.
3619 Diag(diag::err_imported_module_not_found)
3620 << F.ModuleName << F.FileName << ImportedBy->FileName
3621 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003622 // In case it was imported by a PCH, there's a chance the user is
3623 // just missing to include the search path to the directory containing
3624 // the modulemap.
3625 if (ImportedBy->Kind == MK_PCH)
3626 Diag(diag::note_imported_by_pch_module_not_found)
3627 << llvm::sys::path::parent_path(F.ModuleMapPath);
3628 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003629 }
3630 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003631 }
3632
Richard Smithe842a472014-10-22 02:05:46 +00003633 assert(M->Name == F.ModuleName && "found module with different name");
3634
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003635 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003636 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003637 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3638 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003639 assert(ImportedBy && "top-level import should be verified");
3640 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3641 Diag(diag::err_imported_module_modmap_changed)
3642 << F.ModuleName << ImportedBy->FileName
3643 << ModMap->getName() << F.ModuleMapPath;
3644 return OutOfDate;
3645 }
3646
3647 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3648 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3649 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003650 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003651 const FileEntry *F =
3652 FileMgr.getFile(Filename, false, false);
3653 if (F == nullptr) {
3654 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3655 Error("could not find file '" + Filename +"' referenced by AST file");
3656 return OutOfDate;
3657 }
3658 AdditionalStoredMaps.insert(F);
3659 }
3660
3661 // Check any additional module map files (e.g. module.private.modulemap)
3662 // that are not in the pcm.
3663 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003664 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003665 // Remove files that match
3666 // Note: SmallPtrSet::erase is really remove
3667 if (!AdditionalStoredMaps.erase(ModMap)) {
3668 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3669 Diag(diag::err_module_different_modmap)
3670 << F.ModuleName << /*new*/0 << ModMap->getName();
3671 return OutOfDate;
3672 }
3673 }
3674 }
3675
3676 // Check any additional module map files that are in the pcm, but not
3677 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003678 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003679 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3680 Diag(diag::err_module_different_modmap)
3681 << F.ModuleName << /*not new*/1 << ModMap->getName();
3682 return OutOfDate;
3683 }
3684 }
3685
3686 if (Listener)
3687 Listener->ReadModuleMapFile(F.ModuleMapPath);
3688 return Success;
3689}
3690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003691/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003692static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3693 // Find the entry for this selector in the method pool.
3694 Sema::GlobalMethodPool::iterator Known
3695 = S.MethodPool.find(Method->getSelector());
3696 if (Known == S.MethodPool.end())
3697 return;
3698
3699 // Retrieve the appropriate method list.
3700 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3701 : Known->second.second;
3702 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003703 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003704 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003705 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003706 Found = true;
3707 } else {
3708 // Keep searching.
3709 continue;
3710 }
3711 }
3712
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003713 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003714 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003715 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003716 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003717 }
3718}
3719
Richard Smithde711422015-04-23 21:20:19 +00003720void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003721 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003722 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003723 bool wasHidden = D->isHidden();
3724 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003725
Vedant Kumar48b4f762018-04-14 01:40:48 +00003726 if (wasHidden && SemaObj) {
3727 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003728 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003729 }
3730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 }
3732}
3733
Richard Smith49f906a2014-03-01 00:08:04 +00003734void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003735 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003736 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003738 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003739 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003740 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003741 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003742
3743 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003744 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 // there is nothing more to do.
3746 continue;
3747 }
Richard Smith49f906a2014-03-01 00:08:04 +00003748
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 if (!Mod->isAvailable()) {
3750 // Modules that aren't available cannot be made visible.
3751 continue;
3752 }
3753
3754 // Update the module's name visibility.
3755 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003756
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 // If we've already deserialized any names from this module,
3758 // mark them as visible.
3759 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3760 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003761 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003763 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003764 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3765 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003767
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003769 SmallVector<Module *, 16> Exports;
3770 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003771 for (SmallVectorImpl<Module *>::iterator
3772 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3773 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003774 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003775 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003777 }
3778}
3779
Richard Smith6561f922016-09-12 21:06:40 +00003780/// We've merged the definition \p MergedDef into the existing definition
3781/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3782/// visible.
3783void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3784 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00003785 if (Def->isHidden()) {
3786 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003787 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003788 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00003789 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003790 getContext().mergeDefinitionIntoModule(
3791 Def, MergedDef->getImportedOwningModule(),
3792 /*NotifyListeners*/ false);
3793 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003794 }
Richard Smith6561f922016-09-12 21:06:40 +00003795 }
3796}
3797
Douglas Gregore060e572013-01-25 01:03:03 +00003798bool ASTReader::loadGlobalIndex() {
3799 if (GlobalIndex)
3800 return false;
3801
3802 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003803 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003804 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003805
Douglas Gregore060e572013-01-25 01:03:03 +00003806 // Try to load the global index.
3807 TriedLoadingGlobalIndex = true;
3808 StringRef ModuleCachePath
3809 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3810 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003811 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003812 if (!Result.first)
3813 return true;
3814
3815 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003816 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003817 return false;
3818}
3819
3820bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003821 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003822 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3823}
3824
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003825static void updateModuleTimestamp(ModuleFile &MF) {
3826 // Overwrite the timestamp file contents so that file's mtime changes.
3827 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003828 std::error_code EC;
3829 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3830 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003831 return;
3832 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003833 OS.close();
3834 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003835}
3836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003837/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003838/// cursor into the start of the given block ID, returning false on success and
3839/// true on failure.
3840static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003841 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003842 llvm::BitstreamEntry Entry = Cursor.advance();
3843 switch (Entry.Kind) {
3844 case llvm::BitstreamEntry::Error:
3845 case llvm::BitstreamEntry::EndBlock:
3846 return true;
3847
3848 case llvm::BitstreamEntry::Record:
3849 // Ignore top-level records.
3850 Cursor.skipRecord(Entry.ID);
3851 break;
3852
3853 case llvm::BitstreamEntry::SubBlock:
3854 if (Entry.ID == BlockID) {
3855 if (Cursor.EnterSubBlock(BlockID))
3856 return true;
3857 // Found it!
3858 return false;
3859 }
3860
3861 if (Cursor.SkipBlock())
3862 return true;
3863 }
3864 }
3865}
3866
Benjamin Kramer0772c422016-02-13 13:42:54 +00003867ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 ModuleKind Type,
3869 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003870 unsigned ClientLoadCapabilities,
3871 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003872 llvm::SaveAndRestore<SourceLocation>
3873 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3874
Richard Smithd1c46742014-04-30 02:24:17 +00003875 // Defer any pending actions until we get to the end of reading the AST file.
3876 Deserializing AnASTFile(this);
3877
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003879 unsigned PreviousGeneration = 0;
3880 if (ContextObj)
3881 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003882
3883 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003884 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003885 switch (ASTReadResult ReadResult =
3886 ReadASTCore(FileName, Type, ImportLoc,
3887 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3888 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003890 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 case OutOfDate:
3892 case VersionMismatch:
3893 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003894 case HadErrors: {
3895 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003896 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00003897 LoadedSet.insert(IM.Mod);
3898
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003899 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003900 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003901 ? &PP.getHeaderSearchInfo().getModuleMap()
3902 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003903
3904 // If we find that any modules are unusable, the global index is going
3905 // to be out-of-date. Just remove it.
3906 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003907 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 case Success:
3911 break;
3912 }
3913
3914 // Here comes stuff that we only do once the entire chain is loaded.
3915
3916 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003917 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3918 MEnd = Loaded.end();
3919 M != MEnd; ++M) {
3920 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00003921
3922 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003923 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3924 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003925
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003926 // Read the extension blocks.
3927 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3928 if (ASTReadResult Result = ReadExtensionBlock(F))
3929 return Result;
3930 }
3931
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003932 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 // bits of all files we've seen.
3934 F.GlobalBitOffset = TotalModulesSizeInBits;
3935 TotalModulesSizeInBits += F.SizeInBits;
3936 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003937
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003939 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3940 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 // Load it through the SourceManager and don't call ReadSLocEntry()
3942 // directly because the entry may have already been loaded in which case
3943 // calling ReadSLocEntry() directly would trigger an assertion in
3944 // SourceManager.
3945 SourceMgr.getLoadedSLocEntryByID(Index);
3946 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003947
Richard Smithea741482017-05-01 22:10:47 +00003948 // Map the original source file ID into the ID space of the current
3949 // compilation.
3950 if (F.OriginalSourceFileID.isValid()) {
3951 F.OriginalSourceFileID = FileID::get(
3952 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3953 }
3954
Richard Smith33e0f7e2015-07-22 02:08:40 +00003955 // Preload all the pending interesting identifiers by marking them out of
3956 // date.
3957 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003958 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00003959 F.IdentifierTableData + Offset);
3960
3961 ASTIdentifierLookupTrait Trait(*this, F);
3962 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3963 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003964 auto &II = PP.getIdentifierTable().getOwn(Key);
3965 II.setOutOfDate(true);
3966
3967 // Mark this identifier as being from an AST file so that we can track
3968 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003969 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003970
3971 // Associate the ID with the identifier so that the writer can reuse it.
3972 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3973 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003974 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 }
3976
Douglas Gregor603cd862013-03-22 18:50:14 +00003977 // Setup the import locations and notify the module manager that we've
3978 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003979 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3980 MEnd = Loaded.end();
3981 M != MEnd; ++M) {
3982 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003983
3984 ModuleMgr.moduleFileAccepted(&F);
3985
3986 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003987 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003988 // FIXME: We assume that locations from PCH / preamble do not need
3989 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003990 if (!M->ImportedBy)
3991 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00003993 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 }
3995
Richard Smithdbafb6c2017-06-29 23:23:46 +00003996 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003997 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3998 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003999 // Mark all of the identifiers in the identifier table as being out of date,
4000 // so that various accessors know to check the loaded modules when the
4001 // identifier is used.
4002 //
4003 // For C++ modules, we don't need information on many identifiers (just
4004 // those that provide macros or are poisoned), so we mark all of
4005 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004006 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4007 IdEnd = PP.getIdentifierTable().end();
4008 Id != IdEnd; ++Id)
4009 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004010 }
Manman Rena0f31a02016-04-29 19:04:05 +00004011 // Mark selectors as out of date.
4012 for (auto Sel : SelectorGeneration)
4013 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004014
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004016 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4017 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4019 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004020
4021 switch (Unresolved.Kind) {
4022 case UnresolvedModuleRef::Conflict:
4023 if (ResolvedMod) {
4024 Module::Conflict Conflict;
4025 Conflict.Other = ResolvedMod;
4026 Conflict.Message = Unresolved.String.str();
4027 Unresolved.Mod->Conflicts.push_back(Conflict);
4028 }
4029 continue;
4030
4031 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004033 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035
Douglas Gregorfb912652013-03-20 21:10:35 +00004036 case UnresolvedModuleRef::Export:
4037 if (ResolvedMod || Unresolved.IsWildcard)
4038 Unresolved.Mod->Exports.push_back(
4039 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4040 continue;
4041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004043 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004044
Graydon Hoaree7196af2016-12-09 21:45:49 +00004045 if (Imported)
4046 Imported->append(ImportedModules.begin(),
4047 ImportedModules.end());
4048
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004049 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4050 // Might be unnecessary as use declarations are only used to build the
4051 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004052
Richard Smithdbafb6c2017-06-29 23:23:46 +00004053 if (ContextObj)
4054 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
Richard Smith3d8e97e2013-10-18 06:54:39 +00004056 if (SemaObj)
4057 UpdateSema();
4058
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 if (DeserializationListener)
4060 DeserializationListener->ReaderInitialized(this);
4061
4062 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004063 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 // If this AST file is a precompiled preamble, then set the
4065 // preamble file ID of the source manager to the file source file
4066 // from which the preamble was built.
4067 if (Type == MK_Preamble) {
4068 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4069 } else if (Type == MK_MainFile) {
4070 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4071 }
4072 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004073
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 // For any Objective-C class definitions we have already loaded, make sure
4075 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004076 if (ContextObj) {
4077 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4078 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4079 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004080 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004081 }
4082 }
Douglas Gregore060e572013-01-25 01:03:03 +00004083
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004084 if (PP.getHeaderSearchInfo()
4085 .getHeaderSearchOpts()
4086 .ModulesValidateOncePerBuildSession) {
4087 // Now we are certain that the module and all modules it depends on are
4088 // up to date. Create or update timestamp files for modules that are
4089 // located in the module cache (not for PCH files that could be anywhere
4090 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004091 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4092 ImportedModule &M = Loaded[I];
4093 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004094 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004095 }
4096 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004097 }
4098
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 return Success;
4100}
4101
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004102static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004104/// Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004105static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004106 return Stream.canSkipToPos(4) &&
4107 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004108 Stream.Read(8) == 'P' &&
4109 Stream.Read(8) == 'C' &&
4110 Stream.Read(8) == 'H';
4111}
4112
Richard Smith0f99d6a2015-08-09 08:48:41 +00004113static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4114 switch (Kind) {
4115 case MK_PCH:
4116 return 0; // PCH
4117 case MK_ImplicitModule:
4118 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004119 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004120 return 1; // module
4121 case MK_MainFile:
4122 case MK_Preamble:
4123 return 2; // main source file
4124 }
4125 llvm_unreachable("unknown module kind");
4126}
4127
Guy Benyei11169dd2012-12-18 14:30:41 +00004128ASTReader::ASTReadResult
4129ASTReader::ReadASTCore(StringRef FileName,
4130 ModuleKind Type,
4131 SourceLocation ImportLoc,
4132 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004133 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004134 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004135 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 unsigned ClientLoadCapabilities) {
4137 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004139 ModuleManager::AddModuleResult AddResult
4140 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004141 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004142 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004143 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004144
Douglas Gregor7029ce12013-03-19 00:28:20 +00004145 switch (AddResult) {
4146 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004147 Diag(diag::remark_module_import)
4148 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4149 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004150 return Success;
4151
4152 case ModuleManager::NewlyLoaded:
4153 // Load module file below.
4154 break;
4155
4156 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004157 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004158 // it.
4159 if (ClientLoadCapabilities & ARR_Missing)
4160 return Missing;
4161
4162 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004163 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004164 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004165 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004166 return Failure;
4167
4168 case ModuleManager::OutOfDate:
4169 // We couldn't load the module file because it is out-of-date. If the
4170 // client can handle out-of-date, return it.
4171 if (ClientLoadCapabilities & ARR_OutOfDate)
4172 return OutOfDate;
4173
4174 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004175 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004176 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004177 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 return Failure;
4179 }
4180
Douglas Gregor7029ce12013-03-19 00:28:20 +00004181 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004182
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004184 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004185 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004186 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004187
Guy Benyei11169dd2012-12-18 14:30:41 +00004188 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004189 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004190 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4191 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 return Failure;
4193 }
4194
4195 // This is used for compatibility with older PCH formats.
4196 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004197 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004198 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004199
Chris Lattnerefa77172013-01-20 00:00:22 +00004200 switch (Entry.Kind) {
4201 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004202 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004203 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 Error("invalid record at top-level of AST file");
4205 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004206
Chris Lattnerefa77172013-01-20 00:00:22 +00004207 case llvm::BitstreamEntry::SubBlock:
4208 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 }
4210
Chris Lattnerefa77172013-01-20 00:00:22 +00004211 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 case CONTROL_BLOCK_ID:
4213 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004214 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004216 // Check that we didn't try to load a non-module AST file as a module.
4217 //
4218 // FIXME: Should we also perform the converse check? Loading a module as
4219 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004220 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4221 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004222 F.ModuleName.empty()) {
4223 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4224 if (Result != OutOfDate ||
4225 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4226 Diag(diag::err_module_file_not_module) << FileName;
4227 return Result;
4228 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 break;
4230
4231 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004232 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 case OutOfDate: return OutOfDate;
4234 case VersionMismatch: return VersionMismatch;
4235 case ConfigurationMismatch: return ConfigurationMismatch;
4236 case HadErrors: return HadErrors;
4237 }
4238 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004239
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 case AST_BLOCK_ID:
4241 if (!HaveReadControlBlock) {
4242 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004243 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 return VersionMismatch;
4245 }
4246
4247 // Record that we've loaded this module.
4248 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4249 return Success;
4250
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004251 case UNHASHED_CONTROL_BLOCK_ID:
4252 // This block is handled using look-ahead during ReadControlBlock. We
4253 // shouldn't get here!
4254 Error("malformed block record in AST file");
4255 return Failure;
4256
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 default:
4258 if (Stream.SkipBlock()) {
4259 Error("malformed block record in AST file");
4260 return Failure;
4261 }
4262 break;
4263 }
4264 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004265
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004266 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004267}
4268
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004269ASTReader::ASTReadResult
4270ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4271 unsigned ClientLoadCapabilities) {
4272 const HeaderSearchOptions &HSOpts =
4273 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4274 bool AllowCompatibleConfigurationMismatch =
4275 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4276
4277 ASTReadResult Result = readUnhashedControlBlockImpl(
4278 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4279 Listener.get(),
4280 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4281
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004282 // If F was directly imported by another module, it's implicitly validated by
4283 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004284 if (DisableValidation || WasImportedBy ||
4285 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4286 return Success;
4287
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004288 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004289 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004290 return Failure;
4291 }
4292
4293 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004294 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004295 // with it; we can only load a single version of each module.
4296 //
4297 // This can happen when a module is imported in two contexts: in one, as a
4298 // user module; in another, as a system module (due to an import from
4299 // another module marked with the [system] flag). It usually indicates a
4300 // bug in the module map: this module should also be marked with [system].
4301 //
4302 // If -Wno-system-headers (the default), and the first import is as a
4303 // system module, then validation will fail during the as-user import,
4304 // since -Werror flags won't have been validated. However, it's reasonable
4305 // to treat this consistently as a system module.
4306 //
4307 // If -Wsystem-headers, the PCM on disk was built with
4308 // -Wno-system-headers, and the first import is as a user module, then
4309 // validation will fail during the as-system import since the PCM on disk
4310 // doesn't guarantee that -Werror was respected. However, the -Werror
4311 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004312 if (getModuleManager().getModuleCache().isBufferFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004313 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4314 return Success;
4315 }
4316 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004317
4318 return Result;
4319}
4320
4321ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4322 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4323 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4324 bool ValidateDiagnosticOptions) {
4325 // Initialize a stream.
4326 BitstreamCursor Stream(StreamData);
4327
4328 // Sniff for the signature.
4329 if (!startsWithASTFileMagic(Stream))
4330 return Failure;
4331
4332 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4333 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4334 return Failure;
4335
4336 // Read all of the records in the options block.
4337 RecordData Record;
4338 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004339 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004340 llvm::BitstreamEntry Entry = Stream.advance();
4341
4342 switch (Entry.Kind) {
4343 case llvm::BitstreamEntry::Error:
4344 case llvm::BitstreamEntry::SubBlock:
4345 return Failure;
4346
4347 case llvm::BitstreamEntry::EndBlock:
4348 return Result;
4349
4350 case llvm::BitstreamEntry::Record:
4351 // The interesting case.
4352 break;
4353 }
4354
4355 // Read and process a record.
4356 Record.clear();
4357 switch (
4358 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004359 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004360 if (F)
4361 std::copy(Record.begin(), Record.end(), F->Signature.data());
4362 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004363 case DIAGNOSTIC_OPTIONS: {
4364 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4365 if (Listener && ValidateDiagnosticOptions &&
4366 !AllowCompatibleConfigurationMismatch &&
4367 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004368 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004369 break;
4370 }
4371 case DIAG_PRAGMA_MAPPINGS:
4372 if (!F)
4373 break;
4374 if (F->PragmaDiagMappings.empty())
4375 F->PragmaDiagMappings.swap(Record);
4376 else
4377 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4378 Record.begin(), Record.end());
4379 break;
4380 }
4381 }
4382}
4383
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004384/// Parse a record and blob containing module file extension metadata.
4385static bool parseModuleFileExtensionMetadata(
4386 const SmallVectorImpl<uint64_t> &Record,
4387 StringRef Blob,
4388 ModuleFileExtensionMetadata &Metadata) {
4389 if (Record.size() < 4) return true;
4390
4391 Metadata.MajorVersion = Record[0];
4392 Metadata.MinorVersion = Record[1];
4393
4394 unsigned BlockNameLen = Record[2];
4395 unsigned UserInfoLen = Record[3];
4396
4397 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4398
4399 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4400 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4401 Blob.data() + BlockNameLen + UserInfoLen);
4402 return false;
4403}
4404
4405ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4406 BitstreamCursor &Stream = F.Stream;
4407
4408 RecordData Record;
4409 while (true) {
4410 llvm::BitstreamEntry Entry = Stream.advance();
4411 switch (Entry.Kind) {
4412 case llvm::BitstreamEntry::SubBlock:
4413 if (Stream.SkipBlock())
4414 return Failure;
4415
4416 continue;
4417
4418 case llvm::BitstreamEntry::EndBlock:
4419 return Success;
4420
4421 case llvm::BitstreamEntry::Error:
4422 return HadErrors;
4423
4424 case llvm::BitstreamEntry::Record:
4425 break;
4426 }
4427
4428 Record.clear();
4429 StringRef Blob;
4430 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4431 switch (RecCode) {
4432 case EXTENSION_METADATA: {
4433 ModuleFileExtensionMetadata Metadata;
4434 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4435 return Failure;
4436
4437 // Find a module file extension with this block name.
4438 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4439 if (Known == ModuleFileExtensions.end()) break;
4440
4441 // Form a reader.
4442 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4443 F, Stream)) {
4444 F.ExtensionReaders.push_back(std::move(Reader));
4445 }
4446
4447 break;
4448 }
4449 }
4450 }
4451
4452 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453}
4454
Richard Smitha7e2cc62015-05-01 01:53:09 +00004455void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004456 assert(ContextObj && "no context to initialize");
4457 ASTContext &Context = *ContextObj;
4458
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 // If there's a listener, notify them that we "read" the translation unit.
4460 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004461 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 Context.getTranslationUnitDecl());
4463
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 // FIXME: Find a better way to deal with collisions between these
4465 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004466
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 // Load the special types.
4468 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4469 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4470 if (!Context.CFConstantStringTypeDecl)
4471 Context.setCFConstantStringType(GetType(String));
4472 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004473
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4475 QualType FileType = GetType(File);
4476 if (FileType.isNull()) {
4477 Error("FILE type is NULL");
4478 return;
4479 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004480
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004482 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 Context.setFILEDecl(Typedef->getDecl());
4484 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004485 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 if (!Tag) {
4487 Error("Invalid FILE type in AST file");
4488 return;
4489 }
4490 Context.setFILEDecl(Tag->getDecl());
4491 }
4492 }
4493 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004494
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4496 QualType Jmp_bufType = GetType(Jmp_buf);
4497 if (Jmp_bufType.isNull()) {
4498 Error("jmp_buf type is NULL");
4499 return;
4500 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004501
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004503 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 Context.setjmp_bufDecl(Typedef->getDecl());
4505 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004506 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 if (!Tag) {
4508 Error("Invalid jmp_buf type in AST file");
4509 return;
4510 }
4511 Context.setjmp_bufDecl(Tag->getDecl());
4512 }
4513 }
4514 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004515
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4517 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4518 if (Sigjmp_bufType.isNull()) {
4519 Error("sigjmp_buf type is NULL");
4520 return;
4521 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004522
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004524 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 Context.setsigjmp_bufDecl(Typedef->getDecl());
4526 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004527 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 assert(Tag && "Invalid sigjmp_buf type in AST file");
4529 Context.setsigjmp_bufDecl(Tag->getDecl());
4530 }
4531 }
4532 }
4533
4534 if (unsigned ObjCIdRedef
4535 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4536 if (Context.ObjCIdRedefinitionType.isNull())
4537 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4538 }
4539
4540 if (unsigned ObjCClassRedef
4541 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4542 if (Context.ObjCClassRedefinitionType.isNull())
4543 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4544 }
4545
4546 if (unsigned ObjCSelRedef
4547 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4548 if (Context.ObjCSelRedefinitionType.isNull())
4549 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4550 }
4551
4552 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4553 QualType Ucontext_tType = GetType(Ucontext_t);
4554 if (Ucontext_tType.isNull()) {
4555 Error("ucontext_t type is NULL");
4556 return;
4557 }
4558
4559 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004560 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 Context.setucontext_tDecl(Typedef->getDecl());
4562 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004563 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 assert(Tag && "Invalid ucontext_t type in AST file");
4565 Context.setucontext_tDecl(Tag->getDecl());
4566 }
4567 }
4568 }
4569 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004570
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4572
4573 // If there were any CUDA special declarations, deserialize them.
4574 if (!CUDASpecialDeclRefs.empty()) {
4575 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4576 Context.setcudaConfigureCallDecl(
4577 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4578 }
Richard Smith56be7542014-03-21 00:33:59 +00004579
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004581 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004582 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004583 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004584 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004585 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004586 if (Import.ImportLoc.isValid())
4587 PP.makeModuleVisible(Imported, Import.ImportLoc);
4588 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004589 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
4591 ImportedModules.clear();
4592}
4593
4594void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004595 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004596}
4597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004598/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004599/// else returns 0.
4600static ASTFileSignature readASTFileSignature(StringRef PCH) {
4601 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004602 if (!startsWithASTFileMagic(Stream))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004603 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004604
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004605 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4606 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004607 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004608
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004609 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004610 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004611 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004612 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004613 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004614 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004615
4616 Record.clear();
4617 StringRef Blob;
4618 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004619 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4620 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004621 }
4622}
4623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004624/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004625/// directly from the AST file, without actually loading the AST
4626/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004627std::string ASTReader::getOriginalSourceFile(
4628 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004629 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004631 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004633 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4634 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004635 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 }
4637
4638 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004639 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004640
4641 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004642 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004644 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004646
Chris Lattnere7b154b2013-01-19 21:39:22 +00004647 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004648 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004649 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004650 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004652
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004653 // Scan for ORIGINAL_FILE inside the control block.
4654 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004655 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004656 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004657 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004658 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004659
Chris Lattnere7b154b2013-01-19 21:39:22 +00004660 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4661 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004662 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004664
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004666 StringRef Blob;
4667 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4668 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004670}
4671
4672namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004673
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 class SimplePCHValidator : public ASTReaderListener {
4675 const LangOptions &ExistingLangOpts;
4676 const TargetOptions &ExistingTargetOpts;
4677 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004678 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004680
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 public:
4682 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4683 const TargetOptions &ExistingTargetOpts,
4684 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004685 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 FileManager &FileMgr)
4687 : ExistingLangOpts(ExistingLangOpts),
4688 ExistingTargetOpts(ExistingTargetOpts),
4689 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004690 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004691 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004692
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004693 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4694 bool AllowCompatibleDifferences) override {
4695 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4696 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004698
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004699 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4700 bool AllowCompatibleDifferences) override {
4701 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4702 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004704
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004705 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4706 StringRef SpecificModuleCachePath,
4707 bool Complain) override {
4708 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4709 ExistingModuleCachePath,
4710 nullptr, ExistingLangOpts);
4711 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004712
Craig Topper3e89dfe2014-03-13 02:13:41 +00004713 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4714 bool Complain,
4715 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004716 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004717 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 }
4719 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004720
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004721} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004722
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004723bool ASTReader::readASTFileControlBlock(
4724 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004725 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004726 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004727 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004729 // FIXME: This allows use of the VFS; we do not allow use of the
4730 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004731 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 if (!Buffer) {
4733 return true;
4734 }
4735
4736 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004737 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4738 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004739
4740 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004741 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004743
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004744 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004745 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004746 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004747
4748 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004749 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004750 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004751 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004752
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004754 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004755 bool DoneWithControlBlock = false;
4756 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004757 llvm::BitstreamEntry Entry = Stream.advance();
4758
4759 switch (Entry.Kind) {
4760 case llvm::BitstreamEntry::SubBlock: {
4761 switch (Entry.ID) {
4762 case OPTIONS_BLOCK_ID: {
4763 std::string IgnoredSuggestedPredefines;
4764 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4765 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004766 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004767 return true;
4768 break;
4769 }
4770
4771 case INPUT_FILES_BLOCK_ID:
4772 InputFilesCursor = Stream;
4773 if (Stream.SkipBlock() ||
4774 (NeedsInputFiles &&
4775 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4776 return true;
4777 break;
4778
4779 default:
4780 if (Stream.SkipBlock())
4781 return true;
4782 break;
4783 }
4784
4785 continue;
4786 }
4787
4788 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004789 DoneWithControlBlock = true;
4790 break;
Richard Smith0516b182015-09-08 19:40:14 +00004791
4792 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004793 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004794
4795 case llvm::BitstreamEntry::Record:
4796 break;
4797 }
4798
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004799 if (DoneWithControlBlock) break;
4800
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004802 StringRef Blob;
4803 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004804 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004805 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004806 if (Record[0] != VERSION_MAJOR)
4807 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004808 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004809 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004810 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004811 case MODULE_NAME:
4812 Listener.ReadModuleName(Blob);
4813 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004814 case MODULE_DIRECTORY:
4815 ModuleDir = Blob;
4816 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004817 case MODULE_MAP_FILE: {
4818 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004819 auto Path = ReadString(Record, Idx);
4820 ResolveImportedPath(Path, ModuleDir);
4821 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004822 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004823 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004824 case INPUT_FILE_OFFSETS: {
4825 if (!NeedsInputFiles)
4826 break;
4827
4828 unsigned NumInputFiles = Record[0];
4829 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00004830 const llvm::support::unaligned_uint64_t *InputFileOffs =
4831 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004832 for (unsigned I = 0; I != NumInputFiles; ++I) {
4833 // Go find this input file.
4834 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004835
4836 if (isSystemFile && !NeedsSystemInputFiles)
4837 break; // the rest are system input files
4838
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004839 BitstreamCursor &Cursor = InputFilesCursor;
4840 SavedStreamPosition SavedPosition(Cursor);
4841 Cursor.JumpToBit(InputFileOffs[I]);
4842
4843 unsigned Code = Cursor.ReadCode();
4844 RecordData Record;
4845 StringRef Blob;
4846 bool shouldContinue = false;
4847 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4848 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00004849 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004850 std::string Filename = Blob;
4851 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004852 shouldContinue = Listener.visitInputFile(
4853 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004854 break;
4855 }
4856 if (!shouldContinue)
4857 break;
4858 }
4859 break;
4860 }
4861
Richard Smithd4b230b2014-10-27 23:01:16 +00004862 case IMPORTS: {
4863 if (!NeedsImports)
4864 break;
4865
4866 unsigned Idx = 0, N = Record.size();
4867 while (Idx < N) {
4868 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004869 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
4870 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004871 std::string Filename = ReadString(Record, Idx);
4872 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004873 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004874 }
4875 break;
4876 }
4877
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004878 default:
4879 // No other validation to perform.
4880 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 }
4882 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004883
4884 // Look for module file extension blocks, if requested.
4885 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004886 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004887 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4888 bool DoneWithExtensionBlock = false;
4889 while (!DoneWithExtensionBlock) {
4890 llvm::BitstreamEntry Entry = Stream.advance();
4891
4892 switch (Entry.Kind) {
4893 case llvm::BitstreamEntry::SubBlock:
4894 if (Stream.SkipBlock())
4895 return true;
4896
4897 continue;
4898
4899 case llvm::BitstreamEntry::EndBlock:
4900 DoneWithExtensionBlock = true;
4901 continue;
4902
4903 case llvm::BitstreamEntry::Error:
4904 return true;
4905
4906 case llvm::BitstreamEntry::Record:
4907 break;
4908 }
4909
4910 Record.clear();
4911 StringRef Blob;
4912 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4913 switch (RecCode) {
4914 case EXTENSION_METADATA: {
4915 ModuleFileExtensionMetadata Metadata;
4916 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4917 return true;
4918
4919 Listener.readModuleFileExtension(Metadata);
4920 break;
4921 }
4922 }
4923 }
4924 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004925 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004926 }
4927
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004928 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4929 if (readUnhashedControlBlockImpl(
4930 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4931 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4932 ValidateDiagnosticOptions) != Success)
4933 return true;
4934
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004935 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004936}
4937
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004938bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4939 const PCHContainerReader &PCHContainerRdr,
4940 const LangOptions &LangOpts,
4941 const TargetOptions &TargetOpts,
4942 const PreprocessorOptions &PPOpts,
4943 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004944 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4945 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004946 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004947 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004948 validator,
4949 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004950}
4951
Ben Langmuir2c9af442014-04-10 17:57:43 +00004952ASTReader::ASTReadResult
4953ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 // Enter the submodule block.
4955 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4956 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004957 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 }
4959
4960 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4961 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004962 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 RecordData Record;
4964 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004965 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004966
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004967 switch (Entry.Kind) {
4968 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4969 case llvm::BitstreamEntry::Error:
4970 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004971 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004972 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004973 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004974 case llvm::BitstreamEntry::Record:
4975 // The interesting case.
4976 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004978
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004980 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004982 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4983
4984 if ((Kind == SUBMODULE_METADATA) != First) {
4985 Error("submodule metadata record should be at beginning of block");
4986 return Failure;
4987 }
4988 First = false;
4989
4990 // Submodule information is only valid if we have a current module.
4991 // FIXME: Should we error on these cases?
4992 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4993 Kind != SUBMODULE_DEFINITION)
4994 continue;
4995
4996 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 default: // Default behavior: ignore.
4998 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004999
Richard Smith03478d92014-10-23 22:12:14 +00005000 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005001 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005003 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 }
Richard Smith03478d92014-10-23 22:12:14 +00005005
Chris Lattner0e6c9402013-01-20 02:38:54 +00005006 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005007 unsigned Idx = 0;
5008 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5009 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005010 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005011 bool IsFramework = Record[Idx++];
5012 bool IsExplicit = Record[Idx++];
5013 bool IsSystem = Record[Idx++];
5014 bool IsExternC = Record[Idx++];
5015 bool InferSubmodules = Record[Idx++];
5016 bool InferExplicitSubmodules = Record[Idx++];
5017 bool InferExportWildcard = Record[Idx++];
5018 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005019 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005020
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005021 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005022 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005024
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 // Retrieve this (sub)module from the module map, creating it if
5026 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005027 CurrentModule =
5028 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5029 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005030
5031 // FIXME: set the definition loc for CurrentModule, or call
5032 // ModMap.setInferredModuleAllowedBy()
5033
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5035 if (GlobalIndex >= SubmodulesLoaded.size() ||
5036 SubmodulesLoaded[GlobalIndex]) {
5037 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005040
Douglas Gregor7029ce12013-03-19 00:28:20 +00005041 if (!ParentModule) {
5042 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005043 // Don't emit module relocation error if we have -fno-validate-pch
5044 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5045 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005046 if (!Diags.isDiagnosticInFlight()) {
5047 Diag(diag::err_module_file_conflict)
5048 << CurrentModule->getTopLevelModuleName()
5049 << CurFile->getName()
5050 << F.File->getName();
5051 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005052 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005053 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005054 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005055
5056 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005057 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005058 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005059
Richard Smithdd8b5332017-09-04 05:37:53 +00005060 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005061 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 CurrentModule->IsFromModuleFile = true;
5063 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005064 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 CurrentModule->InferSubmodules = InferSubmodules;
5066 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5067 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005068 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005069 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 if (DeserializationListener)
5071 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005072
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005074
Richard Smith8a3e39a2016-03-28 21:31:09 +00005075 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005076 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005077 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005078 CurrentModule->UnresolvedConflicts.clear();
5079 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005080
5081 // The module is available unless it's missing a requirement; relevant
5082 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5083 // Missing headers that were present when the module was built do not
5084 // make it unavailable -- if we got this far, this must be an explicitly
5085 // imported module file.
5086 CurrentModule->Requirements.clear();
5087 CurrentModule->MissingHeaders.clear();
5088 CurrentModule->IsMissingRequirement =
5089 ParentModule && ParentModule->IsMissingRequirement;
5090 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 break;
5092 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005093
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005095 std::string Filename = Blob;
5096 ResolveImportedPath(F, Filename);
5097 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005099 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5100 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005101 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5102 Error("mismatched umbrella headers in submodule");
5103 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 }
5105 }
5106 break;
5107 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005108
Richard Smith202210b2014-10-24 20:23:01 +00005109 case SUBMODULE_HEADER:
5110 case SUBMODULE_EXCLUDED_HEADER:
5111 case SUBMODULE_PRIVATE_HEADER:
5112 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005113 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5114 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005115 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005116
Richard Smith202210b2014-10-24 20:23:01 +00005117 case SUBMODULE_TEXTUAL_HEADER:
5118 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5119 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5120 // them here.
5121 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005122
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005123 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005124 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005126
5127 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005128 std::string Dirname = Blob;
5129 ResolveImportedPath(F, Dirname);
5130 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005132 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5133 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005134 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5135 Error("mismatched umbrella directories in submodule");
5136 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 }
5138 }
5139 break;
5140 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005141
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 F.BaseSubmoduleID = getTotalNumSubmodules();
5144 F.LocalNumSubmodules = Record[0];
5145 unsigned LocalBaseSubmoduleID = Record[1];
5146 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005147 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 // module.
5149 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005150
5151 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 // module.
5153 F.SubmoduleRemap.insertOrReplace(
5154 std::make_pair(LocalBaseSubmoduleID,
5155 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005156
Ben Langmuir52ca6782014-10-20 16:27:32 +00005157 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5158 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 break;
5160 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005161
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005162 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005164 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 Unresolved.File = &F;
5166 Unresolved.Mod = CurrentModule;
5167 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005168 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005170 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 }
5172 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005173
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005174 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005176 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 Unresolved.File = &F;
5178 Unresolved.Mod = CurrentModule;
5179 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005180 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005182 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005184
5185 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 // the parsed, unresolved exports around.
5187 CurrentModule->UnresolvedExports.clear();
5188 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005189
5190 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005191 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5192 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005194
5195 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005196 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005197 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005198 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005199 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005200
5201 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005202 CurrentModule->ConfigMacros.push_back(Blob.str());
5203 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005204
5205 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005206 UnresolvedModuleRef Unresolved;
5207 Unresolved.File = &F;
5208 Unresolved.Mod = CurrentModule;
5209 Unresolved.ID = Record[0];
5210 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5211 Unresolved.IsWildcard = false;
5212 Unresolved.String = Blob;
5213 UnresolvedModuleRefs.push_back(Unresolved);
5214 break;
5215 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005216
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005217 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005218 if (!ContextObj)
5219 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005220 SmallVector<uint32_t, 16> Inits;
5221 for (auto &ID : Record)
5222 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005223 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005224 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005226
5227 case SUBMODULE_EXPORT_AS:
5228 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005229 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005230 break;
5231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 }
5233}
5234
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005235/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005236/// structure.
5237///
5238/// This routine parses the language options from the AST file and then gives
5239/// them to the AST listener if one is set.
5240///
5241/// \returns true if the listener deems the file unacceptable, false otherwise.
5242bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5243 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005244 ASTReaderListener &Listener,
5245 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 LangOptions LangOpts;
5247 unsigned Idx = 0;
5248#define LANGOPT(Name, Bits, Default, Description) \
5249 LangOpts.Name = Record[Idx++];
5250#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5251 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5252#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005253#define SANITIZER(NAME, ID) \
5254 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005255#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005256
Ben Langmuircd98cb72015-06-23 18:20:18 +00005257 for (unsigned N = Record[Idx++]; N; --N)
5258 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5259
Vedant Kumar48b4f762018-04-14 01:40:48 +00005260 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5262 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005263
Ben Langmuird4a667a2015-06-23 18:20:23 +00005264 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005265
5266 // Comment options.
5267 for (unsigned N = Record[Idx++]; N; --N) {
5268 LangOpts.CommentOpts.BlockCommandNames.push_back(
5269 ReadString(Record, Idx));
5270 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005271 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005272
Samuel Antaoee8fb302016-01-06 13:42:12 +00005273 // OpenMP offloading options.
5274 for (unsigned N = Record[Idx++]; N; --N) {
5275 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5276 }
5277
5278 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5279
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005280 return Listener.ReadLanguageOptions(LangOpts, Complain,
5281 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005282}
5283
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005284bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5285 ASTReaderListener &Listener,
5286 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 unsigned Idx = 0;
5288 TargetOptions TargetOpts;
5289 TargetOpts.Triple = ReadString(Record, Idx);
5290 TargetOpts.CPU = ReadString(Record, Idx);
5291 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 for (unsigned N = Record[Idx++]; N; --N) {
5293 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5294 }
5295 for (unsigned N = Record[Idx++]; N; --N) {
5296 TargetOpts.Features.push_back(ReadString(Record, Idx));
5297 }
5298
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005299 return Listener.ReadTargetOptions(TargetOpts, Complain,
5300 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005301}
5302
5303bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5304 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005305 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005307#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005308#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005309 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005310#include "clang/Basic/DiagnosticOptions.def"
5311
Richard Smith3be1cb22014-08-07 00:24:21 +00005312 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005313 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005314 for (unsigned N = Record[Idx++]; N; --N)
5315 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005316
5317 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5318}
5319
5320bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5321 ASTReaderListener &Listener) {
5322 FileSystemOptions FSOpts;
5323 unsigned Idx = 0;
5324 FSOpts.WorkingDir = ReadString(Record, Idx);
5325 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5326}
5327
5328bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5329 bool Complain,
5330 ASTReaderListener &Listener) {
5331 HeaderSearchOptions HSOpts;
5332 unsigned Idx = 0;
5333 HSOpts.Sysroot = ReadString(Record, Idx);
5334
5335 // Include entries.
5336 for (unsigned N = Record[Idx++]; N; --N) {
5337 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005338 frontend::IncludeDirGroup Group
5339 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 bool IsFramework = Record[Idx++];
5341 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005342 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5343 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 }
5345
5346 // System header prefixes.
5347 for (unsigned N = Record[Idx++]; N; --N) {
5348 std::string Prefix = ReadString(Record, Idx);
5349 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005350 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 }
5352
5353 HSOpts.ResourceDir = ReadString(Record, Idx);
5354 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005355 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005357 HSOpts.ImplicitModuleMaps = Record[Idx++];
5358 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 HSOpts.UseBuiltinIncludes = Record[Idx++];
5360 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5361 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5362 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005363 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005364
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005365 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5366 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005367}
5368
5369bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5370 bool Complain,
5371 ASTReaderListener &Listener,
5372 std::string &SuggestedPredefines) {
5373 PreprocessorOptions PPOpts;
5374 unsigned Idx = 0;
5375
5376 // Macro definitions/undefs
5377 for (unsigned N = Record[Idx++]; N; --N) {
5378 std::string Macro = ReadString(Record, Idx);
5379 bool IsUndef = Record[Idx++];
5380 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5381 }
5382
5383 // Includes
5384 for (unsigned N = Record[Idx++]; N; --N) {
5385 PPOpts.Includes.push_back(ReadString(Record, Idx));
5386 }
5387
5388 // Macro Includes
5389 for (unsigned N = Record[Idx++]; N; --N) {
5390 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5391 }
5392
5393 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005394 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 PPOpts.ObjCXXARCStandardLibrary =
5397 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5398 SuggestedPredefines.clear();
5399 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5400 SuggestedPredefines);
5401}
5402
5403std::pair<ModuleFile *, unsigned>
5404ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5405 GlobalPreprocessedEntityMapType::iterator
5406 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005407 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005408 "Corrupted global preprocessed entity map");
5409 ModuleFile *M = I->second;
5410 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5411 return std::make_pair(M, LocalIndex);
5412}
5413
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005414llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005415ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5416 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5417 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5418 Mod.NumPreprocessedEntities);
5419
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005420 return llvm::make_range(PreprocessingRecord::iterator(),
5421 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005422}
5423
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005424llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005425ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005426 return llvm::make_range(
5427 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5428 ModuleDeclIterator(this, &Mod,
5429 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005430}
5431
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005432SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5433 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5434 assert(I != GlobalSkippedRangeMap.end() &&
5435 "Corrupted global skipped range map");
5436 ModuleFile *M = I->second;
5437 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5438 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5439 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5440 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5441 TranslateSourceLocation(*M, RawRange.getEnd()));
5442 assert(Range.isValid());
5443 return Range;
5444}
5445
Guy Benyei11169dd2012-12-18 14:30:41 +00005446PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5447 PreprocessedEntityID PPID = Index+1;
5448 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5449 ModuleFile &M = *PPInfo.first;
5450 unsigned LocalIndex = PPInfo.second;
5451 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5452
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 if (!PP.getPreprocessingRecord()) {
5454 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005455 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005457
5458 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005459 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5460
5461 llvm::BitstreamEntry Entry =
5462 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5463 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005464 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005465
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005467 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5468 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005470 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 RecordData Record;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005472 PreprocessorDetailRecordTypes RecType =
5473 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5474 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005475 switch (RecType) {
5476 case PPD_MACRO_EXPANSION: {
5477 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005478 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005479 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 if (isBuiltin)
5481 Name = getLocalIdentifier(M, Record[1]);
5482 else {
Richard Smith66a81862015-05-04 02:25:31 +00005483 PreprocessedEntityID GlobalID =
5484 getGlobalPreprocessedEntityID(M, Record[1]);
5485 Def = cast<MacroDefinitionRecord>(
5486 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 }
5488
5489 MacroExpansion *ME;
5490 if (isBuiltin)
5491 ME = new (PPRec) MacroExpansion(Name, Range);
5492 else
5493 ME = new (PPRec) MacroExpansion(Def, Range);
5494
5495 return ME;
5496 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005497
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 case PPD_MACRO_DEFINITION: {
5499 // Decode the identifier info and then check again; if the macro is
5500 // still defined and associated with the identifier,
5501 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005502 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005503
5504 if (DeserializationListener)
5505 DeserializationListener->MacroDefinitionRead(PPID, MD);
5506
5507 return MD;
5508 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005509
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005511 const char *FullFileNameStart = Blob.data() + Record[0];
5512 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005513 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005514 if (!FullFileName.empty())
5515 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005516
Guy Benyei11169dd2012-12-18 14:30:41 +00005517 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005518 InclusionDirective::InclusionKind Kind
5519 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5520 InclusionDirective *ID
5521 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005522 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 Record[1], Record[3],
5524 File,
5525 Range);
5526 return ID;
5527 }
5528 }
5529
5530 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5531}
5532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005533/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005534/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005535///
5536/// \param SLocMapI points at a chunk of a module that contains no
5537/// preprocessed entities or the entities it contains are not the ones we are
5538/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005539PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5540 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5541 ++SLocMapI;
5542 for (GlobalSLocOffsetMapType::const_iterator
5543 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5544 ModuleFile &M = *SLocMapI->second;
5545 if (M.NumPreprocessedEntities)
5546 return M.BasePreprocessedEntityID;
5547 }
5548
5549 return getTotalNumPreprocessedEntities();
5550}
5551
5552namespace {
5553
Guy Benyei11169dd2012-12-18 14:30:41 +00005554struct PPEntityComp {
5555 const ASTReader &Reader;
5556 ModuleFile &M;
5557
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005558 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005559
5560 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5561 SourceLocation LHS = getLoc(L);
5562 SourceLocation RHS = getLoc(R);
5563 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5564 }
5565
5566 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5567 SourceLocation LHS = getLoc(L);
5568 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5569 }
5570
5571 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5572 SourceLocation RHS = getLoc(R);
5573 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5574 }
5575
5576 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005577 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005578 }
5579};
5580
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005581} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005582
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005583PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5584 bool EndsAfter) const {
5585 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005586 return getTotalNumPreprocessedEntities();
5587
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005588 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5589 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5591 "Corrupted global sloc offset map");
5592
5593 if (SLocMapI->second->NumPreprocessedEntities == 0)
5594 return findNextPreprocessedEntity(SLocMapI);
5595
5596 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005597
5598 using pp_iterator = const PPEntityOffset *;
5599
Guy Benyei11169dd2012-12-18 14:30:41 +00005600 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5601 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5602
5603 size_t Count = M.NumPreprocessedEntities;
5604 size_t Half;
5605 pp_iterator First = pp_begin;
5606 pp_iterator PPI;
5607
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005608 if (EndsAfter) {
5609 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005610 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005611 } else {
5612 // Do a binary search manually instead of using std::lower_bound because
5613 // The end locations of entities may be unordered (when a macro expansion
5614 // is inside another macro argument), but for this case it is not important
5615 // whether we get the first macro expansion or its containing macro.
5616 while (Count > 0) {
5617 Half = Count / 2;
5618 PPI = First;
5619 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005620 if (SourceMgr.isBeforeInTranslationUnit(
5621 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005622 First = PPI;
5623 ++First;
5624 Count = Count - Half - 1;
5625 } else
5626 Count = Half;
5627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 }
5629
5630 if (PPI == pp_end)
5631 return findNextPreprocessedEntity(SLocMapI);
5632
5633 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5634}
5635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005636/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00005637/// preprocessed entities that \arg Range encompasses.
5638std::pair<unsigned, unsigned>
5639 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5640 if (Range.isInvalid())
5641 return std::make_pair(0,0);
5642 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5643
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005644 PreprocessedEntityID BeginID =
5645 findPreprocessedEntity(Range.getBegin(), false);
5646 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 return std::make_pair(BeginID, EndID);
5648}
5649
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005650/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00005651/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005652Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 FileID FID) {
5654 if (FID.isInvalid())
5655 return false;
5656
5657 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5658 ModuleFile &M = *PPInfo.first;
5659 unsigned LocalIndex = PPInfo.second;
5660 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005661
Richard Smithcb34bd32016-03-27 07:28:06 +00005662 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 if (Loc.isInvalid())
5664 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005665
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5667 return true;
5668 else
5669 return false;
5670}
5671
5672namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005673
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005674 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005677 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005678
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005680 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005681
5682 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00005683 HeaderFileInfoLookupTable *Table
5684 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00005685 if (!Table)
5686 return false;
5687
5688 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005689 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005690 if (Pos == Table->end())
5691 return false;
5692
Richard Smithbdf2d932015-07-30 03:37:16 +00005693 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 return true;
5695 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005696
David Blaikie05785d12013-02-20 22:23:23 +00005697 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005698 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005699
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005700} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005701
5702HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005703 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005704 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005705 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005707
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 return HeaderFileInfo();
5709}
5710
5711void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005712 using DiagState = DiagnosticsEngine::DiagState;
5713 SmallVector<DiagState *, 32> DiagStates;
5714
Vedant Kumar48b4f762018-04-14 01:40:48 +00005715 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005717 auto &Record = F.PragmaDiagMappings;
5718 if (Record.empty())
5719 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005720
Richard Smithd230de22017-01-26 01:01:01 +00005721 DiagStates.clear();
5722
5723 auto ReadDiagState =
5724 [&](const DiagState &BasedOn, SourceLocation Loc,
5725 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5726 unsigned BackrefID = Record[Idx++];
5727 if (BackrefID != 0)
5728 return DiagStates[BackrefID - 1];
5729
Guy Benyei11169dd2012-12-18 14:30:41 +00005730 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005731 Diag.DiagStates.push_back(BasedOn);
5732 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005733 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005734 unsigned Size = Record[Idx++];
5735 assert(Idx + Size * 2 <= Record.size() &&
5736 "Invalid data, not enough diag/map pairs");
5737 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005738 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005739 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005740 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005741 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5742 continue;
5743
5744 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5745
5746 // If this mapping was specified as a warning but the severity was
5747 // upgraded due to diagnostic settings, simulate the current diagnostic
5748 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005749 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5750 NewMapping.setSeverity(diag::Severity::Warning);
5751 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005752 }
5753
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005754 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005755 }
Richard Smithd230de22017-01-26 01:01:01 +00005756 return NewState;
5757 };
5758
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005759 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005760 DiagState *FirstState;
5761 if (F.Kind == MK_ImplicitModule) {
5762 // Implicitly-built modules are reused with different diagnostic
5763 // settings. Use the initial diagnostic state from Diag to simulate this
5764 // compilation's diagnostic settings.
5765 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5766 DiagStates.push_back(FirstState);
5767
5768 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005769 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005770 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005771 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005772 assert(Idx < Record.size() &&
5773 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005774 } else if (F.isModule()) {
5775 // For an explicit module, preserve the flags from the module build
5776 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5777 // -Wblah flags.
5778 unsigned Flags = Record[Idx++];
5779 DiagState Initial;
5780 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5781 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5782 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5783 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5784 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5785 Initial.ExtBehavior = (diag::Severity)Flags;
5786 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005787
Richard Smith6c2b5a82018-02-09 01:15:13 +00005788 assert(F.OriginalSourceFileID.isValid());
5789
Richard Smithe37391c2017-05-03 00:28:49 +00005790 // Set up the root buffer of the module to start with the initial
5791 // diagnostic state of the module itself, to cover files that contain no
5792 // explicit transitions (for which we did not serialize anything).
5793 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5794 .StateTransitions.push_back({FirstState, 0});
5795 } else {
5796 // For prefix ASTs, start with whatever the user configured on the
5797 // command line.
5798 Idx++; // Skip flags.
5799 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5800 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005801 }
Richard Smithd230de22017-01-26 01:01:01 +00005802
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005803 // Read the state transitions.
5804 unsigned NumLocations = Record[Idx++];
5805 while (NumLocations--) {
5806 assert(Idx < Record.size() &&
5807 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005808 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5809 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00005810 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00005811 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5812 unsigned Transitions = Record[Idx++];
5813
5814 // Note that we don't need to set up Parent/ParentOffset here, because
5815 // we won't be changing the diagnostic state within imported FileIDs
5816 // (other than perhaps appending to the main source file, which has no
5817 // parent).
5818 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5819 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5820 for (unsigned I = 0; I != Transitions; ++I) {
5821 unsigned Offset = Record[Idx++];
5822 auto *State =
5823 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5824 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 }
5826 }
Richard Smithd230de22017-01-26 01:01:01 +00005827
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005828 // Read the final state.
5829 assert(Idx < Record.size() &&
5830 "Invalid data, missing final pragma diagnostic state");
5831 SourceLocation CurStateLoc =
5832 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5833 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5834
5835 if (!F.isModule()) {
5836 Diag.DiagStatesByLoc.CurDiagState = CurState;
5837 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5838
5839 // Preserve the property that the imaginary root file describes the
5840 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005841 FileID NullFile;
5842 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005843 if (T.empty())
5844 T.push_back({CurState, 0});
5845 else
5846 T[0].State = CurState;
5847 }
5848
Richard Smithd230de22017-01-26 01:01:01 +00005849 // Don't try to read these mappings again.
5850 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 }
5852}
5853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005854/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00005855ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5856 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5857 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5858 ModuleFile *M = I->second;
5859 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5860}
5861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005862/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00005863///
5864/// The index is the type ID, shifted and minus the number of predefs. This
5865/// routine actually reads the record corresponding to the type at the given
5866/// location. It is a helper routine for GetType, which deals with reading type
5867/// IDs.
5868QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005869 assert(ContextObj && "reading type with no AST context");
5870 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005872 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005873
5874 // Keep track of where we are in the stream, then jump back there
5875 // after reading this type.
5876 SavedStreamPosition SavedPosition(DeclsCursor);
5877
5878 ReadingKindTracker ReadingKind(Read_Type, *this);
5879
5880 // Note that we are loading a type record.
5881 Deserializing AType(this);
5882
5883 unsigned Idx = 0;
5884 DeclsCursor.JumpToBit(Loc.Offset);
5885 RecordData Record;
5886 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005887 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 case TYPE_EXT_QUAL: {
5889 if (Record.size() != 2) {
5890 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005891 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 }
5893 QualType Base = readType(*Loc.F, Record, Idx);
5894 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5895 return Context.getQualifiedType(Base, Quals);
5896 }
5897
5898 case TYPE_COMPLEX: {
5899 if (Record.size() != 1) {
5900 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005901 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 }
5903 QualType ElemType = readType(*Loc.F, Record, Idx);
5904 return Context.getComplexType(ElemType);
5905 }
5906
5907 case TYPE_POINTER: {
5908 if (Record.size() != 1) {
5909 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005910 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005911 }
5912 QualType PointeeType = readType(*Loc.F, Record, Idx);
5913 return Context.getPointerType(PointeeType);
5914 }
5915
Reid Kleckner8a365022013-06-24 17:51:48 +00005916 case TYPE_DECAYED: {
5917 if (Record.size() != 1) {
5918 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005919 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00005920 }
5921 QualType OriginalType = readType(*Loc.F, Record, Idx);
5922 QualType DT = Context.getAdjustedParameterType(OriginalType);
5923 if (!isa<DecayedType>(DT))
5924 Error("Decayed type does not decay");
5925 return DT;
5926 }
5927
Reid Kleckner0503a872013-12-05 01:23:43 +00005928 case TYPE_ADJUSTED: {
5929 if (Record.size() != 2) {
5930 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005931 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00005932 }
5933 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5934 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5935 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5936 }
5937
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 case TYPE_BLOCK_POINTER: {
5939 if (Record.size() != 1) {
5940 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005941 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005942 }
5943 QualType PointeeType = readType(*Loc.F, Record, Idx);
5944 return Context.getBlockPointerType(PointeeType);
5945 }
5946
5947 case TYPE_LVALUE_REFERENCE: {
5948 if (Record.size() != 2) {
5949 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005950 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 }
5952 QualType PointeeType = readType(*Loc.F, Record, Idx);
5953 return Context.getLValueReferenceType(PointeeType, Record[1]);
5954 }
5955
5956 case TYPE_RVALUE_REFERENCE: {
5957 if (Record.size() != 1) {
5958 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005959 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 }
5961 QualType PointeeType = readType(*Loc.F, Record, Idx);
5962 return Context.getRValueReferenceType(PointeeType);
5963 }
5964
5965 case TYPE_MEMBER_POINTER: {
5966 if (Record.size() != 2) {
5967 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005968 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 }
5970 QualType PointeeType = readType(*Loc.F, Record, Idx);
5971 QualType ClassType = readType(*Loc.F, Record, Idx);
5972 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00005973 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005974
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5976 }
5977
5978 case TYPE_CONSTANT_ARRAY: {
5979 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005980 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 unsigned IndexTypeQuals = Record[2];
5982 unsigned Idx = 3;
5983 llvm::APInt Size = ReadAPInt(Record, Idx);
5984 return Context.getConstantArrayType(ElementType, Size,
5985 ASM, IndexTypeQuals);
5986 }
5987
5988 case TYPE_INCOMPLETE_ARRAY: {
5989 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005990 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 unsigned IndexTypeQuals = Record[2];
5992 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5993 }
5994
5995 case TYPE_VARIABLE_ARRAY: {
5996 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005997 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 unsigned IndexTypeQuals = Record[2];
5999 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6000 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6001 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6002 ASM, IndexTypeQuals,
6003 SourceRange(LBLoc, RBLoc));
6004 }
6005
6006 case TYPE_VECTOR: {
6007 if (Record.size() != 3) {
6008 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006009 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 }
6011
6012 QualType ElementType = readType(*Loc.F, Record, Idx);
6013 unsigned NumElements = Record[1];
6014 unsigned VecKind = Record[2];
6015 return Context.getVectorType(ElementType, NumElements,
6016 (VectorType::VectorKind)VecKind);
6017 }
6018
6019 case TYPE_EXT_VECTOR: {
6020 if (Record.size() != 3) {
6021 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006022 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 }
6024
6025 QualType ElementType = readType(*Loc.F, Record, Idx);
6026 unsigned NumElements = Record[1];
6027 return Context.getExtVectorType(ElementType, NumElements);
6028 }
6029
6030 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006031 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006033 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006034 }
6035 QualType ResultType = readType(*Loc.F, Record, Idx);
6036 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006037 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006038 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 return Context.getFunctionNoProtoType(ResultType, Info);
6040 }
6041
6042 case TYPE_FUNCTION_PROTO: {
6043 QualType ResultType = readType(*Loc.F, Record, Idx);
6044
6045 FunctionProtoType::ExtProtoInfo EPI;
6046 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6047 /*hasregparm*/ Record[2],
6048 /*regparm*/ Record[3],
6049 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006050 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006051 /*nocallersavedregs*/ Record[6],
6052 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006053
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006054 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006055
6056 EPI.Variadic = Record[Idx++];
6057 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006058 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006060 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006061 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006062
6063 unsigned NumParams = Record[Idx++];
6064 SmallVector<QualType, 16> ParamTypes;
6065 for (unsigned I = 0; I != NumParams; ++I)
6066 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6067
John McCall18afab72016-03-01 00:49:02 +00006068 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6069 if (Idx != Record.size()) {
6070 for (unsigned I = 0; I != NumParams; ++I)
6071 ExtParameterInfos.push_back(
6072 FunctionProtoType::ExtParameterInfo
6073 ::getFromOpaqueValue(Record[Idx++]));
6074 EPI.ExtParameterInfos = ExtParameterInfos.data();
6075 }
6076
6077 assert(Idx == Record.size());
6078
Jordan Rose5c382722013-03-08 21:51:21 +00006079 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 }
6081
6082 case TYPE_UNRESOLVED_USING: {
6083 unsigned Idx = 0;
6084 return Context.getTypeDeclType(
6085 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6086 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006087
Guy Benyei11169dd2012-12-18 14:30:41 +00006088 case TYPE_TYPEDEF: {
6089 if (Record.size() != 2) {
6090 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006091 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 }
6093 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006094 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 QualType Canonical = readType(*Loc.F, Record, Idx);
6096 if (!Canonical.isNull())
6097 Canonical = Context.getCanonicalType(Canonical);
6098 return Context.getTypedefType(Decl, Canonical);
6099 }
6100
6101 case TYPE_TYPEOF_EXPR:
6102 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6103
6104 case TYPE_TYPEOF: {
6105 if (Record.size() != 1) {
6106 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006107 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 }
6109 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6110 return Context.getTypeOfType(UnderlyingType);
6111 }
6112
6113 case TYPE_DECLTYPE: {
6114 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6115 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6116 }
6117
6118 case TYPE_UNARY_TRANSFORM: {
6119 QualType BaseType = readType(*Loc.F, Record, Idx);
6120 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006121 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6123 }
6124
Richard Smith74aeef52013-04-26 16:15:35 +00006125 case TYPE_AUTO: {
6126 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006127 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006128 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006129 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006131
Richard Smith600b5262017-01-26 20:40:47 +00006132 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6133 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6134 QualType Deduced = readType(*Loc.F, Record, Idx);
6135 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6136 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6137 IsDependent);
6138 }
6139
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 case TYPE_RECORD: {
6141 if (Record.size() != 2) {
6142 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006143 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 }
6145 unsigned Idx = 0;
6146 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006147 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006148 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6149 QualType T = Context.getRecordType(RD);
6150 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6151 return T;
6152 }
6153
6154 case TYPE_ENUM: {
6155 if (Record.size() != 2) {
6156 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006157 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 }
6159 unsigned Idx = 0;
6160 bool IsDependent = Record[Idx++];
6161 QualType T
6162 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6163 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6164 return T;
6165 }
6166
6167 case TYPE_ATTRIBUTED: {
6168 if (Record.size() != 3) {
6169 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006170 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 }
6172 QualType modifiedType = readType(*Loc.F, Record, Idx);
6173 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006174 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 return Context.getAttributedType(kind, modifiedType, equivalentType);
6176 }
6177
6178 case TYPE_PAREN: {
6179 if (Record.size() != 1) {
6180 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006181 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 }
6183 QualType InnerType = readType(*Loc.F, Record, Idx);
6184 return Context.getParenType(InnerType);
6185 }
6186
6187 case TYPE_PACK_EXPANSION: {
6188 if (Record.size() != 2) {
6189 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006190 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 }
6192 QualType Pattern = readType(*Loc.F, Record, Idx);
6193 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006194 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006195 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 if (Record[1])
6197 NumExpansions = Record[1] - 1;
6198 return Context.getPackExpansionType(Pattern, NumExpansions);
6199 }
6200
6201 case TYPE_ELABORATED: {
6202 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006203 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6205 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006206 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6207 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 }
6209
6210 case TYPE_OBJC_INTERFACE: {
6211 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006212 ObjCInterfaceDecl *ItfD
6213 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6215 }
6216
Manman Rene6be26c2016-09-13 17:25:08 +00006217 case TYPE_OBJC_TYPE_PARAM: {
6218 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006219 ObjCTypeParamDecl *Decl
6220 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006221 unsigned NumProtos = Record[Idx++];
6222 SmallVector<ObjCProtocolDecl*, 4> Protos;
6223 for (unsigned I = 0; I != NumProtos; ++I)
6224 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6225 return Context.getObjCTypeParamType(Decl, Protos);
6226 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006227
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 case TYPE_OBJC_OBJECT: {
6229 unsigned Idx = 0;
6230 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006231 unsigned NumTypeArgs = Record[Idx++];
6232 SmallVector<QualType, 4> TypeArgs;
6233 for (unsigned I = 0; I != NumTypeArgs; ++I)
6234 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 unsigned NumProtos = Record[Idx++];
6236 SmallVector<ObjCProtocolDecl*, 4> Protos;
6237 for (unsigned I = 0; I != NumProtos; ++I)
6238 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006239 bool IsKindOf = Record[Idx++];
6240 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 }
6242
6243 case TYPE_OBJC_OBJECT_POINTER: {
6244 unsigned Idx = 0;
6245 QualType Pointee = readType(*Loc.F, Record, Idx);
6246 return Context.getObjCObjectPointerType(Pointee);
6247 }
6248
6249 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6250 unsigned Idx = 0;
6251 QualType Parm = readType(*Loc.F, Record, Idx);
6252 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006253 return Context.getSubstTemplateTypeParmType(
6254 cast<TemplateTypeParmType>(Parm),
6255 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 }
6257
6258 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6259 unsigned Idx = 0;
6260 QualType Parm = readType(*Loc.F, Record, Idx);
6261 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6262 return Context.getSubstTemplateTypeParmPackType(
6263 cast<TemplateTypeParmType>(Parm),
6264 ArgPack);
6265 }
6266
6267 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006268 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6270 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6271 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006272 const Type *T = nullptr;
6273 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6274 if (const Type *Existing = DI->getTypeForDecl()) {
6275 T = Existing;
6276 break;
6277 }
6278 }
6279 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006280 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006281 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6282 DI->setTypeForDecl(T);
6283 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006284 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 }
6286
6287 case TYPE_TEMPLATE_TYPE_PARM: {
6288 unsigned Idx = 0;
6289 unsigned Depth = Record[Idx++];
6290 unsigned Index = Record[Idx++];
6291 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006292 TemplateTypeParmDecl *D
6293 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6295 }
6296
6297 case TYPE_DEPENDENT_NAME: {
6298 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006299 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006301 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 QualType Canon = readType(*Loc.F, Record, Idx);
6303 if (!Canon.isNull())
6304 Canon = Context.getCanonicalType(Canon);
6305 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6306 }
6307
6308 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6309 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006310 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006312 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 unsigned NumArgs = Record[Idx++];
6314 SmallVector<TemplateArgument, 8> Args;
6315 Args.reserve(NumArgs);
6316 while (NumArgs--)
6317 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6318 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006319 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 }
6321
6322 case TYPE_DEPENDENT_SIZED_ARRAY: {
6323 unsigned Idx = 0;
6324
6325 // ArrayType
6326 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006327 ArrayType::ArraySizeModifier ASM
6328 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 unsigned IndexTypeQuals = Record[Idx++];
6330
6331 // DependentSizedArrayType
6332 Expr *NumElts = ReadExpr(*Loc.F);
6333 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6334
6335 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6336 IndexTypeQuals, Brackets);
6337 }
6338
6339 case TYPE_TEMPLATE_SPECIALIZATION: {
6340 unsigned Idx = 0;
6341 bool IsDependent = Record[Idx++];
6342 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6343 SmallVector<TemplateArgument, 8> Args;
6344 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6345 QualType Underlying = readType(*Loc.F, Record, Idx);
6346 QualType T;
6347 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006348 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006350 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6352 return T;
6353 }
6354
6355 case TYPE_ATOMIC: {
6356 if (Record.size() != 1) {
6357 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006358 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 }
6360 QualType ValueType = readType(*Loc.F, Record, Idx);
6361 return Context.getAtomicType(ValueType);
6362 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006363
Joey Goulye3c85de2016-12-01 11:30:49 +00006364 case TYPE_PIPE: {
6365 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006366 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006367 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006368 }
6369
6370 // Reading the pipe element type.
6371 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006372 unsigned ReadOnly = Record[1];
6373 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006374 }
6375
Erich Keanef702b022018-07-13 19:46:04 +00006376 case TYPE_DEPENDENT_SIZED_VECTOR: {
6377 unsigned Idx = 0;
6378 QualType ElementType = readType(*Loc.F, Record, Idx);
6379 Expr *SizeExpr = ReadExpr(*Loc.F);
6380 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6381 unsigned VecKind = Record[Idx];
6382
6383 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6384 (VectorType::VectorKind)VecKind);
6385 }
6386
Alex Lorenz00aee432017-03-22 10:04:48 +00006387 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6388 unsigned Idx = 0;
6389
6390 // DependentSizedExtVectorType
6391 QualType ElementType = readType(*Loc.F, Record, Idx);
6392 Expr *SizeExpr = ReadExpr(*Loc.F);
6393 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6394
6395 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6396 AttrLoc);
6397 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006398
6399 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6400 unsigned Idx = 0;
6401
6402 // DependentAddressSpaceType
6403 QualType PointeeType = readType(*Loc.F, Record, Idx);
6404 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6405 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6406
6407 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6408 AttrLoc);
6409 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 }
6411 llvm_unreachable("Invalid TypeCode!");
6412}
6413
Richard Smith564417a2014-03-20 21:47:22 +00006414void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6415 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006416 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006417 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006418 ExceptionSpecificationType EST =
6419 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006420 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006421 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006422 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006423 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006424 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006425 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006426 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006427 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006428 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6429 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006430 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006431 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006432 }
6433}
6434
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006435namespace clang {
6436
6437class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006438 ModuleFile *F;
6439 ASTReader *Reader;
6440 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 unsigned &Idx;
6442
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006443 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006444 return Reader->ReadSourceLocation(*F, Record, Idx);
6445 }
6446
6447 TypeSourceInfo *GetTypeSourceInfo() {
6448 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6449 }
6450
6451 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6452 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 }
6454
Richard Smithe43e2b32018-08-20 21:47:29 +00006455 Attr *ReadAttr() {
6456 return Reader->ReadAttr(*F, Record, Idx);
6457 }
6458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006460 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006461 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006462 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006463
6464 // We want compile-time assurance that we've enumerated all of
6465 // these, so unfortunately we have to declare them first, then
6466 // define them out-of-line.
6467#define ABSTRACT_TYPELOC(CLASS, PARENT)
6468#define TYPELOC(CLASS, PARENT) \
6469 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6470#include "clang/AST/TypeLocNodes.def"
6471
6472 void VisitFunctionTypeLoc(FunctionTypeLoc);
6473 void VisitArrayTypeLoc(ArrayTypeLoc);
6474};
6475
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006476} // namespace clang
6477
Guy Benyei11169dd2012-12-18 14:30:41 +00006478void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6479 // nothing to do
6480}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006481
Guy Benyei11169dd2012-12-18 14:30:41 +00006482void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006483 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006485 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6486 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6487 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6488 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 }
6490}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006491
Guy Benyei11169dd2012-12-18 14:30:41 +00006492void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006493 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006494}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006495
Guy Benyei11169dd2012-12-18 14:30:41 +00006496void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006497 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006498}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006499
Reid Kleckner8a365022013-06-24 17:51:48 +00006500void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6501 // nothing to do
6502}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006503
Reid Kleckner0503a872013-12-05 01:23:43 +00006504void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6505 // nothing to do
6506}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006507
Guy Benyei11169dd2012-12-18 14:30:41 +00006508void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006509 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006510}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006511
Guy Benyei11169dd2012-12-18 14:30:41 +00006512void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006513 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006514}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006515
Guy Benyei11169dd2012-12-18 14:30:41 +00006516void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006517 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006518}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006519
Guy Benyei11169dd2012-12-18 14:30:41 +00006520void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006521 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006522 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006523}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006524
Guy Benyei11169dd2012-12-18 14:30:41 +00006525void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006526 TL.setLBracketLoc(ReadSourceLocation());
6527 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006528 if (Record[Idx++])
6529 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 else
Craig Toppera13603a2014-05-22 05:54:18 +00006531 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006532}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006533
Guy Benyei11169dd2012-12-18 14:30:41 +00006534void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6535 VisitArrayTypeLoc(TL);
6536}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006537
Guy Benyei11169dd2012-12-18 14:30:41 +00006538void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6539 VisitArrayTypeLoc(TL);
6540}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006541
Guy Benyei11169dd2012-12-18 14:30:41 +00006542void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6543 VisitArrayTypeLoc(TL);
6544}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006545
Guy Benyei11169dd2012-12-18 14:30:41 +00006546void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6547 DependentSizedArrayTypeLoc TL) {
6548 VisitArrayTypeLoc(TL);
6549}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006550
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006551void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6552 DependentAddressSpaceTypeLoc TL) {
6553
6554 TL.setAttrNameLoc(ReadSourceLocation());
6555 SourceRange range;
6556 range.setBegin(ReadSourceLocation());
6557 range.setEnd(ReadSourceLocation());
6558 TL.setAttrOperandParensRange(range);
6559 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6560}
6561
Guy Benyei11169dd2012-12-18 14:30:41 +00006562void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6563 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006564 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006565}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006566
Guy Benyei11169dd2012-12-18 14:30:41 +00006567void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006568 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006569}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006570
Erich Keanef702b022018-07-13 19:46:04 +00006571void TypeLocReader::VisitDependentVectorTypeLoc(
6572 DependentVectorTypeLoc TL) {
6573 TL.setNameLoc(ReadSourceLocation());
6574}
6575
Guy Benyei11169dd2012-12-18 14:30:41 +00006576void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006577 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006578}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006579
Guy Benyei11169dd2012-12-18 14:30:41 +00006580void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006581 TL.setLocalRangeBegin(ReadSourceLocation());
6582 TL.setLParenLoc(ReadSourceLocation());
6583 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006584 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6585 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006586 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006587 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006588 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 }
6590}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6593 VisitFunctionTypeLoc(TL);
6594}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6597 VisitFunctionTypeLoc(TL);
6598}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006601 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006602}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006603
Guy Benyei11169dd2012-12-18 14:30:41 +00006604void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006605 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006606}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006607
Guy Benyei11169dd2012-12-18 14:30:41 +00006608void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006609 TL.setTypeofLoc(ReadSourceLocation());
6610 TL.setLParenLoc(ReadSourceLocation());
6611 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006612}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006613
Guy Benyei11169dd2012-12-18 14:30:41 +00006614void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006615 TL.setTypeofLoc(ReadSourceLocation());
6616 TL.setLParenLoc(ReadSourceLocation());
6617 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006618 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006619}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006622 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006623}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006624
Guy Benyei11169dd2012-12-18 14:30:41 +00006625void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006626 TL.setKWLoc(ReadSourceLocation());
6627 TL.setLParenLoc(ReadSourceLocation());
6628 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006629 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006630}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006631
Guy Benyei11169dd2012-12-18 14:30:41 +00006632void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006633 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006634}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006635
Richard Smith600b5262017-01-26 20:40:47 +00006636void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6637 DeducedTemplateSpecializationTypeLoc TL) {
6638 TL.setTemplateNameLoc(ReadSourceLocation());
6639}
6640
Guy Benyei11169dd2012-12-18 14:30:41 +00006641void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006642 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006644
Guy Benyei11169dd2012-12-18 14:30:41 +00006645void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006646 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006647}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006648
Guy Benyei11169dd2012-12-18 14:30:41 +00006649void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006650 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006654 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006655}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006656
Guy Benyei11169dd2012-12-18 14:30:41 +00006657void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6658 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006659 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006660}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006661
Guy Benyei11169dd2012-12-18 14:30:41 +00006662void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6663 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006664 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006665}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006666
Guy Benyei11169dd2012-12-18 14:30:41 +00006667void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6668 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006669 TL.setTemplateKeywordLoc(ReadSourceLocation());
6670 TL.setTemplateNameLoc(ReadSourceLocation());
6671 TL.setLAngleLoc(ReadSourceLocation());
6672 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006674 TL.setArgLocInfo(
6675 i,
6676 Reader->GetTemplateArgumentLocInfo(
6677 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006678}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006681 TL.setLParenLoc(ReadSourceLocation());
6682 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006683}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006684
Guy Benyei11169dd2012-12-18 14:30:41 +00006685void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006686 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006687 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006688}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006689
Guy Benyei11169dd2012-12-18 14:30:41 +00006690void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006691 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006692}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006693
Guy Benyei11169dd2012-12-18 14:30:41 +00006694void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006695 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006696 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006697 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006698}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006699
Guy Benyei11169dd2012-12-18 14:30:41 +00006700void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6701 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006702 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006703 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006704 TL.setTemplateKeywordLoc(ReadSourceLocation());
6705 TL.setTemplateNameLoc(ReadSourceLocation());
6706 TL.setLAngleLoc(ReadSourceLocation());
6707 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006709 TL.setArgLocInfo(
6710 I,
6711 Reader->GetTemplateArgumentLocInfo(
6712 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006713}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006716 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006717}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006718
Guy Benyei11169dd2012-12-18 14:30:41 +00006719void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006720 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006721}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006722
Manman Rene6be26c2016-09-13 17:25:08 +00006723void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6724 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006725 TL.setProtocolLAngleLoc(ReadSourceLocation());
6726 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006727 }
6728 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006729 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006730}
6731
Guy Benyei11169dd2012-12-18 14:30:41 +00006732void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006733 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006734 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6735 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006736 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006737 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006738 TL.setProtocolLAngleLoc(ReadSourceLocation());
6739 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006741 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006742}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006743
Guy Benyei11169dd2012-12-18 14:30:41 +00006744void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006745 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006746}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006747
Guy Benyei11169dd2012-12-18 14:30:41 +00006748void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006749 TL.setKWLoc(ReadSourceLocation());
6750 TL.setLParenLoc(ReadSourceLocation());
6751 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006752}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006753
Xiuli Pan9c14e282016-01-09 12:53:17 +00006754void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006755 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006756}
Guy Benyei11169dd2012-12-18 14:30:41 +00006757
Richard Smithc23d7342018-06-29 20:46:25 +00006758void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
6759 unsigned &Idx, TypeLoc TL) {
6760 TypeLocReader TLR(F, *this, Record, Idx);
6761 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6762 TLR.Visit(TL);
6763}
6764
David L. Jonesbe1557a2016-12-21 00:17:49 +00006765TypeSourceInfo *
6766ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6767 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 QualType InfoTy = readType(F, Record, Idx);
6769 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006770 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006771
6772 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00006773 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006774 return TInfo;
6775}
6776
6777QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006778 assert(ContextObj && "reading type with no AST context");
6779 ASTContext &Context = *ContextObj;
6780
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 unsigned FastQuals = ID & Qualifiers::FastMask;
6782 unsigned Index = ID >> Qualifiers::FastWidth;
6783
6784 if (Index < NUM_PREDEF_TYPE_IDS) {
6785 QualType T;
6786 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006787 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006788 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006789 case PREDEF_TYPE_VOID_ID:
6790 T = Context.VoidTy;
6791 break;
6792 case PREDEF_TYPE_BOOL_ID:
6793 T = Context.BoolTy;
6794 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006795 case PREDEF_TYPE_CHAR_U_ID:
6796 case PREDEF_TYPE_CHAR_S_ID:
6797 // FIXME: Check that the signedness of CharTy is correct!
6798 T = Context.CharTy;
6799 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006800 case PREDEF_TYPE_UCHAR_ID:
6801 T = Context.UnsignedCharTy;
6802 break;
6803 case PREDEF_TYPE_USHORT_ID:
6804 T = Context.UnsignedShortTy;
6805 break;
6806 case PREDEF_TYPE_UINT_ID:
6807 T = Context.UnsignedIntTy;
6808 break;
6809 case PREDEF_TYPE_ULONG_ID:
6810 T = Context.UnsignedLongTy;
6811 break;
6812 case PREDEF_TYPE_ULONGLONG_ID:
6813 T = Context.UnsignedLongLongTy;
6814 break;
6815 case PREDEF_TYPE_UINT128_ID:
6816 T = Context.UnsignedInt128Ty;
6817 break;
6818 case PREDEF_TYPE_SCHAR_ID:
6819 T = Context.SignedCharTy;
6820 break;
6821 case PREDEF_TYPE_WCHAR_ID:
6822 T = Context.WCharTy;
6823 break;
6824 case PREDEF_TYPE_SHORT_ID:
6825 T = Context.ShortTy;
6826 break;
6827 case PREDEF_TYPE_INT_ID:
6828 T = Context.IntTy;
6829 break;
6830 case PREDEF_TYPE_LONG_ID:
6831 T = Context.LongTy;
6832 break;
6833 case PREDEF_TYPE_LONGLONG_ID:
6834 T = Context.LongLongTy;
6835 break;
6836 case PREDEF_TYPE_INT128_ID:
6837 T = Context.Int128Ty;
6838 break;
6839 case PREDEF_TYPE_HALF_ID:
6840 T = Context.HalfTy;
6841 break;
6842 case PREDEF_TYPE_FLOAT_ID:
6843 T = Context.FloatTy;
6844 break;
6845 case PREDEF_TYPE_DOUBLE_ID:
6846 T = Context.DoubleTy;
6847 break;
6848 case PREDEF_TYPE_LONGDOUBLE_ID:
6849 T = Context.LongDoubleTy;
6850 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006851 case PREDEF_TYPE_SHORT_ACCUM_ID:
6852 T = Context.ShortAccumTy;
6853 break;
6854 case PREDEF_TYPE_ACCUM_ID:
6855 T = Context.AccumTy;
6856 break;
6857 case PREDEF_TYPE_LONG_ACCUM_ID:
6858 T = Context.LongAccumTy;
6859 break;
6860 case PREDEF_TYPE_USHORT_ACCUM_ID:
6861 T = Context.UnsignedShortAccumTy;
6862 break;
6863 case PREDEF_TYPE_UACCUM_ID:
6864 T = Context.UnsignedAccumTy;
6865 break;
6866 case PREDEF_TYPE_ULONG_ACCUM_ID:
6867 T = Context.UnsignedLongAccumTy;
6868 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006869 case PREDEF_TYPE_SHORT_FRACT_ID:
6870 T = Context.ShortFractTy;
6871 break;
6872 case PREDEF_TYPE_FRACT_ID:
6873 T = Context.FractTy;
6874 break;
6875 case PREDEF_TYPE_LONG_FRACT_ID:
6876 T = Context.LongFractTy;
6877 break;
6878 case PREDEF_TYPE_USHORT_FRACT_ID:
6879 T = Context.UnsignedShortFractTy;
6880 break;
6881 case PREDEF_TYPE_UFRACT_ID:
6882 T = Context.UnsignedFractTy;
6883 break;
6884 case PREDEF_TYPE_ULONG_FRACT_ID:
6885 T = Context.UnsignedLongFractTy;
6886 break;
6887 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6888 T = Context.SatShortAccumTy;
6889 break;
6890 case PREDEF_TYPE_SAT_ACCUM_ID:
6891 T = Context.SatAccumTy;
6892 break;
6893 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6894 T = Context.SatLongAccumTy;
6895 break;
6896 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6897 T = Context.SatUnsignedShortAccumTy;
6898 break;
6899 case PREDEF_TYPE_SAT_UACCUM_ID:
6900 T = Context.SatUnsignedAccumTy;
6901 break;
6902 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6903 T = Context.SatUnsignedLongAccumTy;
6904 break;
6905 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6906 T = Context.SatShortFractTy;
6907 break;
6908 case PREDEF_TYPE_SAT_FRACT_ID:
6909 T = Context.SatFractTy;
6910 break;
6911 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6912 T = Context.SatLongFractTy;
6913 break;
6914 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6915 T = Context.SatUnsignedShortFractTy;
6916 break;
6917 case PREDEF_TYPE_SAT_UFRACT_ID:
6918 T = Context.SatUnsignedFractTy;
6919 break;
6920 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6921 T = Context.SatUnsignedLongFractTy;
6922 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006923 case PREDEF_TYPE_FLOAT16_ID:
6924 T = Context.Float16Ty;
6925 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006926 case PREDEF_TYPE_FLOAT128_ID:
6927 T = Context.Float128Ty;
6928 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006929 case PREDEF_TYPE_OVERLOAD_ID:
6930 T = Context.OverloadTy;
6931 break;
6932 case PREDEF_TYPE_BOUND_MEMBER:
6933 T = Context.BoundMemberTy;
6934 break;
6935 case PREDEF_TYPE_PSEUDO_OBJECT:
6936 T = Context.PseudoObjectTy;
6937 break;
6938 case PREDEF_TYPE_DEPENDENT_ID:
6939 T = Context.DependentTy;
6940 break;
6941 case PREDEF_TYPE_UNKNOWN_ANY:
6942 T = Context.UnknownAnyTy;
6943 break;
6944 case PREDEF_TYPE_NULLPTR_ID:
6945 T = Context.NullPtrTy;
6946 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006947 case PREDEF_TYPE_CHAR8_ID:
6948 T = Context.Char8Ty;
6949 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006950 case PREDEF_TYPE_CHAR16_ID:
6951 T = Context.Char16Ty;
6952 break;
6953 case PREDEF_TYPE_CHAR32_ID:
6954 T = Context.Char32Ty;
6955 break;
6956 case PREDEF_TYPE_OBJC_ID:
6957 T = Context.ObjCBuiltinIdTy;
6958 break;
6959 case PREDEF_TYPE_OBJC_CLASS:
6960 T = Context.ObjCBuiltinClassTy;
6961 break;
6962 case PREDEF_TYPE_OBJC_SEL:
6963 T = Context.ObjCBuiltinSelTy;
6964 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006965#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6966 case PREDEF_TYPE_##Id##_ID: \
6967 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006968 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006969#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006970#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6971 case PREDEF_TYPE_##Id##_ID: \
6972 T = Context.Id##Ty; \
6973 break;
6974#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006975 case PREDEF_TYPE_SAMPLER_ID:
6976 T = Context.OCLSamplerTy;
6977 break;
6978 case PREDEF_TYPE_EVENT_ID:
6979 T = Context.OCLEventTy;
6980 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006981 case PREDEF_TYPE_CLK_EVENT_ID:
6982 T = Context.OCLClkEventTy;
6983 break;
6984 case PREDEF_TYPE_QUEUE_ID:
6985 T = Context.OCLQueueTy;
6986 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006987 case PREDEF_TYPE_RESERVE_ID_ID:
6988 T = Context.OCLReserveIDTy;
6989 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006990 case PREDEF_TYPE_AUTO_DEDUCT:
6991 T = Context.getAutoDeductType();
6992 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006993 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6994 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6997 T = Context.ARCUnbridgedCastTy;
6998 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 case PREDEF_TYPE_BUILTIN_FN:
7000 T = Context.BuiltinFnTy;
7001 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007002 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7003 T = Context.OMPArraySectionTy;
7004 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 }
7006
7007 assert(!T.isNull() && "Unknown predefined type");
7008 return T.withFastQualifiers(FastQuals);
7009 }
7010
7011 Index -= NUM_PREDEF_TYPE_IDS;
7012 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7013 if (TypesLoaded[Index].isNull()) {
7014 TypesLoaded[Index] = readTypeRecord(Index);
7015 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007016 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007017
7018 TypesLoaded[Index]->setFromAST();
7019 if (DeserializationListener)
7020 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7021 TypesLoaded[Index]);
7022 }
7023
7024 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7025}
7026
7027QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7028 return GetType(getGlobalTypeID(F, LocalID));
7029}
7030
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007031serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007032ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7033 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7034 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7037 return LocalID;
7038
Richard Smith37a93df2017-02-18 00:32:02 +00007039 if (!F.ModuleOffsetMap.empty())
7040 ReadModuleOffsetMap(F);
7041
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7043 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7044 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007045
Guy Benyei11169dd2012-12-18 14:30:41 +00007046 unsigned GlobalIndex = LocalIndex + I->second;
7047 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7048}
7049
7050TemplateArgumentLocInfo
7051ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7052 TemplateArgument::ArgKind Kind,
7053 const RecordData &Record,
7054 unsigned &Index) {
7055 switch (Kind) {
7056 case TemplateArgument::Expression:
7057 return ReadExpr(F);
7058 case TemplateArgument::Type:
7059 return GetTypeSourceInfo(F, Record, Index);
7060 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007061 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 Index);
7063 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7064 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7065 SourceLocation());
7066 }
7067 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007068 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007069 Index);
7070 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7071 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007072 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 EllipsisLoc);
7074 }
7075 case TemplateArgument::Null:
7076 case TemplateArgument::Integral:
7077 case TemplateArgument::Declaration:
7078 case TemplateArgument::NullPtr:
7079 case TemplateArgument::Pack:
7080 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007081 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007082 }
7083 llvm_unreachable("unexpected template argument loc");
7084}
7085
7086TemplateArgumentLoc
7087ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7088 const RecordData &Record, unsigned &Index) {
7089 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7090
7091 if (Arg.getKind() == TemplateArgument::Expression) {
7092 if (Record[Index++]) // bool InfoHasSameExpr.
7093 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7094 }
7095 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7096 Record, Index));
7097}
7098
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007099const ASTTemplateArgumentListInfo*
7100ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7101 const RecordData &Record,
7102 unsigned &Index) {
7103 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7104 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7105 unsigned NumArgsAsWritten = Record[Index++];
7106 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7107 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7108 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7109 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7110}
7111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7113 return GetDecl(ID);
7114}
7115
Richard Smith053f6c62014-05-16 23:01:30 +00007116void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007117 if (NumCurrentElementsDeserializing) {
7118 // We arrange to not care about the complete redeclaration chain while we're
7119 // deserializing. Just remember that the AST has marked this one as complete
7120 // but that it's not actually complete yet, so we know we still need to
7121 // complete it later.
7122 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7123 return;
7124 }
7125
Richard Smith053f6c62014-05-16 23:01:30 +00007126 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7127
Richard Smith053f6c62014-05-16 23:01:30 +00007128 // If this is a named declaration, complete it by looking it up
7129 // within its context.
7130 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007131 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007132 // all mergeable entities within it.
7133 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7134 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7135 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007136 if (!getContext().getLangOpts().CPlusPlus &&
7137 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007138 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007139 // the identifier instead. (For C++ modules, we don't store decls
7140 // in the serialized identifier table, so we do the lookup in the TU.)
7141 auto *II = Name.getAsIdentifierInfo();
7142 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007143 if (II->isOutOfDate())
7144 updateOutOfDateIdentifier(*II);
7145 } else
7146 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007147 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007148 // Find all declarations of this kind from the relevant context.
7149 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7150 auto *DC = cast<DeclContext>(DCDecl);
7151 SmallVector<Decl*, 8> Decls;
7152 FindExternalLexicalDecls(
7153 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7154 }
Richard Smith053f6c62014-05-16 23:01:30 +00007155 }
7156 }
Richard Smith50895422015-01-31 03:04:55 +00007157
7158 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7159 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7160 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7161 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7162 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7163 if (auto *Template = FD->getPrimaryTemplate())
7164 Template->LoadLazySpecializations();
7165 }
Richard Smith053f6c62014-05-16 23:01:30 +00007166}
7167
Richard Smithc2bb8182015-03-24 06:36:48 +00007168CXXCtorInitializer **
7169ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7170 RecordLocation Loc = getLocalBitOffset(Offset);
7171 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7172 SavedStreamPosition SavedPosition(Cursor);
7173 Cursor.JumpToBit(Loc.Offset);
7174 ReadingKindTracker ReadingKind(Read_Decl, *this);
7175
7176 RecordData Record;
7177 unsigned Code = Cursor.ReadCode();
7178 unsigned RecCode = Cursor.readRecord(Code, Record);
7179 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7180 Error("malformed AST file: missing C++ ctor initializers");
7181 return nullptr;
7182 }
7183
7184 unsigned Idx = 0;
7185 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7186}
7187
Guy Benyei11169dd2012-12-18 14:30:41 +00007188CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007189 assert(ContextObj && "reading base specifiers with no AST context");
7190 ASTContext &Context = *ContextObj;
7191
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007193 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 SavedStreamPosition SavedPosition(Cursor);
7195 Cursor.JumpToBit(Loc.Offset);
7196 ReadingKindTracker ReadingKind(Read_Decl, *this);
7197 RecordData Record;
7198 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007199 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007201 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007202 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 }
7204
7205 unsigned Idx = 0;
7206 unsigned NumBases = Record[Idx++];
7207 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007208 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 for (unsigned I = 0; I != NumBases; ++I)
7210 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7211 return Bases;
7212}
7213
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007214serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007215ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7216 if (LocalID < NUM_PREDEF_DECL_IDS)
7217 return LocalID;
7218
Richard Smith37a93df2017-02-18 00:32:02 +00007219 if (!F.ModuleOffsetMap.empty())
7220 ReadModuleOffsetMap(F);
7221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7223 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7224 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007225
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 return LocalID + I->second;
7227}
7228
7229bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7230 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007231 // Predefined decls aren't from any module.
7232 if (ID < NUM_PREDEF_DECL_IDS)
7233 return false;
7234
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007235 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007236 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007237}
7238
Douglas Gregor9f782892013-01-21 15:25:38 +00007239ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007241 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7243 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7244 return I->second;
7245}
7246
7247SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7248 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007249 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007250
Guy Benyei11169dd2012-12-18 14:30:41 +00007251 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7252
7253 if (Index > DeclsLoaded.size()) {
7254 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007255 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007256 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007257
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 if (Decl *D = DeclsLoaded[Index])
7259 return D->getLocation();
7260
Richard Smithcb34bd32016-03-27 07:28:06 +00007261 SourceLocation Loc;
7262 DeclCursorForID(ID, Loc);
7263 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007264}
7265
Richard Smithfe620d22015-03-05 23:24:12 +00007266static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7267 switch (ID) {
7268 case PREDEF_DECL_NULL_ID:
7269 return nullptr;
7270
7271 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7272 return Context.getTranslationUnitDecl();
7273
7274 case PREDEF_DECL_OBJC_ID_ID:
7275 return Context.getObjCIdDecl();
7276
7277 case PREDEF_DECL_OBJC_SEL_ID:
7278 return Context.getObjCSelDecl();
7279
7280 case PREDEF_DECL_OBJC_CLASS_ID:
7281 return Context.getObjCClassDecl();
7282
7283 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7284 return Context.getObjCProtocolDecl();
7285
7286 case PREDEF_DECL_INT_128_ID:
7287 return Context.getInt128Decl();
7288
7289 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7290 return Context.getUInt128Decl();
7291
7292 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7293 return Context.getObjCInstanceTypeDecl();
7294
7295 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7296 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007297
Richard Smith9b88a4c2015-07-27 05:40:23 +00007298 case PREDEF_DECL_VA_LIST_TAG:
7299 return Context.getVaListTagDecl();
7300
Charles Davisc7d5c942015-09-17 20:55:33 +00007301 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7302 return Context.getBuiltinMSVaListDecl();
7303
Richard Smithf19e1272015-03-07 00:04:49 +00007304 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7305 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007306
7307 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7308 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007309
7310 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7311 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007312
7313 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7314 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007315
7316 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7317 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007318 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007319 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007320}
7321
Richard Smithcd45dbc2014-04-19 03:48:30 +00007322Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007323 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007324 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007325 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007326 if (D) {
7327 // Track that we have merged the declaration with ID \p ID into the
7328 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007329 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007330 if (Merged.empty())
7331 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 }
Richard Smithfe620d22015-03-05 23:24:12 +00007333 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007335
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7337
7338 if (Index >= DeclsLoaded.size()) {
7339 assert(0 && "declaration ID out-of-range for AST file");
7340 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007341 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007342 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007343
7344 return DeclsLoaded[Index];
7345}
7346
7347Decl *ASTReader::GetDecl(DeclID ID) {
7348 if (ID < NUM_PREDEF_DECL_IDS)
7349 return GetExistingDecl(ID);
7350
7351 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7352
7353 if (Index >= DeclsLoaded.size()) {
7354 assert(0 && "declaration ID out-of-range for AST file");
7355 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007356 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007357 }
7358
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 if (!DeclsLoaded[Index]) {
7360 ReadDeclRecord(ID);
7361 if (DeserializationListener)
7362 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7363 }
7364
7365 return DeclsLoaded[Index];
7366}
7367
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007368DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007369 DeclID GlobalID) {
7370 if (GlobalID < NUM_PREDEF_DECL_IDS)
7371 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007372
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7374 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7375 ModuleFile *Owner = I->second;
7376
7377 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7378 = M.GlobalToLocalDeclIDs.find(Owner);
7379 if (Pos == M.GlobalToLocalDeclIDs.end())
7380 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007381
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 return GlobalID - Owner->BaseDeclID + Pos->second;
7383}
7384
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007385serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007386 const RecordData &Record,
7387 unsigned &Idx) {
7388 if (Idx >= Record.size()) {
7389 Error("Corrupted AST file");
7390 return 0;
7391 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007392
Guy Benyei11169dd2012-12-18 14:30:41 +00007393 return getGlobalDeclID(F, Record[Idx++]);
7394}
7395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007396/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007397///
7398/// This operation will read a new statement from the external
7399/// source each time it is called, and is meant to be used via a
7400/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7401Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7402 // Switch case IDs are per Decl.
7403 ClearSwitchCaseIDs();
7404
7405 // Offset here is a global offset across the entire chain.
7406 RecordLocation Loc = getLocalBitOffset(Offset);
7407 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007408 assert(NumCurrentElementsDeserializing == 0 &&
7409 "should not be called while already deserializing");
7410 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 return ReadStmtFromStream(*Loc.F);
7412}
7413
Richard Smith3cb15722015-08-05 22:41:45 +00007414void ASTReader::FindExternalLexicalDecls(
7415 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7416 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007417 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7418
Richard Smith9ccdd932015-08-06 22:14:12 +00007419 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007420 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7421 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7422 auto K = (Decl::Kind)+LexicalDecls[I];
7423 if (!IsKindWeWant(K))
7424 continue;
7425
7426 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7427
7428 // Don't add predefined declarations to the lexical context more
7429 // than once.
7430 if (ID < NUM_PREDEF_DECL_IDS) {
7431 if (PredefsVisited[ID])
7432 continue;
7433
7434 PredefsVisited[ID] = true;
7435 }
7436
7437 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007438 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007439 if (!DC->isDeclInLexicalTraversal(D))
7440 Decls.push_back(D);
7441 }
7442 }
7443 };
7444
7445 if (isa<TranslationUnitDecl>(DC)) {
7446 for (auto Lexical : TULexicalDecls)
7447 Visit(Lexical.first, Lexical.second);
7448 } else {
7449 auto I = LexicalDecls.find(DC);
7450 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007451 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007452 }
7453
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007455}
7456
7457namespace {
7458
7459class DeclIDComp {
7460 ASTReader &Reader;
7461 ModuleFile &Mod;
7462
7463public:
7464 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7465
7466 bool operator()(LocalDeclID L, LocalDeclID R) const {
7467 SourceLocation LHS = getLocation(L);
7468 SourceLocation RHS = getLocation(R);
7469 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7470 }
7471
7472 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7473 SourceLocation RHS = getLocation(R);
7474 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7475 }
7476
7477 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7478 SourceLocation LHS = getLocation(L);
7479 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7480 }
7481
7482 SourceLocation getLocation(LocalDeclID ID) const {
7483 return Reader.getSourceManager().getFileLoc(
7484 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7485 }
7486};
7487
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007488} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007489
7490void ASTReader::FindFileRegionDecls(FileID File,
7491 unsigned Offset, unsigned Length,
7492 SmallVectorImpl<Decl *> &Decls) {
7493 SourceManager &SM = getSourceManager();
7494
7495 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7496 if (I == FileDeclIDs.end())
7497 return;
7498
7499 FileDeclsInfo &DInfo = I->second;
7500 if (DInfo.Decls.empty())
7501 return;
7502
7503 SourceLocation
7504 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7505 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7506
7507 DeclIDComp DIDComp(*this, *DInfo.Mod);
7508 ArrayRef<serialization::LocalDeclID>::iterator
7509 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7510 BeginLoc, DIDComp);
7511 if (BeginIt != DInfo.Decls.begin())
7512 --BeginIt;
7513
7514 // If we are pointing at a top-level decl inside an objc container, we need
7515 // to backtrack until we find it otherwise we will fail to report that the
7516 // region overlaps with an objc container.
7517 while (BeginIt != DInfo.Decls.begin() &&
7518 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7519 ->isTopLevelDeclInObjCContainer())
7520 --BeginIt;
7521
7522 ArrayRef<serialization::LocalDeclID>::iterator
7523 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7524 EndLoc, DIDComp);
7525 if (EndIt != DInfo.Decls.end())
7526 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007527
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 for (ArrayRef<serialization::LocalDeclID>::iterator
7529 DIt = BeginIt; DIt != EndIt; ++DIt)
7530 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7531}
7532
Richard Smith9ce12e32013-02-07 03:30:24 +00007533bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007534ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7535 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007536 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 "DeclContext has no visible decls in storage");
7538 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007539 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007540
Richard Smithd88a7f12015-09-01 20:35:42 +00007541 auto It = Lookups.find(DC);
7542 if (It == Lookups.end())
7543 return false;
7544
Richard Smith8c913ec2014-08-14 02:21:01 +00007545 Deserializing LookupResults(this);
7546
Richard Smithd88a7f12015-09-01 20:35:42 +00007547 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007549 for (DeclID ID : It->second.Table.find(Name)) {
7550 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007551 if (ND->getDeclName() == Name)
7552 Decls.push_back(ND);
7553 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007554
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 ++NumVisibleDeclContextsRead;
7556 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007557 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007558}
7559
Guy Benyei11169dd2012-12-18 14:30:41 +00007560void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7561 if (!DC->hasExternalVisibleStorage())
7562 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007563
7564 auto It = Lookups.find(DC);
7565 assert(It != Lookups.end() &&
7566 "have external visible storage but no lookup tables");
7567
Craig Topper79be4cd2013-07-05 04:33:53 +00007568 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007569
Vedant Kumar48b4f762018-04-14 01:40:48 +00007570 for (DeclID ID : It->second.Table.findAll()) {
7571 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007572 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007573 }
7574
Guy Benyei11169dd2012-12-18 14:30:41 +00007575 ++NumVisibleDeclContextsRead;
7576
Vedant Kumar48b4f762018-04-14 01:40:48 +00007577 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7578 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7579 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7581}
7582
Richard Smithd88a7f12015-09-01 20:35:42 +00007583const serialization::reader::DeclContextLookupTable *
7584ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7585 auto I = Lookups.find(Primary);
7586 return I == Lookups.end() ? nullptr : &I->second;
7587}
7588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007589/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007590/// before receiving the implementation, and codegen depends on this.
7591/// We simulate this by deserializing and passing to consumer the methods of the
7592/// implementation before passing the deserialized implementation decl.
7593static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7594 ASTConsumer *Consumer) {
7595 assert(ImplD && Consumer);
7596
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007597 for (auto *I : ImplD->methods())
7598 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007599
7600 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7601}
7602
Guy Benyei11169dd2012-12-18 14:30:41 +00007603void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007604 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 PassObjCImplDeclToConsumer(ImplD, Consumer);
7606 else
7607 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7608}
7609
7610void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7611 this->Consumer = Consumer;
7612
Richard Smith9e2341d2015-03-23 03:25:59 +00007613 if (Consumer)
7614 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007615
7616 if (DeserializationListener)
7617 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007618}
7619
7620void ASTReader::PrintStats() {
7621 std::fprintf(stderr, "*** AST File Statistics:\n");
7622
7623 unsigned NumTypesLoaded
7624 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7625 QualType());
7626 unsigned NumDeclsLoaded
7627 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007628 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 unsigned NumIdentifiersLoaded
7630 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7631 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007632 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 unsigned NumMacrosLoaded
7634 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7635 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007636 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 unsigned NumSelectorsLoaded
7638 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7639 SelectorsLoaded.end(),
7640 Selector());
7641
7642 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7643 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7644 NumSLocEntriesRead, TotalNumSLocEntries,
7645 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7646 if (!TypesLoaded.empty())
7647 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7648 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7649 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7650 if (!DeclsLoaded.empty())
7651 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7652 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7653 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7654 if (!IdentifiersLoaded.empty())
7655 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7656 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7657 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7658 if (!MacrosLoaded.empty())
7659 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7660 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7661 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7662 if (!SelectorsLoaded.empty())
7663 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7664 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7665 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7666 if (TotalNumStatements)
7667 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7668 NumStatementsRead, TotalNumStatements,
7669 ((float)NumStatementsRead/TotalNumStatements * 100));
7670 if (TotalNumMacros)
7671 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7672 NumMacrosRead, TotalNumMacros,
7673 ((float)NumMacrosRead/TotalNumMacros * 100));
7674 if (TotalLexicalDeclContexts)
7675 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7676 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7677 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7678 * 100));
7679 if (TotalVisibleDeclContexts)
7680 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7681 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7682 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7683 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007684 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7686 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7687 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7688 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007689 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007690 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7691 NumMethodPoolHits, NumMethodPoolLookups,
7692 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007693 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007694 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7695 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7696 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7697 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007698 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007699 std::fprintf(stderr,
7700 " %u / %u identifier table lookups succeeded (%f%%)\n",
7701 NumIdentifierLookupHits, NumIdentifierLookups,
7702 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007703
Douglas Gregore060e572013-01-25 01:03:03 +00007704 if (GlobalIndex) {
7705 std::fprintf(stderr, "\n");
7706 GlobalIndex->printStats();
7707 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007708
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 std::fprintf(stderr, "\n");
7710 dump();
7711 std::fprintf(stderr, "\n");
7712}
7713
7714template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007715LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007716dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007717 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 InitialCapacity> &Map) {
7719 if (Map.begin() == Map.end())
7720 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007721
Vedant Kumar48b4f762018-04-14 01:40:48 +00007722 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7723
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007725 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7726 I != IEnd; ++I) {
7727 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7728 << "\n";
7729 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007730}
7731
Yaron Kerencdae9412016-01-29 19:38:18 +00007732LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7734 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7735 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7736 dumpModuleIDMap("Global type map", GlobalTypeMap);
7737 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7738 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7739 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7740 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7741 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007742 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007744
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007746 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007747 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007748}
7749
7750/// Return the amount of memory used by memory buffers, breaking down
7751/// by heap-backed versus mmap'ed memory.
7752void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007753 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007754 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 size_t bytes = buf->getBufferSize();
7756 switch (buf->getBufferKind()) {
7757 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7758 sizes.malloc_bytes += bytes;
7759 break;
7760 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7761 sizes.mmap_bytes += bytes;
7762 break;
7763 }
7764 }
7765 }
7766}
7767
7768void ASTReader::InitializeSema(Sema &S) {
7769 SemaObj = &S;
7770 S.addExternalSource(this);
7771
7772 // Makes sure any declarations that were deserialized "too early"
7773 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007774 for (uint64_t ID : PreloadedDeclIDs) {
7775 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007776 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007777 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007778 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007779
Richard Smith3d8e97e2013-10-18 06:54:39 +00007780 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007781 if (!FPPragmaOptions.empty()) {
7782 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007783 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 }
7785
Yaxun Liu5b746652016-12-18 05:18:55 +00007786 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7787 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7788 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007789
7790 UpdateSema();
7791}
7792
7793void ASTReader::UpdateSema() {
7794 assert(SemaObj && "no Sema to update");
7795
7796 // Load the offsets of the declarations that Sema references.
7797 // They will be lazily deserialized when needed.
7798 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007799 assert(SemaDeclRefs.size() % 3 == 0);
7800 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007801 if (!SemaObj->StdNamespace)
7802 SemaObj->StdNamespace = SemaDeclRefs[I];
7803 if (!SemaObj->StdBadAlloc)
7804 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007805 if (!SemaObj->StdAlignValT)
7806 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007807 }
7808 SemaDeclRefs.clear();
7809 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007810
Nico Weber779355f2016-03-02 23:22:00 +00007811 // Update the state of pragmas. Use the same API as if we had encountered the
7812 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007813 if(OptimizeOffPragmaLocation.isValid())
7814 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007815 if (PragmaMSStructState != -1)
7816 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007817 if (PointersToMembersPragmaLocation.isValid()) {
7818 SemaObj->ActOnPragmaMSPointersToMembers(
7819 (LangOptions::PragmaMSPointersToMembersKind)
7820 PragmaMSPointersToMembersState,
7821 PointersToMembersPragmaLocation);
7822 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007823 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007824
7825 if (PragmaPackCurrentValue) {
7826 // The bottom of the stack might have a default value. It must be adjusted
7827 // to the current value to ensure that the packing state is preserved after
7828 // popping entries that were included/imported from a PCH/module.
7829 bool DropFirst = false;
7830 if (!PragmaPackStack.empty() &&
7831 PragmaPackStack.front().Location.isInvalid()) {
7832 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7833 "Expected a default alignment value");
7834 SemaObj->PackStack.Stack.emplace_back(
7835 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007836 SemaObj->PackStack.CurrentPragmaLocation,
7837 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007838 DropFirst = true;
7839 }
7840 for (const auto &Entry :
7841 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7842 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007843 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007844 if (PragmaPackCurrentLocation.isInvalid()) {
7845 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7846 "Expected a default alignment value");
7847 // Keep the current values.
7848 } else {
7849 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7850 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7851 }
7852 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007853}
7854
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007855IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 // Note that we are loading an identifier.
7857 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007858
Douglas Gregor7211ac12013-01-25 23:32:03 +00007859 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007860 NumIdentifierLookups,
7861 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007862
7863 // We don't need to do identifier table lookups in C++ modules (we preload
7864 // all interesting declarations, and don't need to use the scope for name
7865 // lookups). Perform the lookup in PCH files, though, since we don't build
7866 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007867 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007868 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007869 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007870 break;
7871 } else {
7872 // If there is a global index, look there first to determine which modules
7873 // provably do not have any results for this identifier.
7874 GlobalModuleIndex::HitSet Hits;
7875 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7876 if (!loadGlobalIndex()) {
7877 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7878 HitsPtr = &Hits;
7879 }
7880 }
7881
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007882 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007883 }
7884
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 IdentifierInfo *II = Visitor.getIdentifierInfo();
7886 markIdentifierUpToDate(II);
7887 return II;
7888}
7889
7890namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007892 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 /// identifiers stored within a set of AST files.
7894 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007895 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007896 const ASTReader &Reader;
7897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007898 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 /// the AST reader.
7900 unsigned Index;
7901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007902 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 /// of the current AST file.
7904 ASTIdentifierLookupTable::key_iterator Current;
7905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007906 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007907 /// the current AST file.
7908 ASTIdentifierLookupTable::key_iterator End;
7909
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007910 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007911 bool SkipModules;
7912
Guy Benyei11169dd2012-12-18 14:30:41 +00007913 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007914 explicit ASTIdentifierIterator(const ASTReader &Reader,
7915 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007916
Craig Topper3e89dfe2014-03-13 02:13:41 +00007917 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007918 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007919
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007920} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007921
Ben Langmuir537c5b52016-05-04 00:53:13 +00007922ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7923 bool SkipModules)
7924 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007925}
7926
7927StringRef ASTIdentifierIterator::Next() {
7928 while (Current == End) {
7929 // If we have exhausted all of our AST files, we're done.
7930 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007931 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007932
7933 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007934 ModuleFile &F = Reader.ModuleMgr[Index];
7935 if (SkipModules && F.isModule())
7936 continue;
7937
Vedant Kumar48b4f762018-04-14 01:40:48 +00007938 ASTIdentifierLookupTable *IdTable =
7939 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 Current = IdTable->key_begin();
7941 End = IdTable->key_end();
7942 }
7943
7944 // We have any identifiers remaining in the current AST file; return
7945 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007946 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007948 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007949}
7950
Ben Langmuir537c5b52016-05-04 00:53:13 +00007951namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007952
Ben Langmuir537c5b52016-05-04 00:53:13 +00007953/// A utility for appending two IdentifierIterators.
7954class ChainedIdentifierIterator : public IdentifierIterator {
7955 std::unique_ptr<IdentifierIterator> Current;
7956 std::unique_ptr<IdentifierIterator> Queued;
7957
7958public:
7959 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7960 std::unique_ptr<IdentifierIterator> Second)
7961 : Current(std::move(First)), Queued(std::move(Second)) {}
7962
7963 StringRef Next() override {
7964 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007965 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007966
7967 StringRef result = Current->Next();
7968 if (!result.empty())
7969 return result;
7970
7971 // Try the queued iterator, which may itself be empty.
7972 Current.reset();
7973 std::swap(Current, Queued);
7974 return Next();
7975 }
7976};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007977
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007978} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007979
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007980IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007981 if (!loadGlobalIndex()) {
7982 std::unique_ptr<IdentifierIterator> ReaderIter(
7983 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7984 std::unique_ptr<IdentifierIterator> ModulesIter(
7985 GlobalIndex->createIdentifierIterator());
7986 return new ChainedIdentifierIterator(std::move(ReaderIter),
7987 std::move(ModulesIter));
7988 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007989
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 return new ASTIdentifierIterator(*this);
7991}
7992
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007993namespace clang {
7994namespace serialization {
7995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 class ReadMethodPoolVisitor {
7997 ASTReader &Reader;
7998 Selector Sel;
7999 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008000 unsigned InstanceBits = 0;
8001 unsigned FactoryBits = 0;
8002 bool InstanceHasMoreThanOneDecl = false;
8003 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008004 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8005 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008006
8007 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008008 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008010 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008011
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008012 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 if (!M.SelectorLookupTable)
8014 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008015
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008017 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008018 return true;
8019
Richard Smithbdf2d932015-07-30 03:37:16 +00008020 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008021 ASTSelectorLookupTable *PoolTable
8022 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008023 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 if (Pos == PoolTable->end())
8025 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008026
Richard Smithbdf2d932015-07-30 03:37:16 +00008027 ++Reader.NumMethodPoolTableHits;
8028 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 // FIXME: Not quite happy with the statistics here. We probably should
8030 // disable this tracking when called via LoadSelector.
8031 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008032 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008034 if (Reader.DeserializationListener)
8035 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008036
Richard Smithbdf2d932015-07-30 03:37:16 +00008037 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8038 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8039 InstanceBits = Data.InstanceBits;
8040 FactoryBits = Data.FactoryBits;
8041 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8042 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 return true;
8044 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008046 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008047 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8048 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 }
8050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008051 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008052 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 return FactoryMethods;
8054 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008055
8056 unsigned getInstanceBits() const { return InstanceBits; }
8057 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008058
Nico Weberff4b35e2014-12-27 22:14:15 +00008059 bool instanceHasMoreThanOneDecl() const {
8060 return InstanceHasMoreThanOneDecl;
8061 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008062
Nico Weberff4b35e2014-12-27 22:14:15 +00008063 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008065
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008066} // namespace serialization
8067} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008069/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008070static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8071 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008072 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8073 S.addMethodToGlobalList(&List, Methods[I]);
8074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008075}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008076
Guy Benyei11169dd2012-12-18 14:30:41 +00008077void ASTReader::ReadMethodPool(Selector Sel) {
8078 // Get the selector generation and update it to the current generation.
8079 unsigned &Generation = SelectorGeneration[Sel];
8080 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008081 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008082 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008083
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008085 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008087 ModuleMgr.visit(Visitor);
8088
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008090 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008092
8093 ++NumMethodPoolHits;
8094
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 if (!getSema())
8096 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008097
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 Sema &S = *getSema();
8099 Sema::GlobalMethodPool::iterator Pos
8100 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008101
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008102 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008103 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008104 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008105 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008106
8107 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8108 // when building a module we keep every method individually and may need to
8109 // update hasMoreThanOneDecl as we add the methods.
8110 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8111 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008112}
8113
Manman Rena0f31a02016-04-29 19:04:05 +00008114void ASTReader::updateOutOfDateSelector(Selector Sel) {
8115 if (SelectorOutOfDate[Sel])
8116 ReadMethodPool(Sel);
8117}
8118
Guy Benyei11169dd2012-12-18 14:30:41 +00008119void ASTReader::ReadKnownNamespaces(
8120 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8121 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008122
Vedant Kumar48b4f762018-04-14 01:40:48 +00008123 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8124 if (NamespaceDecl *Namespace
8125 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008127 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008128}
8129
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008130void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008131 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008132 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008133 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008134 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008135 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008136 Undefined.insert(std::make_pair(D, Loc));
8137 }
8138}
Nick Lewycky8334af82013-01-26 00:35:08 +00008139
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008140void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8141 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8142 Exprs) {
8143 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008144 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008145 uint64_t Count = DelayedDeleteExprs[Idx++];
8146 for (uint64_t C = 0; C < Count; ++C) {
8147 SourceLocation DeleteLoc =
8148 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8149 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8150 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8151 }
8152 }
8153}
8154
Guy Benyei11169dd2012-12-18 14:30:41 +00008155void ASTReader::ReadTentativeDefinitions(
8156 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008157 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8158 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 if (Var)
8160 TentativeDefs.push_back(Var);
8161 }
8162 TentativeDefinitions.clear();
8163}
8164
8165void ASTReader::ReadUnusedFileScopedDecls(
8166 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008167 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8168 DeclaratorDecl *D
8169 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 if (D)
8171 Decls.push_back(D);
8172 }
8173 UnusedFileScopedDecls.clear();
8174}
8175
8176void ASTReader::ReadDelegatingConstructors(
8177 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008178 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8179 CXXConstructorDecl *D
8180 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 if (D)
8182 Decls.push_back(D);
8183 }
8184 DelegatingCtorDecls.clear();
8185}
8186
8187void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008188 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8189 TypedefNameDecl *D
8190 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 if (D)
8192 Decls.push_back(D);
8193 }
8194 ExtVectorDecls.clear();
8195}
8196
Nico Weber72889432014-09-06 01:25:55 +00008197void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8198 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008199 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8200 ++I) {
8201 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8202 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008203 if (D)
8204 Decls.insert(D);
8205 }
8206 UnusedLocalTypedefNameCandidates.clear();
8207}
8208
Guy Benyei11169dd2012-12-18 14:30:41 +00008209void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008210 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 if (ReferencedSelectorsData.empty())
8212 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008213
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 // If there are @selector references added them to its pool. This is for
8215 // implementation of -Wselector.
8216 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8217 unsigned I = 0;
8218 while (I < DataSize) {
8219 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8220 SourceLocation SelLoc
8221 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8222 Sels.push_back(std::make_pair(Sel, SelLoc));
8223 }
8224 ReferencedSelectorsData.clear();
8225}
8226
8227void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008228 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 if (WeakUndeclaredIdentifiers.empty())
8230 return;
8231
8232 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008233 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008235 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8237 SourceLocation Loc
8238 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8239 bool Used = WeakUndeclaredIdentifiers[I++];
8240 WeakInfo WI(AliasId, Loc);
8241 WI.setUsed(Used);
8242 WeakIDs.push_back(std::make_pair(WeakId, WI));
8243 }
8244 WeakUndeclaredIdentifiers.clear();
8245}
8246
8247void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8248 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8249 ExternalVTableUse VT;
8250 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8251 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8252 VT.DefinitionRequired = VTableUses[Idx++];
8253 VTables.push_back(VT);
8254 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008255
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 VTableUses.clear();
8257}
8258
8259void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008260 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008262 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 SourceLocation Loc
8264 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8265
8266 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008267 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 PendingInstantiations.clear();
8269}
8270
Richard Smithe40f2ba2013-08-07 21:41:30 +00008271void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008272 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8273 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008274 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8275 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008276 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008277
Justin Lebar28f09c52016-10-10 16:26:08 +00008278 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008279 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8280
8281 ModuleFile *F = getOwningModuleFile(LT->D);
8282 assert(F && "No module");
8283
8284 unsigned TokN = LateParsedTemplates[Idx++];
8285 LT->Toks.reserve(TokN);
8286 for (unsigned T = 0; T < TokN; ++T)
8287 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8288
Justin Lebar28f09c52016-10-10 16:26:08 +00008289 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008290 }
8291
8292 LateParsedTemplates.clear();
8293}
8294
Guy Benyei11169dd2012-12-18 14:30:41 +00008295void ASTReader::LoadSelector(Selector Sel) {
8296 // It would be complicated to avoid reading the methods anyway. So don't.
8297 ReadMethodPool(Sel);
8298}
8299
8300void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8301 assert(ID && "Non-zero identifier ID required");
8302 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8303 IdentifiersLoaded[ID - 1] = II;
8304 if (DeserializationListener)
8305 DeserializationListener->IdentifierRead(ID, II);
8306}
8307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008308/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008309/// identifier.
8310///
8311/// If the AST reader is currently in a state where the given declaration IDs
8312/// cannot safely be resolved, they are queued until it is safe to resolve
8313/// them.
8314///
8315/// \param II an IdentifierInfo that refers to one or more globally-visible
8316/// declarations.
8317///
8318/// \param DeclIDs the set of declaration IDs with the name @p II that are
8319/// visible at global scope.
8320///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008321/// \param Decls if non-null, this vector will be populated with the set of
8322/// deserialized declarations. These declarations will not be pushed into
8323/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008324void
8325ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8326 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008327 SmallVectorImpl<Decl *> *Decls) {
8328 if (NumCurrentElementsDeserializing && !Decls) {
8329 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 return;
8331 }
8332
Vedant Kumar48b4f762018-04-14 01:40:48 +00008333 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008334 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008335 // Queue this declaration so that it will be added to the
8336 // translation unit scope and identifier's declaration chain
8337 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008338 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008339 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008340 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008341
Vedant Kumar48b4f762018-04-14 01:40:48 +00008342 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008343
8344 // If we're simply supposed to record the declarations, do so now.
8345 if (Decls) {
8346 Decls->push_back(D);
8347 continue;
8348 }
8349
8350 // Introduce this declaration into the translation-unit scope
8351 // and add it to the declaration chain for this identifier, so
8352 // that (unqualified) name lookup will find it.
8353 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
8355}
8356
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008357IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008359 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008360
8361 if (IdentifiersLoaded.empty()) {
8362 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008363 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 }
8365
8366 ID -= 1;
8367 if (!IdentifiersLoaded[ID]) {
8368 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8369 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8370 ModuleFile *M = I->second;
8371 unsigned Index = ID - M->BaseIdentifierID;
8372 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8373
8374 // All of the strings in the AST file are preceded by a 16-bit length.
8375 // Extract that 16-bit length to avoid having to execute strlen().
8376 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8377 // unsigned integers. This is important to avoid integer overflow when
8378 // we cast them to 'unsigned'.
8379 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8380 unsigned StrLen = (((unsigned) StrLenPtr[0])
8381 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008382 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8383 IdentifiersLoaded[ID] = &II;
8384 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008386 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008387 }
8388
8389 return IdentifiersLoaded[ID];
8390}
8391
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008392IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8393 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008394}
8395
8396IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8397 if (LocalID < NUM_PREDEF_IDENT_IDS)
8398 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008399
Richard Smith37a93df2017-02-18 00:32:02 +00008400 if (!M.ModuleOffsetMap.empty())
8401 ReadModuleOffsetMap(M);
8402
Guy Benyei11169dd2012-12-18 14:30:41 +00008403 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8404 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008405 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008406 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 return LocalID + I->second;
8409}
8410
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008411MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008413 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008414
8415 if (MacrosLoaded.empty()) {
8416 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008417 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 }
8419
8420 ID -= NUM_PREDEF_MACRO_IDS;
8421 if (!MacrosLoaded[ID]) {
8422 GlobalMacroMapType::iterator I
8423 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8424 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8425 ModuleFile *M = I->second;
8426 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008427 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008428
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008429 if (DeserializationListener)
8430 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8431 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 }
8433
8434 return MacrosLoaded[ID];
8435}
8436
8437MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8438 if (LocalID < NUM_PREDEF_MACRO_IDS)
8439 return LocalID;
8440
Richard Smith37a93df2017-02-18 00:32:02 +00008441 if (!M.ModuleOffsetMap.empty())
8442 ReadModuleOffsetMap(M);
8443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8445 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8446 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8447
8448 return LocalID + I->second;
8449}
8450
8451serialization::SubmoduleID
8452ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8453 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8454 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008455
Richard Smith37a93df2017-02-18 00:32:02 +00008456 if (!M.ModuleOffsetMap.empty())
8457 ReadModuleOffsetMap(M);
8458
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8460 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008461 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464 return LocalID + I->second;
8465}
8466
8467Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8468 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8469 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008470 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008471 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008472
Guy Benyei11169dd2012-12-18 14:30:41 +00008473 if (GlobalID > SubmodulesLoaded.size()) {
8474 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008475 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008477
Guy Benyei11169dd2012-12-18 14:30:41 +00008478 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8479}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008480
8481Module *ASTReader::getModule(unsigned ID) {
8482 return getSubmodule(ID);
8483}
8484
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008485bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8486 ModuleFile *MF = getOwningModuleFile(D);
8487 return MF && MF->PCHHasObjectFile;
8488}
8489
Richard Smithd88a7f12015-09-01 20:35:42 +00008490ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8491 if (ID & 1) {
8492 // It's a module, look it up by submodule ID.
8493 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8494 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8495 } else {
8496 // It's a prefix (preamble, PCH, ...). Look it up by index.
8497 unsigned IndexFromEnd = ID >> 1;
8498 assert(IndexFromEnd && "got reference to unknown module file");
8499 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8500 }
8501}
8502
8503unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8504 if (!F)
8505 return 1;
8506
8507 // For a file representing a module, use the submodule ID of the top-level
8508 // module as the file ID. For any other kind of file, the number of such
8509 // files loaded beforehand will be the same on reload.
8510 // FIXME: Is this true even if we have an explicit module file and a PCH?
8511 if (F->isModule())
8512 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8513
8514 auto PCHModules = getModuleManager().pch_modules();
8515 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8516 assert(I != PCHModules.end() && "emitting reference to unknown file");
8517 return (I - PCHModules.end()) << 1;
8518}
8519
Adrian Prantl15bcf702015-06-30 17:39:43 +00008520llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8521ASTReader::getSourceDescriptor(unsigned ID) {
8522 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008523 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008524
8525 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008526 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008527 const auto &PCHChain = ModuleMgr.pch_modules();
8528 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008529 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008530 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008531 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8532 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8533 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008534 }
8535 return None;
8536}
8537
David Blaikie1ac9c982017-04-11 21:13:37 +00008538ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008539 auto I = DefinitionSource.find(FD);
8540 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008541 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008542 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008543}
8544
Guy Benyei11169dd2012-12-18 14:30:41 +00008545Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8546 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8547}
8548
8549Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8550 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008551 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008552
8553 if (ID > SelectorsLoaded.size()) {
8554 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008555 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008556 }
8557
Craig Toppera13603a2014-05-22 05:54:18 +00008558 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008559 // Load this selector from the selector table.
8560 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8561 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8562 ModuleFile &M = *I->second;
8563 ASTSelectorLookupTrait Trait(*this, M);
8564 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8565 SelectorsLoaded[ID - 1] =
8566 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8567 if (DeserializationListener)
8568 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8569 }
8570
8571 return SelectorsLoaded[ID - 1];
8572}
8573
8574Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8575 return DecodeSelector(ID);
8576}
8577
8578uint32_t ASTReader::GetNumExternalSelectors() {
8579 // ID 0 (the null selector) is considered an external selector.
8580 return getTotalNumSelectors() + 1;
8581}
8582
8583serialization::SelectorID
8584ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8585 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8586 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008587
Richard Smith37a93df2017-02-18 00:32:02 +00008588 if (!M.ModuleOffsetMap.empty())
8589 ReadModuleOffsetMap(M);
8590
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8592 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008593 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008594 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596 return LocalID + I->second;
8597}
8598
8599DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008600ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008601 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008602 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008603 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008604 switch (Kind) {
8605 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008606 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008607
8608 case DeclarationName::ObjCZeroArgSelector:
8609 case DeclarationName::ObjCOneArgSelector:
8610 case DeclarationName::ObjCMultiArgSelector:
8611 return DeclarationName(ReadSelector(F, Record, Idx));
8612
8613 case DeclarationName::CXXConstructorName:
8614 return Context.DeclarationNames.getCXXConstructorName(
8615 Context.getCanonicalType(readType(F, Record, Idx)));
8616
8617 case DeclarationName::CXXDestructorName:
8618 return Context.DeclarationNames.getCXXDestructorName(
8619 Context.getCanonicalType(readType(F, Record, Idx)));
8620
Richard Smith35845152017-02-07 01:37:30 +00008621 case DeclarationName::CXXDeductionGuideName:
8622 return Context.DeclarationNames.getCXXDeductionGuideName(
8623 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8624
Guy Benyei11169dd2012-12-18 14:30:41 +00008625 case DeclarationName::CXXConversionFunctionName:
8626 return Context.DeclarationNames.getCXXConversionFunctionName(
8627 Context.getCanonicalType(readType(F, Record, Idx)));
8628
8629 case DeclarationName::CXXOperatorName:
8630 return Context.DeclarationNames.getCXXOperatorName(
8631 (OverloadedOperatorKind)Record[Idx++]);
8632
8633 case DeclarationName::CXXLiteralOperatorName:
8634 return Context.DeclarationNames.getCXXLiteralOperatorName(
8635 GetIdentifierInfo(F, Record, Idx));
8636
8637 case DeclarationName::CXXUsingDirective:
8638 return DeclarationName::getUsingDirectiveName();
8639 }
8640
8641 llvm_unreachable("Invalid NameKind!");
8642}
8643
8644void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8645 DeclarationNameLoc &DNLoc,
8646 DeclarationName Name,
8647 const RecordData &Record, unsigned &Idx) {
8648 switch (Name.getNameKind()) {
8649 case DeclarationName::CXXConstructorName:
8650 case DeclarationName::CXXDestructorName:
8651 case DeclarationName::CXXConversionFunctionName:
8652 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8653 break;
8654
8655 case DeclarationName::CXXOperatorName:
8656 DNLoc.CXXOperatorName.BeginOpNameLoc
8657 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8658 DNLoc.CXXOperatorName.EndOpNameLoc
8659 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8660 break;
8661
8662 case DeclarationName::CXXLiteralOperatorName:
8663 DNLoc.CXXLiteralOperatorName.OpNameLoc
8664 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8665 break;
8666
8667 case DeclarationName::Identifier:
8668 case DeclarationName::ObjCZeroArgSelector:
8669 case DeclarationName::ObjCOneArgSelector:
8670 case DeclarationName::ObjCMultiArgSelector:
8671 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008672 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008673 break;
8674 }
8675}
8676
8677void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8678 DeclarationNameInfo &NameInfo,
8679 const RecordData &Record, unsigned &Idx) {
8680 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8681 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8682 DeclarationNameLoc DNLoc;
8683 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8684 NameInfo.setInfo(DNLoc);
8685}
8686
8687void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8688 const RecordData &Record, unsigned &Idx) {
8689 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8690 unsigned NumTPLists = Record[Idx++];
8691 Info.NumTemplParamLists = NumTPLists;
8692 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008693 Info.TemplParamLists =
8694 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008695 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8697 }
8698}
8699
8700TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008701ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008702 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008703 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008704 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008705 switch (Kind) {
8706 case TemplateName::Template:
8707 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8708
8709 case TemplateName::OverloadedTemplate: {
8710 unsigned size = Record[Idx++];
8711 UnresolvedSet<8> Decls;
8712 while (size--)
8713 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8714
8715 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8716 }
8717
8718 case TemplateName::QualifiedTemplate: {
8719 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8720 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008721 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008722 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8723 }
8724
8725 case TemplateName::DependentTemplate: {
8726 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8727 if (Record[Idx++]) // isIdentifier
8728 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008729 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 Idx));
8731 return Context.getDependentTemplateName(NNS,
8732 (OverloadedOperatorKind)Record[Idx++]);
8733 }
8734
8735 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008736 TemplateTemplateParmDecl *param
8737 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8738 if (!param) return TemplateName();
8739 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8740 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008741 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008742
Guy Benyei11169dd2012-12-18 14:30:41 +00008743 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008744 TemplateTemplateParmDecl *Param
8745 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008746 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008747 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008748
Guy Benyei11169dd2012-12-18 14:30:41 +00008749 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8750 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008751 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008752
Guy Benyei11169dd2012-12-18 14:30:41 +00008753 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8754 }
8755 }
8756
8757 llvm_unreachable("Unhandled template name kind!");
8758}
8759
Richard Smith2bb3c342015-08-09 01:05:31 +00008760TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8761 const RecordData &Record,
8762 unsigned &Idx,
8763 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008764 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008765 if (Canonicalize) {
8766 // The caller wants a canonical template argument. Sometimes the AST only
8767 // wants template arguments in canonical form (particularly as the template
8768 // argument lists of template specializations) so ensure we preserve that
8769 // canonical form across serialization.
8770 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8771 return Context.getCanonicalTemplateArgument(Arg);
8772 }
8773
Vedant Kumar48b4f762018-04-14 01:40:48 +00008774 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008775 switch (Kind) {
8776 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008777 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008778 case TemplateArgument::Type:
8779 return TemplateArgument(readType(F, Record, Idx));
8780 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008781 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008782 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 }
8784 case TemplateArgument::NullPtr:
8785 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8786 case TemplateArgument::Integral: {
8787 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8788 QualType T = readType(F, Record, Idx);
8789 return TemplateArgument(Context, Value, T);
8790 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008791 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008792 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8793 case TemplateArgument::TemplateExpansion: {
8794 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008795 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008796 if (unsigned NumExpansions = Record[Idx++])
8797 NumTemplateExpansions = NumExpansions - 1;
8798 return TemplateArgument(Name, NumTemplateExpansions);
8799 }
8800 case TemplateArgument::Expression:
8801 return TemplateArgument(ReadExpr(F));
8802 case TemplateArgument::Pack: {
8803 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008804 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008805 for (unsigned I = 0; I != NumArgs; ++I)
8806 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008807 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008808 }
8809 }
8810
8811 llvm_unreachable("Unhandled template argument kind!");
8812}
8813
8814TemplateParameterList *
8815ASTReader::ReadTemplateParameterList(ModuleFile &F,
8816 const RecordData &Record, unsigned &Idx) {
8817 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8818 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8819 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8820
8821 unsigned NumParams = Record[Idx++];
8822 SmallVector<NamedDecl *, 16> Params;
8823 Params.reserve(NumParams);
8824 while (NumParams--)
8825 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8826
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008827 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008828 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8829 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008830 return TemplateParams;
8831}
8832
8833void
8834ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008835ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008836 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008837 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008838 unsigned NumTemplateArgs = Record[Idx++];
8839 TemplArgs.reserve(NumTemplateArgs);
8840 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008841 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008842}
8843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008844/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008845void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008846 const RecordData &Record, unsigned &Idx) {
8847 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008848 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008850 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008851 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008852 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008853 }
8854}
8855
8856CXXBaseSpecifier
8857ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8858 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008859 bool isVirtual = static_cast<bool>(Record[Idx++]);
8860 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8861 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8862 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008863 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8864 SourceRange Range = ReadSourceRange(F, Record, Idx);
8865 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008866 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008867 EllipsisLoc);
8868 Result.setInheritConstructors(inheritConstructors);
8869 return Result;
8870}
8871
Richard Smithc2bb8182015-03-24 06:36:48 +00008872CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008873ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8874 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008875 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008876 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008877 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008878 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008879 for (unsigned i = 0; i != NumInitializers; ++i) {
8880 TypeSourceInfo *TInfo = nullptr;
8881 bool IsBaseVirtual = false;
8882 FieldDecl *Member = nullptr;
8883 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008884
Vedant Kumar48b4f762018-04-14 01:40:48 +00008885 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008886 switch (Type) {
8887 case CTOR_INITIALIZER_BASE:
8888 TInfo = GetTypeSourceInfo(F, Record, Idx);
8889 IsBaseVirtual = Record[Idx++];
8890 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008891
Richard Smithc2bb8182015-03-24 06:36:48 +00008892 case CTOR_INITIALIZER_DELEGATING:
8893 TInfo = GetTypeSourceInfo(F, Record, Idx);
8894 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008895
Richard Smithc2bb8182015-03-24 06:36:48 +00008896 case CTOR_INITIALIZER_MEMBER:
8897 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8898 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008899
Richard Smithc2bb8182015-03-24 06:36:48 +00008900 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8901 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8902 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008904
8905 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8906 Expr *Init = ReadExpr(F);
8907 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8908 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008909
8910 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008911 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008912 BOMInit = new (Context)
8913 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8914 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008915 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008916 BOMInit = new (Context)
8917 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008918 else if (Member)
8919 BOMInit = new (Context)
8920 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8921 Init, RParenLoc);
8922 else
8923 BOMInit = new (Context)
8924 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8925 LParenLoc, Init, RParenLoc);
8926
Richard Smith418ed822016-12-14 19:45:03 +00008927 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008928 unsigned SourceOrder = Record[Idx++];
8929 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008930 }
8931
Richard Smithc2bb8182015-03-24 06:36:48 +00008932 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008933 }
8934
Richard Smithc2bb8182015-03-24 06:36:48 +00008935 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008936}
8937
8938NestedNameSpecifier *
8939ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8940 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008941 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008942 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008943 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008944 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008945 NestedNameSpecifier::SpecifierKind Kind
8946 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008947 switch (Kind) {
8948 case NestedNameSpecifier::Identifier: {
8949 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8950 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8951 break;
8952 }
8953
8954 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008955 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008956 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8957 break;
8958 }
8959
8960 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008961 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008962 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8963 break;
8964 }
8965
8966 case NestedNameSpecifier::TypeSpec:
8967 case NestedNameSpecifier::TypeSpecWithTemplate: {
8968 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8969 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008970 return nullptr;
8971
Guy Benyei11169dd2012-12-18 14:30:41 +00008972 bool Template = Record[Idx++];
8973 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8974 break;
8975 }
8976
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008977 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008978 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8979 // No associated value, and there can't be a prefix.
8980 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008981
8982 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008983 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008984 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8985 break;
8986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008987 }
8988 Prev = NNS;
8989 }
8990 return NNS;
8991}
8992
8993NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008994ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008995 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008996 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008997 unsigned N = Record[Idx++];
8998 NestedNameSpecifierLocBuilder Builder;
8999 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009000 NestedNameSpecifier::SpecifierKind Kind
9001 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009002 switch (Kind) {
9003 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009004 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009005 SourceRange Range = ReadSourceRange(F, Record, Idx);
9006 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9007 break;
9008 }
9009
9010 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009011 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009012 SourceRange Range = ReadSourceRange(F, Record, Idx);
9013 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9014 break;
9015 }
9016
9017 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009018 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009019 SourceRange Range = ReadSourceRange(F, Record, Idx);
9020 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9021 break;
9022 }
9023
9024 case NestedNameSpecifier::TypeSpec:
9025 case NestedNameSpecifier::TypeSpecWithTemplate: {
9026 bool Template = Record[Idx++];
9027 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9028 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009029 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009030 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9031
9032 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009033 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009034 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9035 T->getTypeLoc(), ColonColonLoc);
9036 break;
9037 }
9038
9039 case NestedNameSpecifier::Global: {
9040 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9041 Builder.MakeGlobal(Context, ColonColonLoc);
9042 break;
9043 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009044
9045 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009046 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009047 SourceRange Range = ReadSourceRange(F, Record, Idx);
9048 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9049 break;
9050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009051 }
9052 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009053
Guy Benyei11169dd2012-12-18 14:30:41 +00009054 return Builder.getWithLocInContext(Context);
9055}
9056
9057SourceRange
9058ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9059 unsigned &Idx) {
9060 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9061 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9062 return SourceRange(beg, end);
9063}
9064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009065/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009066llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9067 unsigned BitWidth = Record[Idx++];
9068 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9069 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9070 Idx += NumWords;
9071 return Result;
9072}
9073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009074/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009075llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9076 bool isUnsigned = Record[Idx++];
9077 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9078}
9079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009080/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009081llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9082 const llvm::fltSemantics &Sem,
9083 unsigned &Idx) {
9084 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009085}
9086
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009087// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009088std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9089 unsigned Len = Record[Idx++];
9090 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9091 Idx += Len;
9092 return Result;
9093}
9094
Richard Smith7ed1bc92014-12-05 22:42:13 +00009095std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9096 unsigned &Idx) {
9097 std::string Filename = ReadString(Record, Idx);
9098 ResolveImportedPath(F, Filename);
9099 return Filename;
9100}
9101
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009102VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009103 unsigned &Idx) {
9104 unsigned Major = Record[Idx++];
9105 unsigned Minor = Record[Idx++];
9106 unsigned Subminor = Record[Idx++];
9107 if (Minor == 0)
9108 return VersionTuple(Major);
9109 if (Subminor == 0)
9110 return VersionTuple(Major, Minor - 1);
9111 return VersionTuple(Major, Minor - 1, Subminor - 1);
9112}
9113
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009114CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009115 const RecordData &Record,
9116 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009117 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009118 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009119}
9120
Richard Smith37a93df2017-02-18 00:32:02 +00009121DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009122 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009123}
9124
Richard Smith37a93df2017-02-18 00:32:02 +00009125DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009126 return Diags.Report(Loc, DiagID);
9127}
9128
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009129/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009130/// preprocessor.
9131IdentifierTable &ASTReader::getIdentifierTable() {
9132 return PP.getIdentifierTable();
9133}
9134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009135/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009136/// statement.
9137void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009138 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009139 "Already have a SwitchCase with this ID");
9140 (*CurrSwitchCaseStmts)[ID] = SC;
9141}
9142
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009143/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009144SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009145 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009146 return (*CurrSwitchCaseStmts)[ID];
9147}
9148
9149void ASTReader::ClearSwitchCaseIDs() {
9150 CurrSwitchCaseStmts->clear();
9151}
9152
9153void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009154 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009155 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009156 for (SmallVectorImpl<std::pair<BitstreamCursor,
9157 serialization::ModuleFile *>>::iterator
9158 I = CommentsCursors.begin(),
9159 E = CommentsCursors.end();
9160 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009161 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009162 BitstreamCursor &Cursor = I->first;
9163 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009164 SavedStreamPosition SavedPosition(Cursor);
9165
9166 RecordData Record;
9167 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009168 llvm::BitstreamEntry Entry =
9169 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009170
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009171 switch (Entry.Kind) {
9172 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9173 case llvm::BitstreamEntry::Error:
9174 Error("malformed block record in AST file");
9175 return;
9176 case llvm::BitstreamEntry::EndBlock:
9177 goto NextCursor;
9178 case llvm::BitstreamEntry::Record:
9179 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009180 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009181 }
9182
9183 // Read a record.
9184 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009185 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009186 case COMMENTS_RAW_COMMENT: {
9187 unsigned Idx = 0;
9188 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009189 RawComment::CommentKind Kind =
9190 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009191 bool IsTrailingComment = Record[Idx++];
9192 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009193 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009194 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009195 break;
9196 }
9197 }
9198 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009199 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009200 // De-serialized SourceLocations get negative FileIDs for other modules,
9201 // potentially invalidating the original order. Sort it again.
Fangrui Song55fab262018-09-26 22:16:28 +00009202 llvm::sort(Comments, BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009203 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009205}
9206
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009207void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9208 bool IncludeSystem, bool Complain,
9209 llvm::function_ref<void(const serialization::InputFile &IF,
9210 bool isSystem)> Visitor) {
9211 unsigned NumUserInputs = MF.NumUserInputFiles;
9212 unsigned NumInputs = MF.InputFilesLoaded.size();
9213 assert(NumUserInputs <= NumInputs);
9214 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9215 for (unsigned I = 0; I < N; ++I) {
9216 bool IsSystem = I >= NumUserInputs;
9217 InputFile IF = getInputFile(MF, I+1, Complain);
9218 Visitor(IF, IsSystem);
9219 }
9220}
9221
Richard Smithf3f84612017-06-29 02:19:42 +00009222void ASTReader::visitTopLevelModuleMaps(
9223 serialization::ModuleFile &MF,
9224 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9225 unsigned NumInputs = MF.InputFilesLoaded.size();
9226 for (unsigned I = 0; I < NumInputs; ++I) {
9227 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9228 if (IFI.TopLevelModuleMap)
9229 // FIXME: This unnecessarily re-reads the InputFileInfo.
9230 if (auto *FE = getInputFile(MF, I + 1).getFile())
9231 Visitor(FE);
9232 }
9233}
9234
Richard Smithcd45dbc2014-04-19 03:48:30 +00009235std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9236 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009237 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009238 return M->getFullModuleName();
9239
9240 // Otherwise, use the name of the top-level module the decl is within.
9241 if (ModuleFile *M = getOwningModuleFile(D))
9242 return M->ModuleName;
9243
9244 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009245 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009246}
9247
Guy Benyei11169dd2012-12-18 14:30:41 +00009248void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009249 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009250 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009251 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009252 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009253 // If any identifiers with corresponding top-level declarations have
9254 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009255 using TopLevelDeclsMap =
9256 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009257 TopLevelDeclsMap TopLevelDecls;
9258
Guy Benyei11169dd2012-12-18 14:30:41 +00009259 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009260 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009261 SmallVector<uint32_t, 4> DeclIDs =
9262 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009263 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009264
9265 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009266 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009267
Richard Smitha62d1982018-08-03 01:00:01 +00009268 // Load each function type that we deferred loading because it was a
9269 // deduced type that might refer to a local type declared within itself.
9270 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9271 auto *FD = PendingFunctionTypes[I].first;
9272 FD->setType(GetType(PendingFunctionTypes[I].second));
9273
9274 // If we gave a function a deduced return type, remember that we need to
9275 // propagate that along the redeclaration chain.
9276 auto *DT = FD->getReturnType()->getContainedDeducedType();
9277 if (DT && DT->isDeduced())
9278 PendingDeducedTypeUpdates.insert(
9279 {FD->getCanonicalDecl(), FD->getReturnType()});
9280 }
9281 PendingFunctionTypes.clear();
9282
Richard Smith851072e2014-05-19 20:59:20 +00009283 // For each decl chain that we wanted to complete while deserializing, mark
9284 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009285 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9286 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9287 }
Richard Smith851072e2014-05-19 20:59:20 +00009288 PendingIncompleteDeclChains.clear();
9289
Guy Benyei11169dd2012-12-18 14:30:41 +00009290 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009291 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009292 loadPendingDeclChain(PendingDeclChains[I].first,
9293 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009294 PendingDeclChains.clear();
9295
Douglas Gregor6168bd22013-02-18 15:53:43 +00009296 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009297 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9298 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9299 IdentifierInfo *II = TLD->first;
9300 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9301 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009302 }
9303 }
9304
Guy Benyei11169dd2012-12-18 14:30:41 +00009305 // Load any pending macro definitions.
9306 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009307 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9308 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9309 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9310 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009311 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009312 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009313 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009314 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009315 resolvePendingMacro(II, Info);
9316 }
9317 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009318 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009319 ++IDIdx) {
9320 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009321 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009322 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009323 }
9324 }
9325 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009326
9327 // Wire up the DeclContexts for Decls that we delayed setting until
9328 // recursive loading is completed.
9329 while (!PendingDeclContextInfos.empty()) {
9330 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9331 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009332 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9333 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009334 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9335 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009336
Richard Smithd1c46742014-04-30 02:24:17 +00009337 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009338 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009339 auto Update = PendingUpdateRecords.pop_back_val();
9340 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009341 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009342 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009343 }
Richard Smith8a639892015-01-24 01:07:20 +00009344
9345 // At this point, all update records for loaded decls are in place, so any
9346 // fake class definitions should have become real.
9347 assert(PendingFakeDefinitionData.empty() &&
9348 "faked up a class definition but never saw the real one");
9349
Guy Benyei11169dd2012-12-18 14:30:41 +00009350 // If we deserialized any C++ or Objective-C class definitions, any
9351 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009352 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009353 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009354 for (Decl *D : PendingDefinitions) {
9355 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9356 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009357 // Make sure that the TagType points at the definition.
9358 const_cast<TagType*>(TagT)->decl = TD;
9359 }
Richard Smith8ce51082015-03-11 01:44:51 +00009360
Vedant Kumar48b4f762018-04-14 01:40:48 +00009361 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009362 for (auto *R = getMostRecentExistingDecl(RD); R;
9363 R = R->getPreviousDecl()) {
9364 assert((R == D) ==
9365 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009366 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009367 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009369 }
9370
9371 continue;
9372 }
Richard Smith8ce51082015-03-11 01:44:51 +00009373
Vedant Kumar48b4f762018-04-14 01:40:48 +00009374 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009375 // Make sure that the ObjCInterfaceType points at the definition.
9376 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9377 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009378
9379 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9380 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9381
Guy Benyei11169dd2012-12-18 14:30:41 +00009382 continue;
9383 }
Richard Smith8ce51082015-03-11 01:44:51 +00009384
Vedant Kumar48b4f762018-04-14 01:40:48 +00009385 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009386 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9387 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9388
Guy Benyei11169dd2012-12-18 14:30:41 +00009389 continue;
9390 }
Richard Smith8ce51082015-03-11 01:44:51 +00009391
Vedant Kumar48b4f762018-04-14 01:40:48 +00009392 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009393 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9394 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009395 }
9396 PendingDefinitions.clear();
9397
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009398 // Load the bodies of any functions or methods we've encountered. We do
9399 // this now (delayed) so that we can be sure that the declaration chains
9400 // have been fully wired up (hasBody relies on this).
9401 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009402 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9403 PBEnd = PendingBodies.end();
9404 PB != PBEnd; ++PB) {
9405 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009406 // For a function defined inline within a class template, force the
9407 // canonical definition to be the one inside the canonical definition of
9408 // the template. This ensures that we instantiate from a correct view
9409 // of the template.
9410 //
9411 // Sadly we can't do this more generally: we can't be sure that all
9412 // copies of an arbitrary class definition will have the same members
9413 // defined (eg, some member functions may not be instantiated, and some
9414 // special members may or may not have been implicitly defined).
9415 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9416 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9417 continue;
9418
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009419 // FIXME: Check for =delete/=default?
9420 // FIXME: Complain about ODR violations here?
9421 const FunctionDecl *Defn = nullptr;
9422 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009423 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009424 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009425 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009426 mergeDefinitionVisibility(NonConstDefn, FD);
9427
9428 if (!FD->isLateTemplateParsed() &&
9429 !NonConstDefn->isLateTemplateParsed() &&
9430 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009431 if (!isa<CXXMethodDecl>(FD)) {
9432 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9433 } else if (FD->getLexicalParent()->isFileContext() &&
9434 NonConstDefn->getLexicalParent()->isFileContext()) {
9435 // Only diagnose out-of-line method definitions. If they are
9436 // in class definitions, then an error will be generated when
9437 // processing the class bodies.
9438 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9439 }
Richard Trieue6caa262017-12-23 00:41:01 +00009440 }
9441 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009442 continue;
9443 }
9444
Vedant Kumar48b4f762018-04-14 01:40:48 +00009445 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009446 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009447 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009448 }
9449 PendingBodies.clear();
9450
Richard Smith42413142015-05-15 20:05:43 +00009451 // Do some cleanup.
9452 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9453 getContext().deduplicateMergedDefinitonsFor(ND);
9454 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009455}
9456
9457void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009458 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009459 PendingFunctionOdrMergeFailures.empty() &&
9460 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009461 return;
9462
Richard Smitha0ce9c42014-07-29 23:23:27 +00009463 // Trigger the import of the full definition of each class that had any
9464 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009465 // These updates may in turn find and diagnose some ODR failures, so take
9466 // ownership of the set first.
9467 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9468 PendingOdrMergeFailures.clear();
9469 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009470 Merge.first->buildLookup();
9471 Merge.first->decls_begin();
9472 Merge.first->bases_begin();
9473 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009474 for (auto &RecordPair : Merge.second) {
9475 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009476 RD->decls_begin();
9477 RD->bases_begin();
9478 RD->vbases_begin();
9479 }
9480 }
9481
Richard Trieue6caa262017-12-23 00:41:01 +00009482 // Trigger the import of functions.
9483 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9484 PendingFunctionOdrMergeFailures.clear();
9485 for (auto &Merge : FunctionOdrMergeFailures) {
9486 Merge.first->buildLookup();
9487 Merge.first->decls_begin();
9488 Merge.first->getBody();
9489 for (auto &FD : Merge.second) {
9490 FD->buildLookup();
9491 FD->decls_begin();
9492 FD->getBody();
9493 }
9494 }
9495
Richard Trieuab4d7302018-07-25 22:52:05 +00009496 // Trigger the import of enums.
9497 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9498 PendingEnumOdrMergeFailures.clear();
9499 for (auto &Merge : EnumOdrMergeFailures) {
9500 Merge.first->decls_begin();
9501 for (auto &Enum : Merge.second) {
9502 Enum->decls_begin();
9503 }
9504 }
9505
Richard Smitha0ce9c42014-07-29 23:23:27 +00009506 // For each declaration from a merged context, check that the canonical
9507 // definition of that context also contains a declaration of the same
9508 // entity.
9509 //
9510 // Caution: this loop does things that might invalidate iterators into
9511 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9512 while (!PendingOdrMergeChecks.empty()) {
9513 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9514
9515 // FIXME: Skip over implicit declarations for now. This matters for things
9516 // like implicitly-declared special member functions. This isn't entirely
9517 // correct; we can end up with multiple unmerged declarations of the same
9518 // implicit entity.
9519 if (D->isImplicit())
9520 continue;
9521
9522 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009523
9524 bool Found = false;
9525 const Decl *DCanon = D->getCanonicalDecl();
9526
Richard Smith01bdb7a2014-08-28 05:44:07 +00009527 for (auto RI : D->redecls()) {
9528 if (RI->getLexicalDeclContext() == CanonDef) {
9529 Found = true;
9530 break;
9531 }
9532 }
9533 if (Found)
9534 continue;
9535
Richard Smith0f4e2c42015-08-06 04:23:48 +00009536 // Quick check failed, time to do the slow thing. Note, we can't just
9537 // look up the name of D in CanonDef here, because the member that is
9538 // in CanonDef might not be found by name lookup (it might have been
9539 // replaced by a more recent declaration in the lookup table), and we
9540 // can't necessarily find it in the redeclaration chain because it might
9541 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009542 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009543 for (auto *CanonMember : CanonDef->decls()) {
9544 if (CanonMember->getCanonicalDecl() == DCanon) {
9545 // This can happen if the declaration is merely mergeable and not
9546 // actually redeclarable (we looked for redeclarations earlier).
9547 //
9548 // FIXME: We should be able to detect this more efficiently, without
9549 // pulling in all of the members of CanonDef.
9550 Found = true;
9551 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009552 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009553 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9554 if (ND->getDeclName() == D->getDeclName())
9555 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009556 }
9557
9558 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009559 // The AST doesn't like TagDecls becoming invalid after they've been
9560 // completed. We only really need to mark FieldDecls as invalid here.
9561 if (!isa<TagDecl>(D))
9562 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009563
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009564 // Ensure we don't accidentally recursively enter deserialization while
9565 // we're producing our diagnostic.
9566 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009567
9568 std::string CanonDefModule =
9569 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9570 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9571 << D << getOwningModuleNameForDiagnostic(D)
9572 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9573
9574 if (Candidates.empty())
9575 Diag(cast<Decl>(CanonDef)->getLocation(),
9576 diag::note_module_odr_violation_no_possible_decls) << D;
9577 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009578 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9579 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009580 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009581 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009582 }
9583
9584 DiagnosedOdrMergeFailures.insert(CanonDef);
9585 }
9586 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009587
Richard Trieuab4d7302018-07-25 22:52:05 +00009588 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9589 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009590 return;
9591
9592 // Ensure we don't accidentally recursively enter deserialization while
9593 // we're producing our diagnostics.
9594 Deserializing RecursionGuard(this);
9595
Richard Trieue6caa262017-12-23 00:41:01 +00009596 // Common code for hashing helpers.
9597 ODRHash Hash;
9598 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9599 Hash.clear();
9600 Hash.AddQualType(Ty);
9601 return Hash.CalculateHash();
9602 };
9603
9604 auto ComputeODRHash = [&Hash](const Stmt *S) {
9605 assert(S);
9606 Hash.clear();
9607 Hash.AddStmt(S);
9608 return Hash.CalculateHash();
9609 };
9610
9611 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9612 assert(D);
9613 Hash.clear();
9614 Hash.AddSubDecl(D);
9615 return Hash.CalculateHash();
9616 };
9617
Richard Trieu7282d322018-04-25 00:31:15 +00009618 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9619 Hash.clear();
9620 Hash.AddTemplateArgument(TA);
9621 return Hash.CalculateHash();
9622 };
9623
Richard Trieu9359e8f2018-05-30 01:12:26 +00009624 auto ComputeTemplateParameterListODRHash =
9625 [&Hash](const TemplateParameterList *TPL) {
9626 assert(TPL);
9627 Hash.clear();
9628 Hash.AddTemplateParameterList(TPL);
9629 return Hash.CalculateHash();
9630 };
9631
Richard Smithcd45dbc2014-04-19 03:48:30 +00009632 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009633 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009634 // If we've already pointed out a specific problem with this class, don't
9635 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009636 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009637 continue;
9638
9639 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009640 CXXRecordDecl *FirstRecord = Merge.first;
9641 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009642 for (auto &RecordPair : Merge.second) {
9643 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009644 // Multiple different declarations got merged together; tell the user
9645 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009646 if (FirstRecord == SecondRecord)
9647 continue;
9648
9649 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009650
9651 auto *FirstDD = FirstRecord->DefinitionData;
9652 auto *SecondDD = RecordPair.second;
9653
9654 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9655
9656 // Diagnostics from DefinitionData are emitted here.
9657 if (FirstDD != SecondDD) {
9658 enum ODRDefinitionDataDifference {
9659 NumBases,
9660 NumVBases,
9661 BaseType,
9662 BaseVirtual,
9663 BaseAccess,
9664 };
9665 auto ODRDiagError = [FirstRecord, &FirstModule,
9666 this](SourceLocation Loc, SourceRange Range,
9667 ODRDefinitionDataDifference DiffType) {
9668 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9669 << FirstRecord << FirstModule.empty() << FirstModule << Range
9670 << DiffType;
9671 };
9672 auto ODRDiagNote = [&SecondModule,
9673 this](SourceLocation Loc, SourceRange Range,
9674 ODRDefinitionDataDifference DiffType) {
9675 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9676 << SecondModule << Range << DiffType;
9677 };
9678
Richard Trieue13eabe2017-09-30 02:19:17 +00009679 unsigned FirstNumBases = FirstDD->NumBases;
9680 unsigned FirstNumVBases = FirstDD->NumVBases;
9681 unsigned SecondNumBases = SecondDD->NumBases;
9682 unsigned SecondNumVBases = SecondDD->NumVBases;
9683
9684 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9685 unsigned NumBases = DD->NumBases;
9686 if (NumBases == 0) return SourceRange();
9687 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009688 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009689 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009690 };
9691
9692 if (FirstNumBases != SecondNumBases) {
9693 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9694 NumBases)
9695 << FirstNumBases;
9696 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9697 NumBases)
9698 << SecondNumBases;
9699 Diagnosed = true;
9700 break;
9701 }
9702
9703 if (FirstNumVBases != SecondNumVBases) {
9704 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9705 NumVBases)
9706 << FirstNumVBases;
9707 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9708 NumVBases)
9709 << SecondNumVBases;
9710 Diagnosed = true;
9711 break;
9712 }
9713
9714 auto FirstBases = FirstDD->bases();
9715 auto SecondBases = SecondDD->bases();
9716 unsigned i = 0;
9717 for (i = 0; i < FirstNumBases; ++i) {
9718 auto FirstBase = FirstBases[i];
9719 auto SecondBase = SecondBases[i];
9720 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9721 ComputeQualTypeODRHash(SecondBase.getType())) {
9722 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9723 BaseType)
9724 << (i + 1) << FirstBase.getType();
9725 ODRDiagNote(SecondRecord->getLocation(),
9726 SecondBase.getSourceRange(), BaseType)
9727 << (i + 1) << SecondBase.getType();
9728 break;
9729 }
9730
9731 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9732 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9733 BaseVirtual)
9734 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9735 ODRDiagNote(SecondRecord->getLocation(),
9736 SecondBase.getSourceRange(), BaseVirtual)
9737 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9738 break;
9739 }
9740
9741 if (FirstBase.getAccessSpecifierAsWritten() !=
9742 SecondBase.getAccessSpecifierAsWritten()) {
9743 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9744 BaseAccess)
9745 << (i + 1) << FirstBase.getType()
9746 << (int)FirstBase.getAccessSpecifierAsWritten();
9747 ODRDiagNote(SecondRecord->getLocation(),
9748 SecondBase.getSourceRange(), BaseAccess)
9749 << (i + 1) << SecondBase.getType()
9750 << (int)SecondBase.getAccessSpecifierAsWritten();
9751 break;
9752 }
9753 }
9754
9755 if (i != FirstNumBases) {
9756 Diagnosed = true;
9757 break;
9758 }
9759 }
9760
Richard Trieue7f7ed22017-02-22 01:11:25 +00009761 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009762
9763 const ClassTemplateDecl *FirstTemplate =
9764 FirstRecord->getDescribedClassTemplate();
9765 const ClassTemplateDecl *SecondTemplate =
9766 SecondRecord->getDescribedClassTemplate();
9767
9768 assert(!FirstTemplate == !SecondTemplate &&
9769 "Both pointers should be null or non-null");
9770
9771 enum ODRTemplateDifference {
9772 ParamEmptyName,
9773 ParamName,
9774 ParamSingleDefaultArgument,
9775 ParamDifferentDefaultArgument,
9776 };
9777
9778 if (FirstTemplate && SecondTemplate) {
9779 DeclHashes FirstTemplateHashes;
9780 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009781
9782 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009783 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9784 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009785 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009786 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009787 }
9788 };
9789
9790 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9791 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9792
9793 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9794 "Number of template parameters should be equal.");
9795
9796 auto FirstIt = FirstTemplateHashes.begin();
9797 auto FirstEnd = FirstTemplateHashes.end();
9798 auto SecondIt = SecondTemplateHashes.begin();
9799 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9800 if (FirstIt->second == SecondIt->second)
9801 continue;
9802
9803 auto ODRDiagError = [FirstRecord, &FirstModule,
9804 this](SourceLocation Loc, SourceRange Range,
9805 ODRTemplateDifference DiffType) {
9806 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9807 << FirstRecord << FirstModule.empty() << FirstModule << Range
9808 << DiffType;
9809 };
9810 auto ODRDiagNote = [&SecondModule,
9811 this](SourceLocation Loc, SourceRange Range,
9812 ODRTemplateDifference DiffType) {
9813 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9814 << SecondModule << Range << DiffType;
9815 };
9816
Vedant Kumar48b4f762018-04-14 01:40:48 +00009817 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9818 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009819
9820 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9821 "Parameter Decl's should be the same kind.");
9822
9823 DeclarationName FirstName = FirstDecl->getDeclName();
9824 DeclarationName SecondName = SecondDecl->getDeclName();
9825
9826 if (FirstName != SecondName) {
9827 const bool FirstNameEmpty =
9828 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9829 const bool SecondNameEmpty =
9830 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9831 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9832 "Both template parameters cannot be unnamed.");
9833 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9834 FirstNameEmpty ? ParamEmptyName : ParamName)
9835 << FirstName;
9836 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9837 SecondNameEmpty ? ParamEmptyName : ParamName)
9838 << SecondName;
9839 break;
9840 }
9841
9842 switch (FirstDecl->getKind()) {
9843 default:
9844 llvm_unreachable("Invalid template parameter type.");
9845 case Decl::TemplateTypeParm: {
9846 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9847 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9848 const bool HasFirstDefaultArgument =
9849 FirstParam->hasDefaultArgument() &&
9850 !FirstParam->defaultArgumentWasInherited();
9851 const bool HasSecondDefaultArgument =
9852 SecondParam->hasDefaultArgument() &&
9853 !SecondParam->defaultArgumentWasInherited();
9854
9855 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9856 ODRDiagError(FirstDecl->getLocation(),
9857 FirstDecl->getSourceRange(),
9858 ParamSingleDefaultArgument)
9859 << HasFirstDefaultArgument;
9860 ODRDiagNote(SecondDecl->getLocation(),
9861 SecondDecl->getSourceRange(),
9862 ParamSingleDefaultArgument)
9863 << HasSecondDefaultArgument;
9864 break;
9865 }
9866
9867 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9868 "Expecting default arguments.");
9869
9870 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9871 ParamDifferentDefaultArgument);
9872 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9873 ParamDifferentDefaultArgument);
9874
9875 break;
9876 }
9877 case Decl::NonTypeTemplateParm: {
9878 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9879 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9880 const bool HasFirstDefaultArgument =
9881 FirstParam->hasDefaultArgument() &&
9882 !FirstParam->defaultArgumentWasInherited();
9883 const bool HasSecondDefaultArgument =
9884 SecondParam->hasDefaultArgument() &&
9885 !SecondParam->defaultArgumentWasInherited();
9886
9887 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9888 ODRDiagError(FirstDecl->getLocation(),
9889 FirstDecl->getSourceRange(),
9890 ParamSingleDefaultArgument)
9891 << HasFirstDefaultArgument;
9892 ODRDiagNote(SecondDecl->getLocation(),
9893 SecondDecl->getSourceRange(),
9894 ParamSingleDefaultArgument)
9895 << HasSecondDefaultArgument;
9896 break;
9897 }
9898
9899 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9900 "Expecting default arguments.");
9901
9902 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9903 ParamDifferentDefaultArgument);
9904 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9905 ParamDifferentDefaultArgument);
9906
9907 break;
9908 }
9909 case Decl::TemplateTemplateParm: {
9910 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9911 const auto *SecondParam =
9912 cast<TemplateTemplateParmDecl>(SecondDecl);
9913 const bool HasFirstDefaultArgument =
9914 FirstParam->hasDefaultArgument() &&
9915 !FirstParam->defaultArgumentWasInherited();
9916 const bool HasSecondDefaultArgument =
9917 SecondParam->hasDefaultArgument() &&
9918 !SecondParam->defaultArgumentWasInherited();
9919
9920 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9921 ODRDiagError(FirstDecl->getLocation(),
9922 FirstDecl->getSourceRange(),
9923 ParamSingleDefaultArgument)
9924 << HasFirstDefaultArgument;
9925 ODRDiagNote(SecondDecl->getLocation(),
9926 SecondDecl->getSourceRange(),
9927 ParamSingleDefaultArgument)
9928 << HasSecondDefaultArgument;
9929 break;
9930 }
9931
9932 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9933 "Expecting default arguments.");
9934
9935 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9936 ParamDifferentDefaultArgument);
9937 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9938 ParamDifferentDefaultArgument);
9939
9940 break;
9941 }
9942 }
9943
9944 break;
9945 }
9946
9947 if (FirstIt != FirstEnd) {
9948 Diagnosed = true;
9949 break;
9950 }
9951 }
9952
Richard Trieue7f7ed22017-02-22 01:11:25 +00009953 DeclHashes FirstHashes;
9954 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009955
Richard Trieue6caa262017-12-23 00:41:01 +00009956 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9957 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009958 for (auto *D : Record->decls()) {
9959 // Due to decl merging, the first CXXRecordDecl is the parent of
9960 // Decls in both records.
9961 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9962 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009963 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009964 }
9965 };
9966 PopulateHashes(FirstHashes, FirstRecord);
9967 PopulateHashes(SecondHashes, SecondRecord);
9968
9969 // Used with err_module_odr_violation_mismatch_decl and
9970 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009971 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009972 enum {
9973 EndOfClass,
9974 PublicSpecifer,
9975 PrivateSpecifer,
9976 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009977 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009978 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009979 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009980 TypeAlias,
9981 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009982 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009983 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009984 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009985 Other
9986 } FirstDiffType = Other,
9987 SecondDiffType = Other;
9988
9989 auto DifferenceSelector = [](Decl *D) {
9990 assert(D && "valid Decl required");
9991 switch (D->getKind()) {
9992 default:
9993 return Other;
9994 case Decl::AccessSpec:
9995 switch (D->getAccess()) {
9996 case AS_public:
9997 return PublicSpecifer;
9998 case AS_private:
9999 return PrivateSpecifer;
10000 case AS_protected:
10001 return ProtectedSpecifer;
10002 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010003 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010004 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010005 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010006 case Decl::StaticAssert:
10007 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010008 case Decl::Field:
10009 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010010 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010011 case Decl::CXXConstructor:
10012 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010013 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010014 case Decl::TypeAlias:
10015 return TypeAlias;
10016 case Decl::Typedef:
10017 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010018 case Decl::Var:
10019 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010020 case Decl::Friend:
10021 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010022 case Decl::FunctionTemplate:
10023 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010024 }
10025 };
10026
10027 Decl *FirstDecl = nullptr;
10028 Decl *SecondDecl = nullptr;
10029 auto FirstIt = FirstHashes.begin();
10030 auto SecondIt = SecondHashes.begin();
10031
10032 // If there is a diagnoseable difference, FirstDiffType and
10033 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10034 // filled in if not EndOfClass.
10035 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010036 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10037 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010038 ++FirstIt;
10039 ++SecondIt;
10040 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010041 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010042
Richard Trieue7f7ed22017-02-22 01:11:25 +000010043 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10044 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10045
10046 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10047 SecondDiffType =
10048 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10049
10050 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010051 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010052
10053 if (FirstDiffType == Other || SecondDiffType == Other) {
10054 // Reaching this point means an unexpected Decl was encountered
10055 // or no difference was detected. This causes a generic error
10056 // message to be emitted.
10057 Diag(FirstRecord->getLocation(),
10058 diag::err_module_odr_violation_different_definitions)
10059 << FirstRecord << FirstModule.empty() << FirstModule;
10060
Richard Trieuca48d362017-06-21 01:43:13 +000010061 if (FirstDecl) {
10062 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10063 << FirstRecord << FirstDecl->getSourceRange();
10064 }
10065
Richard Trieue7f7ed22017-02-22 01:11:25 +000010066 Diag(SecondRecord->getLocation(),
10067 diag::note_module_odr_violation_different_definitions)
10068 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010069
10070 if (SecondDecl) {
10071 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10072 << SecondDecl->getSourceRange();
10073 }
10074
Richard Trieue7f7ed22017-02-22 01:11:25 +000010075 Diagnosed = true;
10076 break;
10077 }
10078
10079 if (FirstDiffType != SecondDiffType) {
10080 SourceLocation FirstLoc;
10081 SourceRange FirstRange;
10082 if (FirstDiffType == EndOfClass) {
10083 FirstLoc = FirstRecord->getBraceRange().getEnd();
10084 } else {
10085 FirstLoc = FirstIt->first->getLocation();
10086 FirstRange = FirstIt->first->getSourceRange();
10087 }
10088 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10089 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10090 << FirstDiffType;
10091
10092 SourceLocation SecondLoc;
10093 SourceRange SecondRange;
10094 if (SecondDiffType == EndOfClass) {
10095 SecondLoc = SecondRecord->getBraceRange().getEnd();
10096 } else {
10097 SecondLoc = SecondDecl->getLocation();
10098 SecondRange = SecondDecl->getSourceRange();
10099 }
10100 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10101 << SecondModule << SecondRange << SecondDiffType;
10102 Diagnosed = true;
10103 break;
10104 }
10105
Richard Trieu639d7b62017-02-22 22:22:42 +000010106 assert(FirstDiffType == SecondDiffType);
10107
10108 // Used with err_module_odr_violation_mismatch_decl_diff and
10109 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010110 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010111 StaticAssertCondition,
10112 StaticAssertMessage,
10113 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010114 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010115 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010116 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010117 FieldDifferentWidthBitField,
10118 FieldSingleMutable,
10119 FieldSingleInitializer,
10120 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010121 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010122 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010123 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010124 MethodVirtual,
10125 MethodStatic,
10126 MethodVolatile,
10127 MethodConst,
10128 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010129 MethodNumberParameters,
10130 MethodParameterType,
10131 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010132 MethodParameterSingleDefaultArgument,
10133 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010134 MethodNoTemplateArguments,
10135 MethodDifferentNumberTemplateArguments,
10136 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010137 MethodSingleBody,
10138 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010139 TypedefName,
10140 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010141 VarName,
10142 VarType,
10143 VarSingleInitializer,
10144 VarDifferentInitializer,
10145 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010146 FriendTypeFunction,
10147 FriendType,
10148 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010149 FunctionTemplateDifferentNumberParameters,
10150 FunctionTemplateParameterDifferentKind,
10151 FunctionTemplateParameterName,
10152 FunctionTemplateParameterSingleDefaultArgument,
10153 FunctionTemplateParameterDifferentDefaultArgument,
10154 FunctionTemplateParameterDifferentType,
10155 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010156 };
10157
10158 // These lambdas have the common portions of the ODR diagnostics. This
10159 // has the same return as Diag(), so addition parameters can be passed
10160 // in with operator<<
10161 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10162 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10163 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10164 << FirstRecord << FirstModule.empty() << FirstModule << Range
10165 << DiffType;
10166 };
10167 auto ODRDiagNote = [&SecondModule, this](
10168 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10169 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10170 << SecondModule << Range << DiffType;
10171 };
10172
Richard Trieu639d7b62017-02-22 22:22:42 +000010173 switch (FirstDiffType) {
10174 case Other:
10175 case EndOfClass:
10176 case PublicSpecifer:
10177 case PrivateSpecifer:
10178 case ProtectedSpecifer:
10179 llvm_unreachable("Invalid diff type");
10180
10181 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010182 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10183 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010184
10185 Expr *FirstExpr = FirstSA->getAssertExpr();
10186 Expr *SecondExpr = SecondSA->getAssertExpr();
10187 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10188 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10189 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010190 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010191 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010192 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10193 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010194 Diagnosed = true;
10195 break;
10196 }
10197
10198 StringLiteral *FirstStr = FirstSA->getMessage();
10199 StringLiteral *SecondStr = SecondSA->getMessage();
10200 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10201 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10202 SourceLocation FirstLoc, SecondLoc;
10203 SourceRange FirstRange, SecondRange;
10204 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010205 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010206 FirstRange = FirstStr->getSourceRange();
10207 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010208 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010209 FirstRange = FirstSA->getSourceRange();
10210 }
10211 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010212 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010213 SecondRange = SecondStr->getSourceRange();
10214 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010215 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010216 SecondRange = SecondSA->getSourceRange();
10217 }
10218 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10219 << (FirstStr == nullptr);
10220 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10221 << (SecondStr == nullptr);
10222 Diagnosed = true;
10223 break;
10224 }
10225
10226 if (FirstStr && SecondStr &&
10227 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010228 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010229 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010230 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010231 StaticAssertMessage);
10232 Diagnosed = true;
10233 break;
10234 }
10235 break;
10236 }
Richard Trieud0786092017-02-23 00:23:01 +000010237 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010238 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10239 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010240 IdentifierInfo *FirstII = FirstField->getIdentifier();
10241 IdentifierInfo *SecondII = SecondField->getIdentifier();
10242 if (FirstII->getName() != SecondII->getName()) {
10243 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10244 FieldName)
10245 << FirstII;
10246 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10247 FieldName)
10248 << SecondII;
10249
10250 Diagnosed = true;
10251 break;
10252 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010253
Richard Smithdbafb6c2017-06-29 23:23:46 +000010254 assert(getContext().hasSameType(FirstField->getType(),
10255 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010256
10257 QualType FirstType = FirstField->getType();
10258 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010259 if (ComputeQualTypeODRHash(FirstType) !=
10260 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010261 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10262 FieldTypeName)
10263 << FirstII << FirstType;
10264 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10265 FieldTypeName)
10266 << SecondII << SecondType;
10267
10268 Diagnosed = true;
10269 break;
10270 }
10271
Richard Trieu93772fc2017-02-24 20:59:28 +000010272 const bool IsFirstBitField = FirstField->isBitField();
10273 const bool IsSecondBitField = SecondField->isBitField();
10274 if (IsFirstBitField != IsSecondBitField) {
10275 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10276 FieldSingleBitField)
10277 << FirstII << IsFirstBitField;
10278 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10279 FieldSingleBitField)
10280 << SecondII << IsSecondBitField;
10281 Diagnosed = true;
10282 break;
10283 }
10284
10285 if (IsFirstBitField && IsSecondBitField) {
10286 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10287 FieldDifferentWidthBitField)
10288 << FirstII << FirstField->getBitWidth()->getSourceRange();
10289 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10290 FieldDifferentWidthBitField)
10291 << SecondII << SecondField->getBitWidth()->getSourceRange();
10292 Diagnosed = true;
10293 break;
10294 }
10295
Richard Trieu8d543e22017-02-24 23:35:37 +000010296 const bool IsFirstMutable = FirstField->isMutable();
10297 const bool IsSecondMutable = SecondField->isMutable();
10298 if (IsFirstMutable != IsSecondMutable) {
10299 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10300 FieldSingleMutable)
10301 << FirstII << IsFirstMutable;
10302 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10303 FieldSingleMutable)
10304 << SecondII << IsSecondMutable;
10305 Diagnosed = true;
10306 break;
10307 }
10308
10309 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10310 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10311 if ((!FirstInitializer && SecondInitializer) ||
10312 (FirstInitializer && !SecondInitializer)) {
10313 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10314 FieldSingleInitializer)
10315 << FirstII << (FirstInitializer != nullptr);
10316 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10317 FieldSingleInitializer)
10318 << SecondII << (SecondInitializer != nullptr);
10319 Diagnosed = true;
10320 break;
10321 }
10322
10323 if (FirstInitializer && SecondInitializer) {
10324 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10325 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10326 if (FirstInitHash != SecondInitHash) {
10327 ODRDiagError(FirstField->getLocation(),
10328 FirstField->getSourceRange(),
10329 FieldDifferentInitializers)
10330 << FirstII << FirstInitializer->getSourceRange();
10331 ODRDiagNote(SecondField->getLocation(),
10332 SecondField->getSourceRange(),
10333 FieldDifferentInitializers)
10334 << SecondII << SecondInitializer->getSourceRange();
10335 Diagnosed = true;
10336 break;
10337 }
10338 }
10339
Richard Trieud0786092017-02-23 00:23:01 +000010340 break;
10341 }
Richard Trieu48143742017-02-28 21:24:38 +000010342 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010343 enum {
10344 DiagMethod,
10345 DiagConstructor,
10346 DiagDestructor,
10347 } FirstMethodType,
10348 SecondMethodType;
10349 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10350 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10351 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10352 return DiagMethod;
10353 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010354 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10355 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010356 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10357 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010358 auto FirstName = FirstMethod->getDeclName();
10359 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010360 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010361 ODRDiagError(FirstMethod->getLocation(),
10362 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010363 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010364 ODRDiagNote(SecondMethod->getLocation(),
10365 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010366 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010367
10368 Diagnosed = true;
10369 break;
10370 }
10371
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010372 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10373 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010374 if (FirstDeleted != SecondDeleted) {
10375 ODRDiagError(FirstMethod->getLocation(),
10376 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010377 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010378
10379 ODRDiagNote(SecondMethod->getLocation(),
10380 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010381 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010382 Diagnosed = true;
10383 break;
10384 }
10385
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010386 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10387 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10388 if (FirstDefaulted != SecondDefaulted) {
10389 ODRDiagError(FirstMethod->getLocation(),
10390 FirstMethod->getSourceRange(), MethodDefaulted)
10391 << FirstMethodType << FirstName << FirstDefaulted;
10392
10393 ODRDiagNote(SecondMethod->getLocation(),
10394 SecondMethod->getSourceRange(), MethodDefaulted)
10395 << SecondMethodType << SecondName << SecondDefaulted;
10396 Diagnosed = true;
10397 break;
10398 }
10399
Richard Trieu583e2c12017-03-04 00:08:58 +000010400 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10401 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10402 const bool FirstPure = FirstMethod->isPure();
10403 const bool SecondPure = SecondMethod->isPure();
10404 if ((FirstVirtual || SecondVirtual) &&
10405 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10406 ODRDiagError(FirstMethod->getLocation(),
10407 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010408 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010409 ODRDiagNote(SecondMethod->getLocation(),
10410 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010411 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010412 Diagnosed = true;
10413 break;
10414 }
10415
10416 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10417 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10418 // class needs to be checked instead.
10419 const auto FirstStorage = FirstMethod->getStorageClass();
10420 const auto SecondStorage = SecondMethod->getStorageClass();
10421 const bool FirstStatic = FirstStorage == SC_Static;
10422 const bool SecondStatic = SecondStorage == SC_Static;
10423 if (FirstStatic != SecondStatic) {
10424 ODRDiagError(FirstMethod->getLocation(),
10425 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010426 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010427 ODRDiagNote(SecondMethod->getLocation(),
10428 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010429 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010430 Diagnosed = true;
10431 break;
10432 }
10433
10434 const bool FirstVolatile = FirstMethod->isVolatile();
10435 const bool SecondVolatile = SecondMethod->isVolatile();
10436 if (FirstVolatile != SecondVolatile) {
10437 ODRDiagError(FirstMethod->getLocation(),
10438 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010439 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010440 ODRDiagNote(SecondMethod->getLocation(),
10441 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010442 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010443 Diagnosed = true;
10444 break;
10445 }
10446
10447 const bool FirstConst = FirstMethod->isConst();
10448 const bool SecondConst = SecondMethod->isConst();
10449 if (FirstConst != SecondConst) {
10450 ODRDiagError(FirstMethod->getLocation(),
10451 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010452 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010453 ODRDiagNote(SecondMethod->getLocation(),
10454 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010455 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010456 Diagnosed = true;
10457 break;
10458 }
10459
10460 const bool FirstInline = FirstMethod->isInlineSpecified();
10461 const bool SecondInline = SecondMethod->isInlineSpecified();
10462 if (FirstInline != SecondInline) {
10463 ODRDiagError(FirstMethod->getLocation(),
10464 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010465 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010466 ODRDiagNote(SecondMethod->getLocation(),
10467 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010468 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010469 Diagnosed = true;
10470 break;
10471 }
10472
Richard Trieu02552272017-05-02 23:58:52 +000010473 const unsigned FirstNumParameters = FirstMethod->param_size();
10474 const unsigned SecondNumParameters = SecondMethod->param_size();
10475 if (FirstNumParameters != SecondNumParameters) {
10476 ODRDiagError(FirstMethod->getLocation(),
10477 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010478 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010479 ODRDiagNote(SecondMethod->getLocation(),
10480 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010481 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010482 Diagnosed = true;
10483 break;
10484 }
10485
10486 // Need this status boolean to know when break out of the switch.
10487 bool ParameterMismatch = false;
10488 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10489 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10490 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10491
10492 QualType FirstParamType = FirstParam->getType();
10493 QualType SecondParamType = SecondParam->getType();
10494 if (FirstParamType != SecondParamType &&
10495 ComputeQualTypeODRHash(FirstParamType) !=
10496 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010497 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010498 FirstParamType->getAs<DecayedType>()) {
10499 ODRDiagError(FirstMethod->getLocation(),
10500 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010501 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10502 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010503 } else {
10504 ODRDiagError(FirstMethod->getLocation(),
10505 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010506 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10507 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010508 }
10509
Vedant Kumar48b4f762018-04-14 01:40:48 +000010510 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010511 SecondParamType->getAs<DecayedType>()) {
10512 ODRDiagNote(SecondMethod->getLocation(),
10513 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010514 << SecondMethodType << SecondName << (I + 1)
10515 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010516 << ParamDecayedType->getOriginalType();
10517 } else {
10518 ODRDiagNote(SecondMethod->getLocation(),
10519 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010520 << SecondMethodType << SecondName << (I + 1)
10521 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010522 }
10523 ParameterMismatch = true;
10524 break;
10525 }
10526
10527 DeclarationName FirstParamName = FirstParam->getDeclName();
10528 DeclarationName SecondParamName = SecondParam->getDeclName();
10529 if (FirstParamName != SecondParamName) {
10530 ODRDiagError(FirstMethod->getLocation(),
10531 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010532 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010533 ODRDiagNote(SecondMethod->getLocation(),
10534 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010535 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010536 ParameterMismatch = true;
10537 break;
10538 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010539
10540 const Expr *FirstInit = FirstParam->getInit();
10541 const Expr *SecondInit = SecondParam->getInit();
10542 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10543 ODRDiagError(FirstMethod->getLocation(),
10544 FirstMethod->getSourceRange(),
10545 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010546 << FirstMethodType << FirstName << (I + 1)
10547 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010548 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10549 ODRDiagNote(SecondMethod->getLocation(),
10550 SecondMethod->getSourceRange(),
10551 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010552 << SecondMethodType << SecondName << (I + 1)
10553 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010554 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10555 ParameterMismatch = true;
10556 break;
10557 }
10558
10559 if (FirstInit && SecondInit &&
10560 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10561 ODRDiagError(FirstMethod->getLocation(),
10562 FirstMethod->getSourceRange(),
10563 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010564 << FirstMethodType << FirstName << (I + 1)
10565 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010566 ODRDiagNote(SecondMethod->getLocation(),
10567 SecondMethod->getSourceRange(),
10568 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010569 << SecondMethodType << SecondName << (I + 1)
10570 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010571 ParameterMismatch = true;
10572 break;
10573
10574 }
Richard Trieu02552272017-05-02 23:58:52 +000010575 }
10576
10577 if (ParameterMismatch) {
10578 Diagnosed = true;
10579 break;
10580 }
10581
Richard Trieu7282d322018-04-25 00:31:15 +000010582 const auto *FirstTemplateArgs =
10583 FirstMethod->getTemplateSpecializationArgs();
10584 const auto *SecondTemplateArgs =
10585 SecondMethod->getTemplateSpecializationArgs();
10586
10587 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10588 (!FirstTemplateArgs && SecondTemplateArgs)) {
10589 ODRDiagError(FirstMethod->getLocation(),
10590 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10591 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10592 ODRDiagNote(SecondMethod->getLocation(),
10593 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10594 << SecondMethodType << SecondName
10595 << (SecondTemplateArgs != nullptr);
10596
10597 Diagnosed = true;
10598 break;
10599 }
10600
10601 if (FirstTemplateArgs && SecondTemplateArgs) {
10602 // Remove pack expansions from argument list.
10603 auto ExpandTemplateArgumentList =
10604 [](const TemplateArgumentList *TAL) {
10605 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10606 for (const TemplateArgument &TA : TAL->asArray()) {
10607 if (TA.getKind() != TemplateArgument::Pack) {
10608 ExpandedList.push_back(&TA);
10609 continue;
10610 }
10611 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10612 ExpandedList.push_back(&PackTA);
10613 }
10614 }
10615 return ExpandedList;
10616 };
10617 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10618 ExpandTemplateArgumentList(FirstTemplateArgs);
10619 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10620 ExpandTemplateArgumentList(SecondTemplateArgs);
10621
10622 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10623 ODRDiagError(FirstMethod->getLocation(),
10624 FirstMethod->getSourceRange(),
10625 MethodDifferentNumberTemplateArguments)
10626 << FirstMethodType << FirstName
10627 << (unsigned)FirstExpandedList.size();
10628 ODRDiagNote(SecondMethod->getLocation(),
10629 SecondMethod->getSourceRange(),
10630 MethodDifferentNumberTemplateArguments)
10631 << SecondMethodType << SecondName
10632 << (unsigned)SecondExpandedList.size();
10633
10634 Diagnosed = true;
10635 break;
10636 }
10637
10638 bool TemplateArgumentMismatch = false;
10639 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10640 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10641 &SecondTA = *SecondExpandedList[i];
10642 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10643 ComputeTemplateArgumentODRHash(SecondTA)) {
10644 continue;
10645 }
10646
10647 ODRDiagError(FirstMethod->getLocation(),
10648 FirstMethod->getSourceRange(),
10649 MethodDifferentTemplateArgument)
10650 << FirstMethodType << FirstName << FirstTA << i + 1;
10651 ODRDiagNote(SecondMethod->getLocation(),
10652 SecondMethod->getSourceRange(),
10653 MethodDifferentTemplateArgument)
10654 << SecondMethodType << SecondName << SecondTA << i + 1;
10655
10656 TemplateArgumentMismatch = true;
10657 break;
10658 }
10659
10660 if (TemplateArgumentMismatch) {
10661 Diagnosed = true;
10662 break;
10663 }
10664 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010665
10666 // Compute the hash of the method as if it has no body.
10667 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10668 Hash.clear();
10669 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10670 return Hash.CalculateHash();
10671 };
10672
10673 // Compare the hash generated to the hash stored. A difference means
10674 // that a body was present in the original source. Due to merging,
10675 // the stardard way of detecting a body will not work.
10676 const bool HasFirstBody =
10677 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10678 const bool HasSecondBody =
10679 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10680
10681 if (HasFirstBody != HasSecondBody) {
10682 ODRDiagError(FirstMethod->getLocation(),
10683 FirstMethod->getSourceRange(), MethodSingleBody)
10684 << FirstMethodType << FirstName << HasFirstBody;
10685 ODRDiagNote(SecondMethod->getLocation(),
10686 SecondMethod->getSourceRange(), MethodSingleBody)
10687 << SecondMethodType << SecondName << HasSecondBody;
10688 Diagnosed = true;
10689 break;
10690 }
10691
10692 if (HasFirstBody && HasSecondBody) {
10693 ODRDiagError(FirstMethod->getLocation(),
10694 FirstMethod->getSourceRange(), MethodDifferentBody)
10695 << FirstMethodType << FirstName;
10696 ODRDiagNote(SecondMethod->getLocation(),
10697 SecondMethod->getSourceRange(), MethodDifferentBody)
10698 << SecondMethodType << SecondName;
10699 Diagnosed = true;
10700 break;
10701 }
10702
Richard Trieu48143742017-02-28 21:24:38 +000010703 break;
10704 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010705 case TypeAlias:
10706 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010707 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10708 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010709 auto FirstName = FirstTD->getDeclName();
10710 auto SecondName = SecondTD->getDeclName();
10711 if (FirstName != SecondName) {
10712 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10713 TypedefName)
10714 << (FirstDiffType == TypeAlias) << FirstName;
10715 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10716 TypedefName)
10717 << (FirstDiffType == TypeAlias) << SecondName;
10718 Diagnosed = true;
10719 break;
10720 }
10721
10722 QualType FirstType = FirstTD->getUnderlyingType();
10723 QualType SecondType = SecondTD->getUnderlyingType();
10724 if (ComputeQualTypeODRHash(FirstType) !=
10725 ComputeQualTypeODRHash(SecondType)) {
10726 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10727 TypedefType)
10728 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10729 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10730 TypedefType)
10731 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10732 Diagnosed = true;
10733 break;
10734 }
10735 break;
10736 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010737 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010738 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10739 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010740 auto FirstName = FirstVD->getDeclName();
10741 auto SecondName = SecondVD->getDeclName();
10742 if (FirstName != SecondName) {
10743 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10744 VarName)
10745 << FirstName;
10746 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10747 VarName)
10748 << SecondName;
10749 Diagnosed = true;
10750 break;
10751 }
10752
10753 QualType FirstType = FirstVD->getType();
10754 QualType SecondType = SecondVD->getType();
10755 if (ComputeQualTypeODRHash(FirstType) !=
10756 ComputeQualTypeODRHash(SecondType)) {
10757 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10758 VarType)
10759 << FirstName << FirstType;
10760 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10761 VarType)
10762 << SecondName << SecondType;
10763 Diagnosed = true;
10764 break;
10765 }
10766
10767 const Expr *FirstInit = FirstVD->getInit();
10768 const Expr *SecondInit = SecondVD->getInit();
10769 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10770 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10771 VarSingleInitializer)
10772 << FirstName << (FirstInit == nullptr)
10773 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10774 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10775 VarSingleInitializer)
10776 << SecondName << (SecondInit == nullptr)
10777 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10778 Diagnosed = true;
10779 break;
10780 }
10781
10782 if (FirstInit && SecondInit &&
10783 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10784 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10785 VarDifferentInitializer)
10786 << FirstName << FirstInit->getSourceRange();
10787 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10788 VarDifferentInitializer)
10789 << SecondName << SecondInit->getSourceRange();
10790 Diagnosed = true;
10791 break;
10792 }
10793
10794 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10795 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10796 if (FirstIsConstexpr != SecondIsConstexpr) {
10797 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10798 VarConstexpr)
10799 << FirstName << FirstIsConstexpr;
10800 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10801 VarConstexpr)
10802 << SecondName << SecondIsConstexpr;
10803 Diagnosed = true;
10804 break;
10805 }
10806 break;
10807 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010808 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010809 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10810 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010811
10812 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10813 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10814
10815 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10816 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10817
10818 if (FirstND && SecondND) {
10819 ODRDiagError(FirstFriend->getFriendLoc(),
10820 FirstFriend->getSourceRange(), FriendFunction)
10821 << FirstND;
10822 ODRDiagNote(SecondFriend->getFriendLoc(),
10823 SecondFriend->getSourceRange(), FriendFunction)
10824 << SecondND;
10825
10826 Diagnosed = true;
10827 break;
10828 }
10829
10830 if (FirstTSI && SecondTSI) {
10831 QualType FirstFriendType = FirstTSI->getType();
10832 QualType SecondFriendType = SecondTSI->getType();
10833 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10834 ComputeQualTypeODRHash(SecondFriendType));
10835 ODRDiagError(FirstFriend->getFriendLoc(),
10836 FirstFriend->getSourceRange(), FriendType)
10837 << FirstFriendType;
10838 ODRDiagNote(SecondFriend->getFriendLoc(),
10839 SecondFriend->getSourceRange(), FriendType)
10840 << SecondFriendType;
10841 Diagnosed = true;
10842 break;
10843 }
10844
10845 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10846 FriendTypeFunction)
10847 << (FirstTSI == nullptr);
10848 ODRDiagNote(SecondFriend->getFriendLoc(),
10849 SecondFriend->getSourceRange(), FriendTypeFunction)
10850 << (SecondTSI == nullptr);
10851
10852 Diagnosed = true;
10853 break;
10854 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010855 case FunctionTemplate: {
10856 FunctionTemplateDecl *FirstTemplate =
10857 cast<FunctionTemplateDecl>(FirstDecl);
10858 FunctionTemplateDecl *SecondTemplate =
10859 cast<FunctionTemplateDecl>(SecondDecl);
10860
10861 TemplateParameterList *FirstTPL =
10862 FirstTemplate->getTemplateParameters();
10863 TemplateParameterList *SecondTPL =
10864 SecondTemplate->getTemplateParameters();
10865
10866 if (FirstTPL->size() != SecondTPL->size()) {
10867 ODRDiagError(FirstTemplate->getLocation(),
10868 FirstTemplate->getSourceRange(),
10869 FunctionTemplateDifferentNumberParameters)
10870 << FirstTemplate << FirstTPL->size();
10871 ODRDiagNote(SecondTemplate->getLocation(),
10872 SecondTemplate->getSourceRange(),
10873 FunctionTemplateDifferentNumberParameters)
10874 << SecondTemplate << SecondTPL->size();
10875
10876 Diagnosed = true;
10877 break;
10878 }
10879
10880 bool ParameterMismatch = false;
10881 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10882 NamedDecl *FirstParam = FirstTPL->getParam(i);
10883 NamedDecl *SecondParam = SecondTPL->getParam(i);
10884
10885 if (FirstParam->getKind() != SecondParam->getKind()) {
10886 enum {
10887 TemplateTypeParameter,
10888 NonTypeTemplateParameter,
10889 TemplateTemplateParameter,
10890 };
10891 auto GetParamType = [](NamedDecl *D) {
10892 switch (D->getKind()) {
10893 default:
10894 llvm_unreachable("Unexpected template parameter type");
10895 case Decl::TemplateTypeParm:
10896 return TemplateTypeParameter;
10897 case Decl::NonTypeTemplateParm:
10898 return NonTypeTemplateParameter;
10899 case Decl::TemplateTemplateParm:
10900 return TemplateTemplateParameter;
10901 }
10902 };
10903
10904 ODRDiagError(FirstTemplate->getLocation(),
10905 FirstTemplate->getSourceRange(),
10906 FunctionTemplateParameterDifferentKind)
10907 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10908 ODRDiagNote(SecondTemplate->getLocation(),
10909 SecondTemplate->getSourceRange(),
10910 FunctionTemplateParameterDifferentKind)
10911 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10912
10913 ParameterMismatch = true;
10914 break;
10915 }
10916
10917 if (FirstParam->getName() != SecondParam->getName()) {
10918 ODRDiagError(FirstTemplate->getLocation(),
10919 FirstTemplate->getSourceRange(),
10920 FunctionTemplateParameterName)
10921 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10922 << FirstParam;
10923 ODRDiagNote(SecondTemplate->getLocation(),
10924 SecondTemplate->getSourceRange(),
10925 FunctionTemplateParameterName)
10926 << SecondTemplate << (i + 1)
10927 << (bool)SecondParam->getIdentifier() << SecondParam;
10928 ParameterMismatch = true;
10929 break;
10930 }
10931
10932 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10933 isa<TemplateTypeParmDecl>(SecondParam)) {
10934 TemplateTypeParmDecl *FirstTTPD =
10935 cast<TemplateTypeParmDecl>(FirstParam);
10936 TemplateTypeParmDecl *SecondTTPD =
10937 cast<TemplateTypeParmDecl>(SecondParam);
10938 bool HasFirstDefaultArgument =
10939 FirstTTPD->hasDefaultArgument() &&
10940 !FirstTTPD->defaultArgumentWasInherited();
10941 bool HasSecondDefaultArgument =
10942 SecondTTPD->hasDefaultArgument() &&
10943 !SecondTTPD->defaultArgumentWasInherited();
10944 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10945 ODRDiagError(FirstTemplate->getLocation(),
10946 FirstTemplate->getSourceRange(),
10947 FunctionTemplateParameterSingleDefaultArgument)
10948 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10949 ODRDiagNote(SecondTemplate->getLocation(),
10950 SecondTemplate->getSourceRange(),
10951 FunctionTemplateParameterSingleDefaultArgument)
10952 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10953 ParameterMismatch = true;
10954 break;
10955 }
10956
10957 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10958 QualType FirstType = FirstTTPD->getDefaultArgument();
10959 QualType SecondType = SecondTTPD->getDefaultArgument();
10960 if (ComputeQualTypeODRHash(FirstType) !=
10961 ComputeQualTypeODRHash(SecondType)) {
10962 ODRDiagError(FirstTemplate->getLocation(),
10963 FirstTemplate->getSourceRange(),
10964 FunctionTemplateParameterDifferentDefaultArgument)
10965 << FirstTemplate << (i + 1) << FirstType;
10966 ODRDiagNote(SecondTemplate->getLocation(),
10967 SecondTemplate->getSourceRange(),
10968 FunctionTemplateParameterDifferentDefaultArgument)
10969 << SecondTemplate << (i + 1) << SecondType;
10970 ParameterMismatch = true;
10971 break;
10972 }
10973 }
10974
10975 if (FirstTTPD->isParameterPack() !=
10976 SecondTTPD->isParameterPack()) {
10977 ODRDiagError(FirstTemplate->getLocation(),
10978 FirstTemplate->getSourceRange(),
10979 FunctionTemplatePackParameter)
10980 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10981 ODRDiagNote(SecondTemplate->getLocation(),
10982 SecondTemplate->getSourceRange(),
10983 FunctionTemplatePackParameter)
10984 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10985 ParameterMismatch = true;
10986 break;
10987 }
10988 }
10989
10990 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10991 isa<TemplateTemplateParmDecl>(SecondParam)) {
10992 TemplateTemplateParmDecl *FirstTTPD =
10993 cast<TemplateTemplateParmDecl>(FirstParam);
10994 TemplateTemplateParmDecl *SecondTTPD =
10995 cast<TemplateTemplateParmDecl>(SecondParam);
10996
10997 TemplateParameterList *FirstTPL =
10998 FirstTTPD->getTemplateParameters();
10999 TemplateParameterList *SecondTPL =
11000 SecondTTPD->getTemplateParameters();
11001
11002 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11003 ComputeTemplateParameterListODRHash(SecondTPL)) {
11004 ODRDiagError(FirstTemplate->getLocation(),
11005 FirstTemplate->getSourceRange(),
11006 FunctionTemplateParameterDifferentType)
11007 << FirstTemplate << (i + 1);
11008 ODRDiagNote(SecondTemplate->getLocation(),
11009 SecondTemplate->getSourceRange(),
11010 FunctionTemplateParameterDifferentType)
11011 << SecondTemplate << (i + 1);
11012 ParameterMismatch = true;
11013 break;
11014 }
11015
11016 bool HasFirstDefaultArgument =
11017 FirstTTPD->hasDefaultArgument() &&
11018 !FirstTTPD->defaultArgumentWasInherited();
11019 bool HasSecondDefaultArgument =
11020 SecondTTPD->hasDefaultArgument() &&
11021 !SecondTTPD->defaultArgumentWasInherited();
11022 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11023 ODRDiagError(FirstTemplate->getLocation(),
11024 FirstTemplate->getSourceRange(),
11025 FunctionTemplateParameterSingleDefaultArgument)
11026 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11027 ODRDiagNote(SecondTemplate->getLocation(),
11028 SecondTemplate->getSourceRange(),
11029 FunctionTemplateParameterSingleDefaultArgument)
11030 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11031 ParameterMismatch = true;
11032 break;
11033 }
11034
11035 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11036 TemplateArgument FirstTA =
11037 FirstTTPD->getDefaultArgument().getArgument();
11038 TemplateArgument SecondTA =
11039 SecondTTPD->getDefaultArgument().getArgument();
11040 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11041 ComputeTemplateArgumentODRHash(SecondTA)) {
11042 ODRDiagError(FirstTemplate->getLocation(),
11043 FirstTemplate->getSourceRange(),
11044 FunctionTemplateParameterDifferentDefaultArgument)
11045 << FirstTemplate << (i + 1) << FirstTA;
11046 ODRDiagNote(SecondTemplate->getLocation(),
11047 SecondTemplate->getSourceRange(),
11048 FunctionTemplateParameterDifferentDefaultArgument)
11049 << SecondTemplate << (i + 1) << SecondTA;
11050 ParameterMismatch = true;
11051 break;
11052 }
11053 }
11054
11055 if (FirstTTPD->isParameterPack() !=
11056 SecondTTPD->isParameterPack()) {
11057 ODRDiagError(FirstTemplate->getLocation(),
11058 FirstTemplate->getSourceRange(),
11059 FunctionTemplatePackParameter)
11060 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11061 ODRDiagNote(SecondTemplate->getLocation(),
11062 SecondTemplate->getSourceRange(),
11063 FunctionTemplatePackParameter)
11064 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11065 ParameterMismatch = true;
11066 break;
11067 }
11068 }
11069
11070 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11071 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11072 NonTypeTemplateParmDecl *FirstNTTPD =
11073 cast<NonTypeTemplateParmDecl>(FirstParam);
11074 NonTypeTemplateParmDecl *SecondNTTPD =
11075 cast<NonTypeTemplateParmDecl>(SecondParam);
11076
11077 QualType FirstType = FirstNTTPD->getType();
11078 QualType SecondType = SecondNTTPD->getType();
11079 if (ComputeQualTypeODRHash(FirstType) !=
11080 ComputeQualTypeODRHash(SecondType)) {
11081 ODRDiagError(FirstTemplate->getLocation(),
11082 FirstTemplate->getSourceRange(),
11083 FunctionTemplateParameterDifferentType)
11084 << FirstTemplate << (i + 1);
11085 ODRDiagNote(SecondTemplate->getLocation(),
11086 SecondTemplate->getSourceRange(),
11087 FunctionTemplateParameterDifferentType)
11088 << SecondTemplate << (i + 1);
11089 ParameterMismatch = true;
11090 break;
11091 }
11092
11093 bool HasFirstDefaultArgument =
11094 FirstNTTPD->hasDefaultArgument() &&
11095 !FirstNTTPD->defaultArgumentWasInherited();
11096 bool HasSecondDefaultArgument =
11097 SecondNTTPD->hasDefaultArgument() &&
11098 !SecondNTTPD->defaultArgumentWasInherited();
11099 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11100 ODRDiagError(FirstTemplate->getLocation(),
11101 FirstTemplate->getSourceRange(),
11102 FunctionTemplateParameterSingleDefaultArgument)
11103 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11104 ODRDiagNote(SecondTemplate->getLocation(),
11105 SecondTemplate->getSourceRange(),
11106 FunctionTemplateParameterSingleDefaultArgument)
11107 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11108 ParameterMismatch = true;
11109 break;
11110 }
11111
11112 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11113 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11114 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11115 if (ComputeODRHash(FirstDefaultArgument) !=
11116 ComputeODRHash(SecondDefaultArgument)) {
11117 ODRDiagError(FirstTemplate->getLocation(),
11118 FirstTemplate->getSourceRange(),
11119 FunctionTemplateParameterDifferentDefaultArgument)
11120 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11121 ODRDiagNote(SecondTemplate->getLocation(),
11122 SecondTemplate->getSourceRange(),
11123 FunctionTemplateParameterDifferentDefaultArgument)
11124 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11125 ParameterMismatch = true;
11126 break;
11127 }
11128 }
11129
11130 if (FirstNTTPD->isParameterPack() !=
11131 SecondNTTPD->isParameterPack()) {
11132 ODRDiagError(FirstTemplate->getLocation(),
11133 FirstTemplate->getSourceRange(),
11134 FunctionTemplatePackParameter)
11135 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11136 ODRDiagNote(SecondTemplate->getLocation(),
11137 SecondTemplate->getSourceRange(),
11138 FunctionTemplatePackParameter)
11139 << SecondTemplate << (i + 1)
11140 << SecondNTTPD->isParameterPack();
11141 ParameterMismatch = true;
11142 break;
11143 }
11144 }
11145 }
11146
11147 if (ParameterMismatch) {
11148 Diagnosed = true;
11149 break;
11150 }
11151
11152 break;
11153 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011154 }
11155
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011156 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011157 continue;
11158
Richard Trieu708859a2017-06-08 00:56:21 +000011159 Diag(FirstDecl->getLocation(),
11160 diag::err_module_odr_violation_mismatch_decl_unknown)
11161 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11162 << FirstDecl->getSourceRange();
11163 Diag(SecondDecl->getLocation(),
11164 diag::note_module_odr_violation_mismatch_decl_unknown)
11165 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011166 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011167 }
11168
11169 if (!Diagnosed) {
11170 // All definitions are updates to the same declaration. This happens if a
11171 // module instantiates the declaration of a class template specialization
11172 // and two or more other modules instantiate its definition.
11173 //
11174 // FIXME: Indicate which modules had instantiations of this definition.
11175 // FIXME: How can this even happen?
11176 Diag(Merge.first->getLocation(),
11177 diag::err_module_odr_violation_different_instantiations)
11178 << Merge.first;
11179 }
11180 }
Richard Trieue6caa262017-12-23 00:41:01 +000011181
11182 // Issue ODR failures diagnostics for functions.
11183 for (auto &Merge : FunctionOdrMergeFailures) {
11184 enum ODRFunctionDifference {
11185 ReturnType,
11186 ParameterName,
11187 ParameterType,
11188 ParameterSingleDefaultArgument,
11189 ParameterDifferentDefaultArgument,
11190 FunctionBody,
11191 };
11192
11193 FunctionDecl *FirstFunction = Merge.first;
11194 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11195
11196 bool Diagnosed = false;
11197 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011198
Richard Trieue6caa262017-12-23 00:41:01 +000011199 if (FirstFunction == SecondFunction)
11200 continue;
11201
11202 std::string SecondModule =
11203 getOwningModuleNameForDiagnostic(SecondFunction);
11204
11205 auto ODRDiagError = [FirstFunction, &FirstModule,
11206 this](SourceLocation Loc, SourceRange Range,
11207 ODRFunctionDifference DiffType) {
11208 return Diag(Loc, diag::err_module_odr_violation_function)
11209 << FirstFunction << FirstModule.empty() << FirstModule << Range
11210 << DiffType;
11211 };
11212 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11213 SourceRange Range,
11214 ODRFunctionDifference DiffType) {
11215 return Diag(Loc, diag::note_module_odr_violation_function)
11216 << SecondModule << Range << DiffType;
11217 };
11218
11219 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11220 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11221 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11222 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11223 << FirstFunction->getReturnType();
11224 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11225 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11226 << SecondFunction->getReturnType();
11227 Diagnosed = true;
11228 break;
11229 }
11230
11231 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11232 "Merged functions with different number of parameters");
11233
11234 auto ParamSize = FirstFunction->param_size();
11235 bool ParameterMismatch = false;
11236 for (unsigned I = 0; I < ParamSize; ++I) {
11237 auto *FirstParam = FirstFunction->getParamDecl(I);
11238 auto *SecondParam = SecondFunction->getParamDecl(I);
11239
11240 assert(getContext().hasSameType(FirstParam->getType(),
11241 SecondParam->getType()) &&
11242 "Merged function has different parameter types.");
11243
11244 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11245 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11246 ParameterName)
11247 << I + 1 << FirstParam->getDeclName();
11248 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11249 ParameterName)
11250 << I + 1 << SecondParam->getDeclName();
11251 ParameterMismatch = true;
11252 break;
11253 };
11254
11255 QualType FirstParamType = FirstParam->getType();
11256 QualType SecondParamType = SecondParam->getType();
11257 if (FirstParamType != SecondParamType &&
11258 ComputeQualTypeODRHash(FirstParamType) !=
11259 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011260 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011261 FirstParamType->getAs<DecayedType>()) {
11262 ODRDiagError(FirstParam->getLocation(),
11263 FirstParam->getSourceRange(), ParameterType)
11264 << (I + 1) << FirstParamType << true
11265 << ParamDecayedType->getOriginalType();
11266 } else {
11267 ODRDiagError(FirstParam->getLocation(),
11268 FirstParam->getSourceRange(), ParameterType)
11269 << (I + 1) << FirstParamType << false;
11270 }
11271
Vedant Kumar48b4f762018-04-14 01:40:48 +000011272 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011273 SecondParamType->getAs<DecayedType>()) {
11274 ODRDiagNote(SecondParam->getLocation(),
11275 SecondParam->getSourceRange(), ParameterType)
11276 << (I + 1) << SecondParamType << true
11277 << ParamDecayedType->getOriginalType();
11278 } else {
11279 ODRDiagNote(SecondParam->getLocation(),
11280 SecondParam->getSourceRange(), ParameterType)
11281 << (I + 1) << SecondParamType << false;
11282 }
11283 ParameterMismatch = true;
11284 break;
11285 }
11286
11287 const Expr *FirstInit = FirstParam->getInit();
11288 const Expr *SecondInit = SecondParam->getInit();
11289 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11290 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11291 ParameterSingleDefaultArgument)
11292 << (I + 1) << (FirstInit == nullptr)
11293 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11294 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11295 ParameterSingleDefaultArgument)
11296 << (I + 1) << (SecondInit == nullptr)
11297 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11298 ParameterMismatch = true;
11299 break;
11300 }
11301
11302 if (FirstInit && SecondInit &&
11303 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11304 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11305 ParameterDifferentDefaultArgument)
11306 << (I + 1) << FirstInit->getSourceRange();
11307 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11308 ParameterDifferentDefaultArgument)
11309 << (I + 1) << SecondInit->getSourceRange();
11310 ParameterMismatch = true;
11311 break;
11312 }
11313
11314 assert(ComputeSubDeclODRHash(FirstParam) ==
11315 ComputeSubDeclODRHash(SecondParam) &&
11316 "Undiagnosed parameter difference.");
11317 }
11318
11319 if (ParameterMismatch) {
11320 Diagnosed = true;
11321 break;
11322 }
11323
11324 // If no error has been generated before now, assume the problem is in
11325 // the body and generate a message.
11326 ODRDiagError(FirstFunction->getLocation(),
11327 FirstFunction->getSourceRange(), FunctionBody);
11328 ODRDiagNote(SecondFunction->getLocation(),
11329 SecondFunction->getSourceRange(), FunctionBody);
11330 Diagnosed = true;
11331 break;
11332 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011333 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011334 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11335 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011336
11337 // Issue ODR failures diagnostics for enums.
11338 for (auto &Merge : EnumOdrMergeFailures) {
11339 enum ODREnumDifference {
11340 SingleScopedEnum,
11341 EnumTagKeywordMismatch,
11342 SingleSpecifiedType,
11343 DifferentSpecifiedTypes,
11344 DifferentNumberEnumConstants,
11345 EnumConstantName,
11346 EnumConstantSingleInitilizer,
11347 EnumConstantDifferentInitilizer,
11348 };
11349
11350 // If we've already pointed out a specific problem with this enum, don't
11351 // bother issuing a general "something's different" diagnostic.
11352 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11353 continue;
11354
11355 EnumDecl *FirstEnum = Merge.first;
11356 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11357
11358 using DeclHashes =
11359 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11360 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11361 DeclHashes &Hashes, EnumDecl *Enum) {
11362 for (auto *D : Enum->decls()) {
11363 // Due to decl merging, the first EnumDecl is the parent of
11364 // Decls in both records.
11365 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11366 continue;
11367 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11368 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11369 ComputeSubDeclODRHash(D));
11370 }
11371 };
11372 DeclHashes FirstHashes;
11373 PopulateHashes(FirstHashes, FirstEnum);
11374 bool Diagnosed = false;
11375 for (auto &SecondEnum : Merge.second) {
11376
11377 if (FirstEnum == SecondEnum)
11378 continue;
11379
11380 std::string SecondModule =
11381 getOwningModuleNameForDiagnostic(SecondEnum);
11382
11383 auto ODRDiagError = [FirstEnum, &FirstModule,
11384 this](SourceLocation Loc, SourceRange Range,
11385 ODREnumDifference DiffType) {
11386 return Diag(Loc, diag::err_module_odr_violation_enum)
11387 << FirstEnum << FirstModule.empty() << FirstModule << Range
11388 << DiffType;
11389 };
11390 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11391 SourceRange Range,
11392 ODREnumDifference DiffType) {
11393 return Diag(Loc, diag::note_module_odr_violation_enum)
11394 << SecondModule << Range << DiffType;
11395 };
11396
11397 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11398 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11399 SingleScopedEnum)
11400 << FirstEnum->isScoped();
11401 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11402 SingleScopedEnum)
11403 << SecondEnum->isScoped();
11404 Diagnosed = true;
11405 continue;
11406 }
11407
11408 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11409 if (FirstEnum->isScopedUsingClassTag() !=
11410 SecondEnum->isScopedUsingClassTag()) {
11411 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11412 EnumTagKeywordMismatch)
11413 << FirstEnum->isScopedUsingClassTag();
11414 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11415 EnumTagKeywordMismatch)
11416 << SecondEnum->isScopedUsingClassTag();
11417 Diagnosed = true;
11418 continue;
11419 }
11420 }
11421
11422 QualType FirstUnderlyingType =
11423 FirstEnum->getIntegerTypeSourceInfo()
11424 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11425 : QualType();
11426 QualType SecondUnderlyingType =
11427 SecondEnum->getIntegerTypeSourceInfo()
11428 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11429 : QualType();
11430 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11431 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11432 SingleSpecifiedType)
11433 << !FirstUnderlyingType.isNull();
11434 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11435 SingleSpecifiedType)
11436 << !SecondUnderlyingType.isNull();
11437 Diagnosed = true;
11438 continue;
11439 }
11440
11441 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11442 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11443 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11444 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11445 DifferentSpecifiedTypes)
11446 << FirstUnderlyingType;
11447 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11448 DifferentSpecifiedTypes)
11449 << SecondUnderlyingType;
11450 Diagnosed = true;
11451 continue;
11452 }
11453 }
11454
11455 DeclHashes SecondHashes;
11456 PopulateHashes(SecondHashes, SecondEnum);
11457
11458 if (FirstHashes.size() != SecondHashes.size()) {
11459 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11460 DifferentNumberEnumConstants)
11461 << (int)FirstHashes.size();
11462 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11463 DifferentNumberEnumConstants)
11464 << (int)SecondHashes.size();
11465 Diagnosed = true;
11466 continue;
11467 }
11468
11469 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11470 if (FirstHashes[I].second == SecondHashes[I].second)
11471 continue;
11472 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11473 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11474
11475 if (FirstEnumConstant->getDeclName() !=
11476 SecondEnumConstant->getDeclName()) {
11477
11478 ODRDiagError(FirstEnumConstant->getLocation(),
11479 FirstEnumConstant->getSourceRange(), EnumConstantName)
11480 << I + 1 << FirstEnumConstant;
11481 ODRDiagNote(SecondEnumConstant->getLocation(),
11482 SecondEnumConstant->getSourceRange(), EnumConstantName)
11483 << I + 1 << SecondEnumConstant;
11484 Diagnosed = true;
11485 break;
11486 }
11487
11488 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11489 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11490 if (!FirstInit && !SecondInit)
11491 continue;
11492
11493 if (!FirstInit || !SecondInit) {
11494 ODRDiagError(FirstEnumConstant->getLocation(),
11495 FirstEnumConstant->getSourceRange(),
11496 EnumConstantSingleInitilizer)
11497 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11498 ODRDiagNote(SecondEnumConstant->getLocation(),
11499 SecondEnumConstant->getSourceRange(),
11500 EnumConstantSingleInitilizer)
11501 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11502 Diagnosed = true;
11503 break;
11504 }
11505
11506 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11507 ODRDiagError(FirstEnumConstant->getLocation(),
11508 FirstEnumConstant->getSourceRange(),
11509 EnumConstantDifferentInitilizer)
11510 << I + 1 << FirstEnumConstant;
11511 ODRDiagNote(SecondEnumConstant->getLocation(),
11512 SecondEnumConstant->getSourceRange(),
11513 EnumConstantDifferentInitilizer)
11514 << I + 1 << SecondEnumConstant;
11515 Diagnosed = true;
11516 break;
11517 }
11518 }
11519 }
11520
11521 (void)Diagnosed;
11522 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11523 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011524}
11525
Richard Smithce18a182015-07-14 00:26:00 +000011526void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011527 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011528 ReadTimer->startTimer();
11529}
11530
Guy Benyei11169dd2012-12-18 14:30:41 +000011531void ASTReader::FinishedDeserializing() {
11532 assert(NumCurrentElementsDeserializing &&
11533 "FinishedDeserializing not paired with StartedDeserializing");
11534 if (NumCurrentElementsDeserializing == 1) {
11535 // We decrease NumCurrentElementsDeserializing only after pending actions
11536 // are finished, to avoid recursively re-calling finishPendingActions().
11537 finishPendingActions();
11538 }
11539 --NumCurrentElementsDeserializing;
11540
Richard Smitha0ce9c42014-07-29 23:23:27 +000011541 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011542 // Propagate exception specification and deduced type updates along
11543 // redeclaration chains.
11544 //
11545 // We do this now rather than in finishPendingActions because we want to
11546 // be able to walk the complete redeclaration chains of the updated decls.
11547 while (!PendingExceptionSpecUpdates.empty() ||
11548 !PendingDeducedTypeUpdates.empty()) {
11549 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011550 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011551 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011552 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011553 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011554 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011555 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011556 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011557 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011558 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011559 }
Richard Smitha62d1982018-08-03 01:00:01 +000011560
11561 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11562 PendingDeducedTypeUpdates.clear();
11563 for (auto Update : DTUpdates) {
11564 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11565 // FIXME: If the return type is already deduced, check that it matches.
11566 getContext().adjustDeducedFunctionResultType(Update.first,
11567 Update.second);
11568 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011569 }
11570
Richard Smithce18a182015-07-14 00:26:00 +000011571 if (ReadTimer)
11572 ReadTimer->stopTimer();
11573
Richard Smith0f4e2c42015-08-06 04:23:48 +000011574 diagnoseOdrViolations();
11575
Richard Smith04d05b52014-03-23 00:27:18 +000011576 // We are not in recursive loading, so it's safe to pass the "interesting"
11577 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011578 if (Consumer)
11579 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011580 }
11581}
11582
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011583void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011584 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11585 // Remove any fake results before adding any real ones.
11586 auto It = PendingFakeLookupResults.find(II);
11587 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011588 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011589 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011590 // FIXME: this works around module+PCH performance issue.
11591 // Rather than erase the result from the map, which is O(n), just clear
11592 // the vector of NamedDecls.
11593 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011594 }
11595 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011596
11597 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11598 SemaObj->TUScope->AddDecl(D);
11599 } else if (SemaObj->TUScope) {
11600 // Adding the decl to IdResolver may have failed because it was already in
11601 // (even though it was not added in scope). If it is already in, make sure
11602 // it gets in the scope as well.
11603 if (std::find(SemaObj->IdResolver.begin(Name),
11604 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11605 SemaObj->TUScope->AddDecl(D);
11606 }
11607}
11608
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011609ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11610 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011611 const PCHContainerReader &PCHContainerRdr,
11612 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11613 StringRef isysroot, bool DisableValidation,
11614 bool AllowASTWithCompilerErrors,
11615 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11616 bool UseGlobalIndex,
11617 std::unique_ptr<llvm::Timer> ReadTimer)
11618 : Listener(DisableValidation
11619 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11620 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011621 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011622 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011623 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11624 PCHContainerRdr, PP.getHeaderSearchInfo()),
11625 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011626 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011627 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11628 AllowConfigurationMismatch(AllowConfigurationMismatch),
11629 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011630 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011631 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011632
11633 for (const auto &Ext : Extensions) {
11634 auto BlockName = Ext->getExtensionMetadata().BlockName;
11635 auto Known = ModuleFileExtensions.find(BlockName);
11636 if (Known != ModuleFileExtensions.end()) {
11637 Diags.Report(diag::warn_duplicate_module_file_extension)
11638 << BlockName;
11639 continue;
11640 }
11641
11642 ModuleFileExtensions.insert({BlockName, Ext});
11643 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011644}
11645
11646ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011647 if (OwnsDeserializationListener)
11648 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011649}
Richard Smith10379092016-05-06 23:14:07 +000011650
11651IdentifierResolver &ASTReader::getIdResolver() {
11652 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11653}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011654
11655unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11656 unsigned AbbrevID) {
11657 Idx = 0;
11658 Record.clear();
11659 return Cursor.readRecord(AbbrevID, Record);
11660}
Kelvin Libe286f52018-09-15 13:54:15 +000011661//===----------------------------------------------------------------------===//
11662//// OMPClauseReader implementation
11663////===----------------------------------------------------------------------===//
11664
11665OMPClause *OMPClauseReader::readClause() {
11666 OMPClause *C;
11667 switch (Record.readInt()) {
11668 case OMPC_if:
11669 C = new (Context) OMPIfClause();
11670 break;
11671 case OMPC_final:
11672 C = new (Context) OMPFinalClause();
11673 break;
11674 case OMPC_num_threads:
11675 C = new (Context) OMPNumThreadsClause();
11676 break;
11677 case OMPC_safelen:
11678 C = new (Context) OMPSafelenClause();
11679 break;
11680 case OMPC_simdlen:
11681 C = new (Context) OMPSimdlenClause();
11682 break;
11683 case OMPC_collapse:
11684 C = new (Context) OMPCollapseClause();
11685 break;
11686 case OMPC_default:
11687 C = new (Context) OMPDefaultClause();
11688 break;
11689 case OMPC_proc_bind:
11690 C = new (Context) OMPProcBindClause();
11691 break;
11692 case OMPC_schedule:
11693 C = new (Context) OMPScheduleClause();
11694 break;
11695 case OMPC_ordered:
11696 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11697 break;
11698 case OMPC_nowait:
11699 C = new (Context) OMPNowaitClause();
11700 break;
11701 case OMPC_untied:
11702 C = new (Context) OMPUntiedClause();
11703 break;
11704 case OMPC_mergeable:
11705 C = new (Context) OMPMergeableClause();
11706 break;
11707 case OMPC_read:
11708 C = new (Context) OMPReadClause();
11709 break;
11710 case OMPC_write:
11711 C = new (Context) OMPWriteClause();
11712 break;
11713 case OMPC_update:
11714 C = new (Context) OMPUpdateClause();
11715 break;
11716 case OMPC_capture:
11717 C = new (Context) OMPCaptureClause();
11718 break;
11719 case OMPC_seq_cst:
11720 C = new (Context) OMPSeqCstClause();
11721 break;
11722 case OMPC_threads:
11723 C = new (Context) OMPThreadsClause();
11724 break;
11725 case OMPC_simd:
11726 C = new (Context) OMPSIMDClause();
11727 break;
11728 case OMPC_nogroup:
11729 C = new (Context) OMPNogroupClause();
11730 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011731 case OMPC_unified_address:
11732 C = new (Context) OMPUnifiedAddressClause();
11733 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011734 case OMPC_unified_shared_memory:
11735 C = new (Context) OMPUnifiedSharedMemoryClause();
11736 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011737 case OMPC_reverse_offload:
11738 C = new (Context) OMPReverseOffloadClause();
11739 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011740 case OMPC_dynamic_allocators:
11741 C = new (Context) OMPDynamicAllocatorsClause();
11742 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011743 case OMPC_atomic_default_mem_order:
11744 C = new (Context) OMPAtomicDefaultMemOrderClause();
11745 break;
11746 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011747 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11748 break;
11749 case OMPC_firstprivate:
11750 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11751 break;
11752 case OMPC_lastprivate:
11753 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11754 break;
11755 case OMPC_shared:
11756 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11757 break;
11758 case OMPC_reduction:
11759 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11760 break;
11761 case OMPC_task_reduction:
11762 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11763 break;
11764 case OMPC_in_reduction:
11765 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11766 break;
11767 case OMPC_linear:
11768 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11769 break;
11770 case OMPC_aligned:
11771 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11772 break;
11773 case OMPC_copyin:
11774 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11775 break;
11776 case OMPC_copyprivate:
11777 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11778 break;
11779 case OMPC_flush:
11780 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11781 break;
11782 case OMPC_depend: {
11783 unsigned NumVars = Record.readInt();
11784 unsigned NumLoops = Record.readInt();
11785 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11786 break;
11787 }
11788 case OMPC_device:
11789 C = new (Context) OMPDeviceClause();
11790 break;
11791 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011792 OMPMappableExprListSizeTy Sizes;
11793 Sizes.NumVars = Record.readInt();
11794 Sizes.NumUniqueDeclarations = Record.readInt();
11795 Sizes.NumComponentLists = Record.readInt();
11796 Sizes.NumComponents = Record.readInt();
11797 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011798 break;
11799 }
11800 case OMPC_num_teams:
11801 C = new (Context) OMPNumTeamsClause();
11802 break;
11803 case OMPC_thread_limit:
11804 C = new (Context) OMPThreadLimitClause();
11805 break;
11806 case OMPC_priority:
11807 C = new (Context) OMPPriorityClause();
11808 break;
11809 case OMPC_grainsize:
11810 C = new (Context) OMPGrainsizeClause();
11811 break;
11812 case OMPC_num_tasks:
11813 C = new (Context) OMPNumTasksClause();
11814 break;
11815 case OMPC_hint:
11816 C = new (Context) OMPHintClause();
11817 break;
11818 case OMPC_dist_schedule:
11819 C = new (Context) OMPDistScheduleClause();
11820 break;
11821 case OMPC_defaultmap:
11822 C = new (Context) OMPDefaultmapClause();
11823 break;
11824 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011825 OMPMappableExprListSizeTy Sizes;
11826 Sizes.NumVars = Record.readInt();
11827 Sizes.NumUniqueDeclarations = Record.readInt();
11828 Sizes.NumComponentLists = Record.readInt();
11829 Sizes.NumComponents = Record.readInt();
11830 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011831 break;
11832 }
11833 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011834 OMPMappableExprListSizeTy Sizes;
11835 Sizes.NumVars = Record.readInt();
11836 Sizes.NumUniqueDeclarations = Record.readInt();
11837 Sizes.NumComponentLists = Record.readInt();
11838 Sizes.NumComponents = Record.readInt();
11839 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011840 break;
11841 }
11842 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011843 OMPMappableExprListSizeTy Sizes;
11844 Sizes.NumVars = Record.readInt();
11845 Sizes.NumUniqueDeclarations = Record.readInt();
11846 Sizes.NumComponentLists = Record.readInt();
11847 Sizes.NumComponents = Record.readInt();
11848 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011849 break;
11850 }
11851 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011852 OMPMappableExprListSizeTy Sizes;
11853 Sizes.NumVars = Record.readInt();
11854 Sizes.NumUniqueDeclarations = Record.readInt();
11855 Sizes.NumComponentLists = Record.readInt();
11856 Sizes.NumComponents = Record.readInt();
11857 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011858 break;
11859 }
11860 }
11861 Visit(C);
11862 C->setLocStart(Record.readSourceLocation());
11863 C->setLocEnd(Record.readSourceLocation());
11864
11865 return C;
11866}
11867
11868void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11869 C->setPreInitStmt(Record.readSubStmt(),
11870 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11871}
11872
11873void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11874 VisitOMPClauseWithPreInit(C);
11875 C->setPostUpdateExpr(Record.readSubExpr());
11876}
11877
11878void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11879 VisitOMPClauseWithPreInit(C);
11880 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11881 C->setNameModifierLoc(Record.readSourceLocation());
11882 C->setColonLoc(Record.readSourceLocation());
11883 C->setCondition(Record.readSubExpr());
11884 C->setLParenLoc(Record.readSourceLocation());
11885}
11886
11887void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11888 C->setCondition(Record.readSubExpr());
11889 C->setLParenLoc(Record.readSourceLocation());
11890}
11891
11892void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11893 VisitOMPClauseWithPreInit(C);
11894 C->setNumThreads(Record.readSubExpr());
11895 C->setLParenLoc(Record.readSourceLocation());
11896}
11897
11898void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11899 C->setSafelen(Record.readSubExpr());
11900 C->setLParenLoc(Record.readSourceLocation());
11901}
11902
11903void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11904 C->setSimdlen(Record.readSubExpr());
11905 C->setLParenLoc(Record.readSourceLocation());
11906}
11907
11908void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11909 C->setNumForLoops(Record.readSubExpr());
11910 C->setLParenLoc(Record.readSourceLocation());
11911}
11912
11913void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11914 C->setDefaultKind(
11915 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11916 C->setLParenLoc(Record.readSourceLocation());
11917 C->setDefaultKindKwLoc(Record.readSourceLocation());
11918}
11919
11920void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11921 C->setProcBindKind(
11922 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
11923 C->setLParenLoc(Record.readSourceLocation());
11924 C->setProcBindKindKwLoc(Record.readSourceLocation());
11925}
11926
11927void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11928 VisitOMPClauseWithPreInit(C);
11929 C->setScheduleKind(
11930 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11931 C->setFirstScheduleModifier(
11932 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11933 C->setSecondScheduleModifier(
11934 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11935 C->setChunkSize(Record.readSubExpr());
11936 C->setLParenLoc(Record.readSourceLocation());
11937 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11938 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11939 C->setScheduleKindLoc(Record.readSourceLocation());
11940 C->setCommaLoc(Record.readSourceLocation());
11941}
11942
11943void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11944 C->setNumForLoops(Record.readSubExpr());
11945 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11946 C->setLoopNumIterations(I, Record.readSubExpr());
11947 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11948 C->setLoopCounter(I, Record.readSubExpr());
11949 C->setLParenLoc(Record.readSourceLocation());
11950}
11951
11952void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11953
11954void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11955
11956void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11957
11958void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11959
11960void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11961
11962void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11963
11964void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11965
11966void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11967
11968void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11969
11970void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11971
11972void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11973
Kelvin Li1408f912018-09-26 04:28:39 +000011974void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11975
Patrick Lyster4a370b92018-10-01 13:47:43 +000011976void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11977 OMPUnifiedSharedMemoryClause *) {}
11978
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011979void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11980
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011981void
11982OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11983}
11984
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011985void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11986 OMPAtomicDefaultMemOrderClause *C) {
11987 C->setAtomicDefaultMemOrderKind(
11988 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11989 C->setLParenLoc(Record.readSourceLocation());
11990 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11991}
11992
Kelvin Libe286f52018-09-15 13:54:15 +000011993void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11994 C->setLParenLoc(Record.readSourceLocation());
11995 unsigned NumVars = C->varlist_size();
11996 SmallVector<Expr *, 16> Vars;
11997 Vars.reserve(NumVars);
11998 for (unsigned i = 0; i != NumVars; ++i)
11999 Vars.push_back(Record.readSubExpr());
12000 C->setVarRefs(Vars);
12001 Vars.clear();
12002 for (unsigned i = 0; i != NumVars; ++i)
12003 Vars.push_back(Record.readSubExpr());
12004 C->setPrivateCopies(Vars);
12005}
12006
12007void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12008 VisitOMPClauseWithPreInit(C);
12009 C->setLParenLoc(Record.readSourceLocation());
12010 unsigned NumVars = C->varlist_size();
12011 SmallVector<Expr *, 16> Vars;
12012 Vars.reserve(NumVars);
12013 for (unsigned i = 0; i != NumVars; ++i)
12014 Vars.push_back(Record.readSubExpr());
12015 C->setVarRefs(Vars);
12016 Vars.clear();
12017 for (unsigned i = 0; i != NumVars; ++i)
12018 Vars.push_back(Record.readSubExpr());
12019 C->setPrivateCopies(Vars);
12020 Vars.clear();
12021 for (unsigned i = 0; i != NumVars; ++i)
12022 Vars.push_back(Record.readSubExpr());
12023 C->setInits(Vars);
12024}
12025
12026void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12027 VisitOMPClauseWithPostUpdate(C);
12028 C->setLParenLoc(Record.readSourceLocation());
12029 unsigned NumVars = C->varlist_size();
12030 SmallVector<Expr *, 16> Vars;
12031 Vars.reserve(NumVars);
12032 for (unsigned i = 0; i != NumVars; ++i)
12033 Vars.push_back(Record.readSubExpr());
12034 C->setVarRefs(Vars);
12035 Vars.clear();
12036 for (unsigned i = 0; i != NumVars; ++i)
12037 Vars.push_back(Record.readSubExpr());
12038 C->setPrivateCopies(Vars);
12039 Vars.clear();
12040 for (unsigned i = 0; i != NumVars; ++i)
12041 Vars.push_back(Record.readSubExpr());
12042 C->setSourceExprs(Vars);
12043 Vars.clear();
12044 for (unsigned i = 0; i != NumVars; ++i)
12045 Vars.push_back(Record.readSubExpr());
12046 C->setDestinationExprs(Vars);
12047 Vars.clear();
12048 for (unsigned i = 0; i != NumVars; ++i)
12049 Vars.push_back(Record.readSubExpr());
12050 C->setAssignmentOps(Vars);
12051}
12052
12053void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12054 C->setLParenLoc(Record.readSourceLocation());
12055 unsigned NumVars = C->varlist_size();
12056 SmallVector<Expr *, 16> Vars;
12057 Vars.reserve(NumVars);
12058 for (unsigned i = 0; i != NumVars; ++i)
12059 Vars.push_back(Record.readSubExpr());
12060 C->setVarRefs(Vars);
12061}
12062
12063void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12064 VisitOMPClauseWithPostUpdate(C);
12065 C->setLParenLoc(Record.readSourceLocation());
12066 C->setColonLoc(Record.readSourceLocation());
12067 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12068 DeclarationNameInfo DNI;
12069 Record.readDeclarationNameInfo(DNI);
12070 C->setQualifierLoc(NNSL);
12071 C->setNameInfo(DNI);
12072
12073 unsigned NumVars = C->varlist_size();
12074 SmallVector<Expr *, 16> Vars;
12075 Vars.reserve(NumVars);
12076 for (unsigned i = 0; i != NumVars; ++i)
12077 Vars.push_back(Record.readSubExpr());
12078 C->setVarRefs(Vars);
12079 Vars.clear();
12080 for (unsigned i = 0; i != NumVars; ++i)
12081 Vars.push_back(Record.readSubExpr());
12082 C->setPrivates(Vars);
12083 Vars.clear();
12084 for (unsigned i = 0; i != NumVars; ++i)
12085 Vars.push_back(Record.readSubExpr());
12086 C->setLHSExprs(Vars);
12087 Vars.clear();
12088 for (unsigned i = 0; i != NumVars; ++i)
12089 Vars.push_back(Record.readSubExpr());
12090 C->setRHSExprs(Vars);
12091 Vars.clear();
12092 for (unsigned i = 0; i != NumVars; ++i)
12093 Vars.push_back(Record.readSubExpr());
12094 C->setReductionOps(Vars);
12095}
12096
12097void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12098 VisitOMPClauseWithPostUpdate(C);
12099 C->setLParenLoc(Record.readSourceLocation());
12100 C->setColonLoc(Record.readSourceLocation());
12101 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12102 DeclarationNameInfo DNI;
12103 Record.readDeclarationNameInfo(DNI);
12104 C->setQualifierLoc(NNSL);
12105 C->setNameInfo(DNI);
12106
12107 unsigned NumVars = C->varlist_size();
12108 SmallVector<Expr *, 16> Vars;
12109 Vars.reserve(NumVars);
12110 for (unsigned I = 0; I != NumVars; ++I)
12111 Vars.push_back(Record.readSubExpr());
12112 C->setVarRefs(Vars);
12113 Vars.clear();
12114 for (unsigned I = 0; I != NumVars; ++I)
12115 Vars.push_back(Record.readSubExpr());
12116 C->setPrivates(Vars);
12117 Vars.clear();
12118 for (unsigned I = 0; I != NumVars; ++I)
12119 Vars.push_back(Record.readSubExpr());
12120 C->setLHSExprs(Vars);
12121 Vars.clear();
12122 for (unsigned I = 0; I != NumVars; ++I)
12123 Vars.push_back(Record.readSubExpr());
12124 C->setRHSExprs(Vars);
12125 Vars.clear();
12126 for (unsigned I = 0; I != NumVars; ++I)
12127 Vars.push_back(Record.readSubExpr());
12128 C->setReductionOps(Vars);
12129}
12130
12131void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12132 VisitOMPClauseWithPostUpdate(C);
12133 C->setLParenLoc(Record.readSourceLocation());
12134 C->setColonLoc(Record.readSourceLocation());
12135 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12136 DeclarationNameInfo DNI;
12137 Record.readDeclarationNameInfo(DNI);
12138 C->setQualifierLoc(NNSL);
12139 C->setNameInfo(DNI);
12140
12141 unsigned NumVars = C->varlist_size();
12142 SmallVector<Expr *, 16> Vars;
12143 Vars.reserve(NumVars);
12144 for (unsigned I = 0; I != NumVars; ++I)
12145 Vars.push_back(Record.readSubExpr());
12146 C->setVarRefs(Vars);
12147 Vars.clear();
12148 for (unsigned I = 0; I != NumVars; ++I)
12149 Vars.push_back(Record.readSubExpr());
12150 C->setPrivates(Vars);
12151 Vars.clear();
12152 for (unsigned I = 0; I != NumVars; ++I)
12153 Vars.push_back(Record.readSubExpr());
12154 C->setLHSExprs(Vars);
12155 Vars.clear();
12156 for (unsigned I = 0; I != NumVars; ++I)
12157 Vars.push_back(Record.readSubExpr());
12158 C->setRHSExprs(Vars);
12159 Vars.clear();
12160 for (unsigned I = 0; I != NumVars; ++I)
12161 Vars.push_back(Record.readSubExpr());
12162 C->setReductionOps(Vars);
12163 Vars.clear();
12164 for (unsigned I = 0; I != NumVars; ++I)
12165 Vars.push_back(Record.readSubExpr());
12166 C->setTaskgroupDescriptors(Vars);
12167}
12168
12169void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12170 VisitOMPClauseWithPostUpdate(C);
12171 C->setLParenLoc(Record.readSourceLocation());
12172 C->setColonLoc(Record.readSourceLocation());
12173 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12174 C->setModifierLoc(Record.readSourceLocation());
12175 unsigned NumVars = C->varlist_size();
12176 SmallVector<Expr *, 16> Vars;
12177 Vars.reserve(NumVars);
12178 for (unsigned i = 0; i != NumVars; ++i)
12179 Vars.push_back(Record.readSubExpr());
12180 C->setVarRefs(Vars);
12181 Vars.clear();
12182 for (unsigned i = 0; i != NumVars; ++i)
12183 Vars.push_back(Record.readSubExpr());
12184 C->setPrivates(Vars);
12185 Vars.clear();
12186 for (unsigned i = 0; i != NumVars; ++i)
12187 Vars.push_back(Record.readSubExpr());
12188 C->setInits(Vars);
12189 Vars.clear();
12190 for (unsigned i = 0; i != NumVars; ++i)
12191 Vars.push_back(Record.readSubExpr());
12192 C->setUpdates(Vars);
12193 Vars.clear();
12194 for (unsigned i = 0; i != NumVars; ++i)
12195 Vars.push_back(Record.readSubExpr());
12196 C->setFinals(Vars);
12197 C->setStep(Record.readSubExpr());
12198 C->setCalcStep(Record.readSubExpr());
12199}
12200
12201void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12202 C->setLParenLoc(Record.readSourceLocation());
12203 C->setColonLoc(Record.readSourceLocation());
12204 unsigned NumVars = C->varlist_size();
12205 SmallVector<Expr *, 16> Vars;
12206 Vars.reserve(NumVars);
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Vars.push_back(Record.readSubExpr());
12209 C->setVarRefs(Vars);
12210 C->setAlignment(Record.readSubExpr());
12211}
12212
12213void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12214 C->setLParenLoc(Record.readSourceLocation());
12215 unsigned NumVars = C->varlist_size();
12216 SmallVector<Expr *, 16> Exprs;
12217 Exprs.reserve(NumVars);
12218 for (unsigned i = 0; i != NumVars; ++i)
12219 Exprs.push_back(Record.readSubExpr());
12220 C->setVarRefs(Exprs);
12221 Exprs.clear();
12222 for (unsigned i = 0; i != NumVars; ++i)
12223 Exprs.push_back(Record.readSubExpr());
12224 C->setSourceExprs(Exprs);
12225 Exprs.clear();
12226 for (unsigned i = 0; i != NumVars; ++i)
12227 Exprs.push_back(Record.readSubExpr());
12228 C->setDestinationExprs(Exprs);
12229 Exprs.clear();
12230 for (unsigned i = 0; i != NumVars; ++i)
12231 Exprs.push_back(Record.readSubExpr());
12232 C->setAssignmentOps(Exprs);
12233}
12234
12235void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12236 C->setLParenLoc(Record.readSourceLocation());
12237 unsigned NumVars = C->varlist_size();
12238 SmallVector<Expr *, 16> Exprs;
12239 Exprs.reserve(NumVars);
12240 for (unsigned i = 0; i != NumVars; ++i)
12241 Exprs.push_back(Record.readSubExpr());
12242 C->setVarRefs(Exprs);
12243 Exprs.clear();
12244 for (unsigned i = 0; i != NumVars; ++i)
12245 Exprs.push_back(Record.readSubExpr());
12246 C->setSourceExprs(Exprs);
12247 Exprs.clear();
12248 for (unsigned i = 0; i != NumVars; ++i)
12249 Exprs.push_back(Record.readSubExpr());
12250 C->setDestinationExprs(Exprs);
12251 Exprs.clear();
12252 for (unsigned i = 0; i != NumVars; ++i)
12253 Exprs.push_back(Record.readSubExpr());
12254 C->setAssignmentOps(Exprs);
12255}
12256
12257void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12258 C->setLParenLoc(Record.readSourceLocation());
12259 unsigned NumVars = C->varlist_size();
12260 SmallVector<Expr *, 16> Vars;
12261 Vars.reserve(NumVars);
12262 for (unsigned i = 0; i != NumVars; ++i)
12263 Vars.push_back(Record.readSubExpr());
12264 C->setVarRefs(Vars);
12265}
12266
12267void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12268 C->setLParenLoc(Record.readSourceLocation());
12269 C->setDependencyKind(
12270 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12271 C->setDependencyLoc(Record.readSourceLocation());
12272 C->setColonLoc(Record.readSourceLocation());
12273 unsigned NumVars = C->varlist_size();
12274 SmallVector<Expr *, 16> Vars;
12275 Vars.reserve(NumVars);
12276 for (unsigned I = 0; I != NumVars; ++I)
12277 Vars.push_back(Record.readSubExpr());
12278 C->setVarRefs(Vars);
12279 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12280 C->setLoopData(I, Record.readSubExpr());
12281}
12282
12283void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12284 VisitOMPClauseWithPreInit(C);
12285 C->setDevice(Record.readSubExpr());
12286 C->setLParenLoc(Record.readSourceLocation());
12287}
12288
12289void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12290 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012291 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12292 C->setMapTypeModifier(
12293 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12294 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12295 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012296 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12297 DeclarationNameInfo DNI;
12298 Record.readDeclarationNameInfo(DNI);
12299 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012300 C->setMapType(
12301 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12302 C->setMapLoc(Record.readSourceLocation());
12303 C->setColonLoc(Record.readSourceLocation());
12304 auto NumVars = C->varlist_size();
12305 auto UniqueDecls = C->getUniqueDeclarationsNum();
12306 auto TotalLists = C->getTotalComponentListNum();
12307 auto TotalComponents = C->getTotalComponentsNum();
12308
12309 SmallVector<Expr *, 16> Vars;
12310 Vars.reserve(NumVars);
12311 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012312 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012313 C->setVarRefs(Vars);
12314
Michael Kruse4304e9d2019-02-19 16:38:20 +000012315 SmallVector<Expr *, 16> UDMappers;
12316 UDMappers.reserve(NumVars);
12317 for (unsigned I = 0; I < NumVars; ++I)
12318 UDMappers.push_back(Record.readExpr());
12319 C->setUDMapperRefs(UDMappers);
12320
Kelvin Libe286f52018-09-15 13:54:15 +000012321 SmallVector<ValueDecl *, 16> Decls;
12322 Decls.reserve(UniqueDecls);
12323 for (unsigned i = 0; i < UniqueDecls; ++i)
12324 Decls.push_back(Record.readDeclAs<ValueDecl>());
12325 C->setUniqueDecls(Decls);
12326
12327 SmallVector<unsigned, 16> ListsPerDecl;
12328 ListsPerDecl.reserve(UniqueDecls);
12329 for (unsigned i = 0; i < UniqueDecls; ++i)
12330 ListsPerDecl.push_back(Record.readInt());
12331 C->setDeclNumLists(ListsPerDecl);
12332
12333 SmallVector<unsigned, 32> ListSizes;
12334 ListSizes.reserve(TotalLists);
12335 for (unsigned i = 0; i < TotalLists; ++i)
12336 ListSizes.push_back(Record.readInt());
12337 C->setComponentListSizes(ListSizes);
12338
12339 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12340 Components.reserve(TotalComponents);
12341 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012342 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012343 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12344 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12345 AssociatedExpr, AssociatedDecl));
12346 }
12347 C->setComponents(Components, ListSizes);
12348}
12349
12350void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12351 VisitOMPClauseWithPreInit(C);
12352 C->setNumTeams(Record.readSubExpr());
12353 C->setLParenLoc(Record.readSourceLocation());
12354}
12355
12356void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12357 VisitOMPClauseWithPreInit(C);
12358 C->setThreadLimit(Record.readSubExpr());
12359 C->setLParenLoc(Record.readSourceLocation());
12360}
12361
12362void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12363 C->setPriority(Record.readSubExpr());
12364 C->setLParenLoc(Record.readSourceLocation());
12365}
12366
12367void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12368 C->setGrainsize(Record.readSubExpr());
12369 C->setLParenLoc(Record.readSourceLocation());
12370}
12371
12372void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12373 C->setNumTasks(Record.readSubExpr());
12374 C->setLParenLoc(Record.readSourceLocation());
12375}
12376
12377void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12378 C->setHint(Record.readSubExpr());
12379 C->setLParenLoc(Record.readSourceLocation());
12380}
12381
12382void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12383 VisitOMPClauseWithPreInit(C);
12384 C->setDistScheduleKind(
12385 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12386 C->setChunkSize(Record.readSubExpr());
12387 C->setLParenLoc(Record.readSourceLocation());
12388 C->setDistScheduleKindLoc(Record.readSourceLocation());
12389 C->setCommaLoc(Record.readSourceLocation());
12390}
12391
12392void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12393 C->setDefaultmapKind(
12394 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12395 C->setDefaultmapModifier(
12396 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12397 C->setLParenLoc(Record.readSourceLocation());
12398 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12399 C->setDefaultmapKindLoc(Record.readSourceLocation());
12400}
12401
12402void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12403 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012404 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12405 DeclarationNameInfo DNI;
12406 Record.readDeclarationNameInfo(DNI);
12407 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012408 auto NumVars = C->varlist_size();
12409 auto UniqueDecls = C->getUniqueDeclarationsNum();
12410 auto TotalLists = C->getTotalComponentListNum();
12411 auto TotalComponents = C->getTotalComponentsNum();
12412
12413 SmallVector<Expr *, 16> Vars;
12414 Vars.reserve(NumVars);
12415 for (unsigned i = 0; i != NumVars; ++i)
12416 Vars.push_back(Record.readSubExpr());
12417 C->setVarRefs(Vars);
12418
Michael Kruse01f670d2019-02-22 22:29:42 +000012419 SmallVector<Expr *, 16> UDMappers;
12420 UDMappers.reserve(NumVars);
12421 for (unsigned I = 0; I < NumVars; ++I)
12422 UDMappers.push_back(Record.readSubExpr());
12423 C->setUDMapperRefs(UDMappers);
12424
Kelvin Libe286f52018-09-15 13:54:15 +000012425 SmallVector<ValueDecl *, 16> Decls;
12426 Decls.reserve(UniqueDecls);
12427 for (unsigned i = 0; i < UniqueDecls; ++i)
12428 Decls.push_back(Record.readDeclAs<ValueDecl>());
12429 C->setUniqueDecls(Decls);
12430
12431 SmallVector<unsigned, 16> ListsPerDecl;
12432 ListsPerDecl.reserve(UniqueDecls);
12433 for (unsigned i = 0; i < UniqueDecls; ++i)
12434 ListsPerDecl.push_back(Record.readInt());
12435 C->setDeclNumLists(ListsPerDecl);
12436
12437 SmallVector<unsigned, 32> ListSizes;
12438 ListSizes.reserve(TotalLists);
12439 for (unsigned i = 0; i < TotalLists; ++i)
12440 ListSizes.push_back(Record.readInt());
12441 C->setComponentListSizes(ListSizes);
12442
12443 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12444 Components.reserve(TotalComponents);
12445 for (unsigned i = 0; i < TotalComponents; ++i) {
12446 Expr *AssociatedExpr = Record.readSubExpr();
12447 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12448 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12449 AssociatedExpr, AssociatedDecl));
12450 }
12451 C->setComponents(Components, ListSizes);
12452}
12453
12454void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12455 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012456 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12457 DeclarationNameInfo DNI;
12458 Record.readDeclarationNameInfo(DNI);
12459 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012460 auto NumVars = C->varlist_size();
12461 auto UniqueDecls = C->getUniqueDeclarationsNum();
12462 auto TotalLists = C->getTotalComponentListNum();
12463 auto TotalComponents = C->getTotalComponentsNum();
12464
12465 SmallVector<Expr *, 16> Vars;
12466 Vars.reserve(NumVars);
12467 for (unsigned i = 0; i != NumVars; ++i)
12468 Vars.push_back(Record.readSubExpr());
12469 C->setVarRefs(Vars);
12470
Michael Kruse0336c752019-02-25 20:34:15 +000012471 SmallVector<Expr *, 16> UDMappers;
12472 UDMappers.reserve(NumVars);
12473 for (unsigned I = 0; I < NumVars; ++I)
12474 UDMappers.push_back(Record.readSubExpr());
12475 C->setUDMapperRefs(UDMappers);
12476
Kelvin Libe286f52018-09-15 13:54:15 +000012477 SmallVector<ValueDecl *, 16> Decls;
12478 Decls.reserve(UniqueDecls);
12479 for (unsigned i = 0; i < UniqueDecls; ++i)
12480 Decls.push_back(Record.readDeclAs<ValueDecl>());
12481 C->setUniqueDecls(Decls);
12482
12483 SmallVector<unsigned, 16> ListsPerDecl;
12484 ListsPerDecl.reserve(UniqueDecls);
12485 for (unsigned i = 0; i < UniqueDecls; ++i)
12486 ListsPerDecl.push_back(Record.readInt());
12487 C->setDeclNumLists(ListsPerDecl);
12488
12489 SmallVector<unsigned, 32> ListSizes;
12490 ListSizes.reserve(TotalLists);
12491 for (unsigned i = 0; i < TotalLists; ++i)
12492 ListSizes.push_back(Record.readInt());
12493 C->setComponentListSizes(ListSizes);
12494
12495 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12496 Components.reserve(TotalComponents);
12497 for (unsigned i = 0; i < TotalComponents; ++i) {
12498 Expr *AssociatedExpr = Record.readSubExpr();
12499 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12500 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12501 AssociatedExpr, AssociatedDecl));
12502 }
12503 C->setComponents(Components, ListSizes);
12504}
12505
12506void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12507 C->setLParenLoc(Record.readSourceLocation());
12508 auto NumVars = C->varlist_size();
12509 auto UniqueDecls = C->getUniqueDeclarationsNum();
12510 auto TotalLists = C->getTotalComponentListNum();
12511 auto TotalComponents = C->getTotalComponentsNum();
12512
12513 SmallVector<Expr *, 16> Vars;
12514 Vars.reserve(NumVars);
12515 for (unsigned i = 0; i != NumVars; ++i)
12516 Vars.push_back(Record.readSubExpr());
12517 C->setVarRefs(Vars);
12518 Vars.clear();
12519 for (unsigned i = 0; i != NumVars; ++i)
12520 Vars.push_back(Record.readSubExpr());
12521 C->setPrivateCopies(Vars);
12522 Vars.clear();
12523 for (unsigned i = 0; i != NumVars; ++i)
12524 Vars.push_back(Record.readSubExpr());
12525 C->setInits(Vars);
12526
12527 SmallVector<ValueDecl *, 16> Decls;
12528 Decls.reserve(UniqueDecls);
12529 for (unsigned i = 0; i < UniqueDecls; ++i)
12530 Decls.push_back(Record.readDeclAs<ValueDecl>());
12531 C->setUniqueDecls(Decls);
12532
12533 SmallVector<unsigned, 16> ListsPerDecl;
12534 ListsPerDecl.reserve(UniqueDecls);
12535 for (unsigned i = 0; i < UniqueDecls; ++i)
12536 ListsPerDecl.push_back(Record.readInt());
12537 C->setDeclNumLists(ListsPerDecl);
12538
12539 SmallVector<unsigned, 32> ListSizes;
12540 ListSizes.reserve(TotalLists);
12541 for (unsigned i = 0; i < TotalLists; ++i)
12542 ListSizes.push_back(Record.readInt());
12543 C->setComponentListSizes(ListSizes);
12544
12545 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12546 Components.reserve(TotalComponents);
12547 for (unsigned i = 0; i < TotalComponents; ++i) {
12548 Expr *AssociatedExpr = Record.readSubExpr();
12549 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12550 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12551 AssociatedExpr, AssociatedDecl));
12552 }
12553 C->setComponents(Components, ListSizes);
12554}
12555
12556void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12557 C->setLParenLoc(Record.readSourceLocation());
12558 auto NumVars = C->varlist_size();
12559 auto UniqueDecls = C->getUniqueDeclarationsNum();
12560 auto TotalLists = C->getTotalComponentListNum();
12561 auto TotalComponents = C->getTotalComponentsNum();
12562
12563 SmallVector<Expr *, 16> Vars;
12564 Vars.reserve(NumVars);
12565 for (unsigned i = 0; i != NumVars; ++i)
12566 Vars.push_back(Record.readSubExpr());
12567 C->setVarRefs(Vars);
12568 Vars.clear();
12569
12570 SmallVector<ValueDecl *, 16> Decls;
12571 Decls.reserve(UniqueDecls);
12572 for (unsigned i = 0; i < UniqueDecls; ++i)
12573 Decls.push_back(Record.readDeclAs<ValueDecl>());
12574 C->setUniqueDecls(Decls);
12575
12576 SmallVector<unsigned, 16> ListsPerDecl;
12577 ListsPerDecl.reserve(UniqueDecls);
12578 for (unsigned i = 0; i < UniqueDecls; ++i)
12579 ListsPerDecl.push_back(Record.readInt());
12580 C->setDeclNumLists(ListsPerDecl);
12581
12582 SmallVector<unsigned, 32> ListSizes;
12583 ListSizes.reserve(TotalLists);
12584 for (unsigned i = 0; i < TotalLists; ++i)
12585 ListSizes.push_back(Record.readInt());
12586 C->setComponentListSizes(ListSizes);
12587
12588 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12589 Components.reserve(TotalComponents);
12590 for (unsigned i = 0; i < TotalComponents; ++i) {
12591 Expr *AssociatedExpr = Record.readSubExpr();
12592 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12593 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12594 AssociatedExpr, AssociatedDecl));
12595 }
12596 C->setComponents(Components, ListSizes);
12597}