blob: 179f25e1c80e7b6fd5039c84e274238aa37c3533 [file] [log] [blame]
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001//===- ASTReader.cpp - AST File Reader ------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000022#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000024#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000025#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000028#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000031#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000032#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000033#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000035#include "clang/AST/TemplateBase.h"
36#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000038#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000039#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "clang/AST/UnresolvedSet.h"
41#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000042#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000043#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000047#include "clang/Basic/IdentifierTable.h"
48#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000050#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000051#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include "clang/Basic/ObjCRuntime.h"
53#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000055#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000056#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include "clang/Basic/SourceManager.h"
58#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000059#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include "clang/Basic/TargetInfo.h"
61#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Basic/Version.h"
64#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000066#include "clang/Lex/HeaderSearch.h"
67#include "clang/Lex/HeaderSearchOptions.h"
68#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "clang/Lex/PreprocessingRecord.h"
71#include "clang/Lex/Preprocessor.h"
72#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000073#include "clang/Lex/Token.h"
74#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "clang/Sema/Scope.h"
76#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000077#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000078#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000079#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000080#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000081#include "clang/Serialization/GlobalModuleIndex.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000082#include "clang/Serialization/Module.h"
83#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include "clang/Serialization/ModuleManager.h"
85#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include "llvm/ADT/APFloat.h"
87#include "llvm/ADT/APInt.h"
88#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000089#include "llvm/ADT/ArrayRef.h"
90#include "llvm/ADT/DenseMap.h"
91#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000092#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000093#include "llvm/ADT/IntrusiveRefCntPtr.h"
94#include "llvm/ADT/None.h"
95#include "llvm/ADT/Optional.h"
96#include "llvm/ADT/STLExtras.h"
97#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000098#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000099#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000100#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000101#include "llvm/ADT/StringMap.h"
102#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000103#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000104#include "llvm/ADT/iterator_range.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000105#include "llvm/Bitcode/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000106#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +0000107#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000108#include "llvm/Support/Compiler.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000109#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000110#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000111#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000112#include "llvm/Support/ErrorHandling.h"
113#include "llvm/Support/FileSystem.h"
114#include "llvm/Support/MemoryBuffer.h"
115#include "llvm/Support/Path.h"
116#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000117#include "llvm/Support/Timer.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000118#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000119#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000121#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000123#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000125#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <limits>
127#include <map>
128#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000129#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000130#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000131#include <tuple>
132#include <utility>
133#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000134
135using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000136using namespace clang::serialization;
137using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000138using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000139
Ben Langmuircb69b572014-03-07 06:40:32 +0000140//===----------------------------------------------------------------------===//
141// ChainedASTReaderListener implementation
142//===----------------------------------------------------------------------===//
143
144bool
145ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
146 return First->ReadFullVersionInformation(FullVersion) ||
147 Second->ReadFullVersionInformation(FullVersion);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000150void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
151 First->ReadModuleName(ModuleName);
152 Second->ReadModuleName(ModuleName);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
156 First->ReadModuleMapFile(ModuleMapPath);
157 Second->ReadModuleMapFile(ModuleMapPath);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000160bool
161ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
162 bool Complain,
163 bool AllowCompatibleDifferences) {
164 return First->ReadLanguageOptions(LangOpts, Complain,
165 AllowCompatibleDifferences) ||
166 Second->ReadLanguageOptions(LangOpts, Complain,
167 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000169
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000170bool ChainedASTReaderListener::ReadTargetOptions(
171 const TargetOptions &TargetOpts, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadTargetOptions(TargetOpts, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadTargetOptions(TargetOpts, Complain,
176 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000177}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000178
Ben Langmuircb69b572014-03-07 06:40:32 +0000179bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000180 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000181 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
182 Second->ReadDiagnosticOptions(DiagOpts, Complain);
183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000184
Ben Langmuircb69b572014-03-07 06:40:32 +0000185bool
186ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
187 bool Complain) {
188 return First->ReadFileSystemOptions(FSOpts, Complain) ||
189 Second->ReadFileSystemOptions(FSOpts, Complain);
190}
191
192bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000193 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
194 bool Complain) {
195 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
196 Complain) ||
197 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
198 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000200
Ben Langmuircb69b572014-03-07 06:40:32 +0000201bool ChainedASTReaderListener::ReadPreprocessorOptions(
202 const PreprocessorOptions &PPOpts, bool Complain,
203 std::string &SuggestedPredefines) {
204 return First->ReadPreprocessorOptions(PPOpts, Complain,
205 SuggestedPredefines) ||
206 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
207}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000208
Ben Langmuircb69b572014-03-07 06:40:32 +0000209void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
210 unsigned Value) {
211 First->ReadCounter(M, Value);
212 Second->ReadCounter(M, Value);
213}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000214
Ben Langmuircb69b572014-03-07 06:40:32 +0000215bool ChainedASTReaderListener::needsInputFileVisitation() {
216 return First->needsInputFileVisitation() ||
217 Second->needsInputFileVisitation();
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
221 return First->needsSystemInputFileVisitation() ||
222 Second->needsSystemInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Richard Smith216a3bd2015-08-13 17:57:10 +0000225void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
226 ModuleKind Kind) {
227 First->visitModuleFile(Filename, Kind);
228 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000230
Ben Langmuircb69b572014-03-07 06:40:32 +0000231bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000232 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000233 bool isOverridden,
234 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000235 bool Continue = false;
236 if (First->needsInputFileVisitation() &&
237 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
239 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 if (Second->needsInputFileVisitation() &&
241 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000242 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
243 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000244 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000245}
246
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000247void ChainedASTReaderListener::readModuleFileExtension(
248 const ModuleFileExtensionMetadata &Metadata) {
249 First->readModuleFileExtension(Metadata);
250 Second->readModuleFileExtension(Metadata);
251}
252
Guy Benyei11169dd2012-12-18 14:30:41 +0000253//===----------------------------------------------------------------------===//
254// PCH validator implementation
255//===----------------------------------------------------------------------===//
256
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000257ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
259/// \brief Compare the given set of language options against an existing set of
260/// language options.
261///
262/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000263/// \param AllowCompatibleDifferences If true, differences between compatible
264/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000265///
266/// \returns true if the languagae options mis-match, false otherwise.
267static bool checkLanguageOptions(const LangOptions &LangOpts,
268 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000269 DiagnosticsEngine *Diags,
270 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#define LANGOPT(Name, Bits, Default, Description) \
272 if (ExistingLangOpts.Name != LangOpts.Name) { \
273 if (Diags) \
274 Diags->Report(diag::err_pch_langopt_mismatch) \
275 << Description << LangOpts.Name << ExistingLangOpts.Name; \
276 return true; \
277 }
278
279#define VALUE_LANGOPT(Name, Bits, Default, Description) \
280 if (ExistingLangOpts.Name != LangOpts.Name) { \
281 if (Diags) \
282 Diags->Report(diag::err_pch_langopt_value_mismatch) \
283 << Description; \
284 return true; \
285 }
286
287#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
289 if (Diags) \
290 Diags->Report(diag::err_pch_langopt_value_mismatch) \
291 << Description; \
292 return true; \
293 }
294
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000295#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
296 if (!AllowCompatibleDifferences) \
297 LANGOPT(Name, Bits, Default, Description)
298
299#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
300 if (!AllowCompatibleDifferences) \
301 ENUM_LANGOPT(Name, Bits, Default, Description)
302
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000303#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
304 if (!AllowCompatibleDifferences) \
305 VALUE_LANGOPT(Name, Bits, Default, Description)
306
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define BENIGN_LANGOPT(Name, Bits, Default, Description)
308#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000309#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310#include "clang/Basic/LangOptions.def"
311
Ben Langmuircd98cb72015-06-23 18:20:18 +0000312 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
313 if (Diags)
314 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
315 return true;
316 }
317
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
319 if (Diags)
320 Diags->Report(diag::err_pch_langopt_value_mismatch)
321 << "target Objective-C runtime";
322 return true;
323 }
324
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000325 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
326 LangOpts.CommentOpts.BlockCommandNames) {
327 if (Diags)
328 Diags->Report(diag::err_pch_langopt_value_mismatch)
329 << "block command names";
330 return true;
331 }
332
Vedant Kumar85a83c22017-06-01 20:01:01 +0000333 // Sanitizer feature mismatches are treated as compatible differences. If
334 // compatible differences aren't allowed, we still only want to check for
335 // mismatches of non-modular sanitizers (the only ones which can affect AST
336 // generation).
337 if (!AllowCompatibleDifferences) {
338 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
339 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
340 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
341 ExistingSanitizers.clear(ModularSanitizers);
342 ImportedSanitizers.clear(ModularSanitizers);
343 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
344 const std::string Flag = "-fsanitize=";
345 if (Diags) {
346#define SANITIZER(NAME, ID) \
347 { \
348 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
349 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
350 if (InExistingModule != InImportedModule) \
351 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
352 << InExistingModule << (Flag + NAME); \
353 }
354#include "clang/Basic/Sanitizers.def"
355 }
356 return true;
357 }
358 }
359
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 return false;
361}
362
363/// \brief Compare the given set of target options against an existing set of
364/// target options.
365///
366/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
367///
368/// \returns true if the target options mis-match, false otherwise.
369static bool checkTargetOptions(const TargetOptions &TargetOpts,
370 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000371 DiagnosticsEngine *Diags,
372 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000373#define CHECK_TARGET_OPT(Field, Name) \
374 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
375 if (Diags) \
376 Diags->Report(diag::err_pch_targetopt_mismatch) \
377 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
378 return true; \
379 }
380
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000381 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000384
385 // We can tolerate different CPUs in many cases, notably when one CPU
386 // supports a strict superset of another. When allowing compatible
387 // differences skip this check.
388 if (!AllowCompatibleDifferences)
389 CHECK_TARGET_OPT(CPU, "target CPU");
390
Guy Benyei11169dd2012-12-18 14:30:41 +0000391#undef CHECK_TARGET_OPT
392
393 // Compare feature sets.
394 SmallVector<StringRef, 4> ExistingFeatures(
395 ExistingTargetOpts.FeaturesAsWritten.begin(),
396 ExistingTargetOpts.FeaturesAsWritten.end());
397 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
398 TargetOpts.FeaturesAsWritten.end());
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000399 llvm::sort(ExistingFeatures.begin(), ExistingFeatures.end());
400 llvm::sort(ReadFeatures.begin(), ReadFeatures.end());
Guy Benyei11169dd2012-12-18 14:30:41 +0000401
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000402 // We compute the set difference in both directions explicitly so that we can
403 // diagnose the differences differently.
404 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
405 std::set_difference(
406 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
407 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
408 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
409 ExistingFeatures.begin(), ExistingFeatures.end(),
410 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000412 // If we are allowing compatible differences and the read feature set is
413 // a strict subset of the existing feature set, there is nothing to diagnose.
414 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
415 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 if (Diags) {
418 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000420 << /* is-existing-feature */ false << Feature;
421 for (StringRef Feature : UnmatchedExistingFeatures)
422 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000426 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000427}
428
429bool
430PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000431 bool Complain,
432 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 const LangOptions &ExistingLangOpts = PP.getLangOpts();
434 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000435 Complain ? &Reader.Diags : nullptr,
436 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000437}
438
439bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000440 bool Complain,
441 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
443 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000444 Complain ? &Reader.Diags : nullptr,
445 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000446}
447
448namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000449
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000450using MacroDefinitionsMap =
451 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
452using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000453
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000454} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000455
Ben Langmuirb92de022014-04-29 16:25:26 +0000456static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000460
461 // Check current mappings for new -Werror mappings, and the stored mappings
462 // for cases that were explicitly mapped to *not* be errors that are now
463 // errors because of options like -Werror.
464 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
465
Vedant Kumar48b4f762018-04-14 01:40:48 +0000466 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000467 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
468 diag::kind DiagID = DiagIDMappingPair.first;
469 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
470 if (CurLevel < DiagnosticsEngine::Error)
471 continue; // not significant
472 Level StoredLevel =
473 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
474 if (StoredLevel < DiagnosticsEngine::Error) {
475 if (Complain)
476 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
477 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
478 return true;
479 }
480 }
481 }
482
483 return false;
484}
485
Alp Tokerac4e8e52014-06-22 21:58:33 +0000486static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
487 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
488 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
489 return true;
490 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000491}
492
493static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
494 DiagnosticsEngine &Diags,
495 bool IsSystem, bool Complain) {
496 // Top-level options
497 if (IsSystem) {
498 if (Diags.getSuppressSystemWarnings())
499 return false;
500 // If -Wsystem-headers was not enabled before, be conservative
501 if (StoredDiags.getSuppressSystemWarnings()) {
502 if (Complain)
503 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
504 return true;
505 }
506 }
507
508 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
509 if (Complain)
510 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
511 return true;
512 }
513
514 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
515 !StoredDiags.getEnableAllWarnings()) {
516 if (Complain)
517 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
518 return true;
519 }
520
521 if (isExtHandlingFromDiagsError(Diags) &&
522 !isExtHandlingFromDiagsError(StoredDiags)) {
523 if (Complain)
524 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
525 return true;
526 }
527
528 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
529}
530
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000531/// Return the top import module if it is implicit, nullptr otherwise.
532static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
533 Preprocessor &PP) {
534 // If the original import came from a file explicitly generated by the user,
535 // don't check the diagnostic mappings.
536 // FIXME: currently this is approximated by checking whether this is not a
537 // module import of an implicitly-loaded module file.
538 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
539 // the transitive closure of its imports, since unrelated modules cannot be
540 // imported until after this module finishes validation.
541 ModuleFile *TopImport = &*ModuleMgr.rbegin();
542 while (!TopImport->ImportedBy.empty())
543 TopImport = TopImport->ImportedBy[0];
544 if (TopImport->Kind != MK_ImplicitModule)
545 return nullptr;
546
547 StringRef ModuleName = TopImport->ModuleName;
548 assert(!ModuleName.empty() && "diagnostic options read before module name");
549
550 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
551 assert(M && "missing module");
552 return M;
553}
554
Ben Langmuirb92de022014-04-29 16:25:26 +0000555bool PCHValidator::ReadDiagnosticOptions(
556 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
557 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
558 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
559 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000560 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000561 // This should never fail, because we would have processed these options
562 // before writing them to an ASTFile.
563 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
564
565 ModuleManager &ModuleMgr = Reader.getModuleManager();
566 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
567
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000568 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
569 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000570 return false;
571
Ben Langmuirb92de022014-04-29 16:25:26 +0000572 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
573 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000574 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
575 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000576}
577
Guy Benyei11169dd2012-12-18 14:30:41 +0000578/// \brief Collect the macro definitions provided by the given preprocessor
579/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000580static void
581collectMacroDefinitions(const PreprocessorOptions &PPOpts,
582 MacroDefinitionsMap &Macros,
583 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000584 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
585 StringRef Macro = PPOpts.Macros[I].first;
586 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000587
588 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
589 StringRef MacroName = MacroPair.first;
590 StringRef MacroBody = MacroPair.second;
591
592 // For an #undef'd macro, we only care about the name.
593 if (IsUndef) {
594 if (MacroNames && !Macros.count(MacroName))
595 MacroNames->push_back(MacroName);
596
597 Macros[MacroName] = std::make_pair("", true);
598 continue;
599 }
600
601 // For a #define'd macro, figure out the actual definition.
602 if (MacroName.size() == Macro.size())
603 MacroBody = "1";
604 else {
605 // Note: GCC drops anything following an end-of-line character.
606 StringRef::size_type End = MacroBody.find_first_of("\n\r");
607 MacroBody = MacroBody.substr(0, End);
608 }
609
610 if (MacroNames && !Macros.count(MacroName))
611 MacroNames->push_back(MacroName);
612 Macros[MacroName] = std::make_pair(MacroBody, false);
613 }
614}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615
Guy Benyei11169dd2012-12-18 14:30:41 +0000616/// \brief Check the preprocessor options deserialized from the control block
617/// against the preprocessor options in an existing preprocessor.
618///
619/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000620/// \param Validate If true, validate preprocessor options. If false, allow
621/// macros defined by \p ExistingPPOpts to override those defined by
622/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000623static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
624 const PreprocessorOptions &ExistingPPOpts,
625 DiagnosticsEngine *Diags,
626 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000627 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000628 const LangOptions &LangOpts,
629 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 // Check macro definitions.
631 MacroDefinitionsMap ASTFileMacros;
632 collectMacroDefinitions(PPOpts, ASTFileMacros);
633 MacroDefinitionsMap ExistingMacros;
634 SmallVector<StringRef, 4> ExistingMacroNames;
635 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
636
Vedant Kumar48b4f762018-04-14 01:40:48 +0000637 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000639 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
641
642 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000643 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
644 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000645 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 // FIXME: Check whether this identifier was referenced anywhere in the
647 // AST file. If so, we should reject the AST file. Unfortunately, this
648 // information isn't in the control block. What shall we do about it?
649
650 if (Existing.second) {
651 SuggestedPredefines += "#undef ";
652 SuggestedPredefines += MacroName.str();
653 SuggestedPredefines += '\n';
654 } else {
655 SuggestedPredefines += "#define ";
656 SuggestedPredefines += MacroName.str();
657 SuggestedPredefines += ' ';
658 SuggestedPredefines += Existing.first.str();
659 SuggestedPredefines += '\n';
660 }
661 continue;
662 }
663
664 // If the macro was defined in one but undef'd in the other, we have a
665 // conflict.
666 if (Existing.second != Known->second.second) {
667 if (Diags) {
668 Diags->Report(diag::err_pch_macro_def_undef)
669 << MacroName << Known->second.second;
670 }
671 return true;
672 }
673
674 // If the macro was #undef'd in both, or if the macro bodies are identical,
675 // it's fine.
676 if (Existing.second || Existing.first == Known->second.first)
677 continue;
678
679 // The macro bodies differ; complain.
680 if (Diags) {
681 Diags->Report(diag::err_pch_macro_def_conflict)
682 << MacroName << Known->second.first << Existing.first;
683 }
684 return true;
685 }
686
687 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000688 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000689 if (Diags) {
690 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
691 }
692 return true;
693 }
694
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000695 // Detailed record is important since it is used for the module cache hash.
696 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000697 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000698 if (Diags) {
699 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
700 }
701 return true;
702 }
703
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000705 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
706 StringRef File = ExistingPPOpts.Includes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 if (File == ExistingPPOpts.ImplicitPCHInclude)
708 continue;
709
710 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
711 != PPOpts.Includes.end())
712 continue;
713
714 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000715 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000716 SuggestedPredefines += "\"\n";
717 }
718
Vedant Kumar48b4f762018-04-14 01:40:48 +0000719 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
720 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
722 File)
723 != PPOpts.MacroIncludes.end())
724 continue;
725
726 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000727 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 SuggestedPredefines += "\"\n##\n";
729 }
730
731 return false;
732}
733
734bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
735 bool Complain,
736 std::string &SuggestedPredefines) {
737 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
738
739 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000740 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000742 SuggestedPredefines,
743 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000744}
745
Yaxun Liu43712e02016-09-07 18:40:20 +0000746bool SimpleASTReaderListener::ReadPreprocessorOptions(
747 const PreprocessorOptions &PPOpts,
748 bool Complain,
749 std::string &SuggestedPredefines) {
750 return checkPreprocessorOptions(PPOpts,
751 PP.getPreprocessorOpts(),
752 nullptr,
753 PP.getFileManager(),
754 SuggestedPredefines,
755 PP.getLangOpts(),
756 false);
757}
758
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000759/// Check the header search options deserialized from the control block
760/// against the header search options in an existing preprocessor.
761///
762/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
763static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
764 StringRef SpecificModuleCachePath,
765 StringRef ExistingModuleCachePath,
766 DiagnosticsEngine *Diags,
767 const LangOptions &LangOpts) {
768 if (LangOpts.Modules) {
769 if (SpecificModuleCachePath != ExistingModuleCachePath) {
770 if (Diags)
771 Diags->Report(diag::err_pch_modulecache_mismatch)
772 << SpecificModuleCachePath << ExistingModuleCachePath;
773 return true;
774 }
775 }
776
777 return false;
778}
779
780bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
781 StringRef SpecificModuleCachePath,
782 bool Complain) {
783 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
784 PP.getHeaderSearchInfo().getModuleCachePath(),
785 Complain ? &Reader.Diags : nullptr,
786 PP.getLangOpts());
787}
788
Guy Benyei11169dd2012-12-18 14:30:41 +0000789void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
790 PP.setCounterValue(Value);
791}
792
793//===----------------------------------------------------------------------===//
794// AST reader implementation
795//===----------------------------------------------------------------------===//
796
Nico Weber824285e2014-05-08 04:26:47 +0000797void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
798 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000800 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000801}
802
Guy Benyei11169dd2012-12-18 14:30:41 +0000803unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
804 return serialization::ComputeHash(Sel);
805}
806
Guy Benyei11169dd2012-12-18 14:30:41 +0000807std::pair<unsigned, unsigned>
808ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000809 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000810
Justin Bogner57ba0b22014-03-28 22:03:24 +0000811 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
812 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 return std::make_pair(KeyLen, DataLen);
814}
815
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000816ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000817ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000819
Guy Benyei11169dd2012-12-18 14:30:41 +0000820 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
822 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
823 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 if (N == 0)
825 return SelTable.getNullarySelector(FirstII);
826 else if (N == 1)
827 return SelTable.getUnarySelector(FirstII);
828
829 SmallVector<IdentifierInfo *, 16> Args;
830 Args.push_back(FirstII);
831 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 Args.push_back(Reader.getLocalIdentifier(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834
835 return SelTable.getSelector(N, Args.data());
836}
837
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000838ASTSelectorLookupTrait::data_type
839ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000841 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000842
843 data_type Result;
844
Justin Bogner57ba0b22014-03-28 22:03:24 +0000845 Result.ID = Reader.getGlobalSelectorID(
846 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000847 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
848 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
849 Result.InstanceBits = FullInstanceBits & 0x3;
850 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
851 Result.FactoryBits = FullFactoryBits & 0x3;
852 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
853 unsigned NumInstanceMethods = FullInstanceBits >> 3;
854 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000855
856 // Load instance methods
857 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000858 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000859 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 Result.Instance.push_back(Method);
861 }
862
863 // Load factory methods
864 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000865 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000866 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 Result.Factory.push_back(Method);
868 }
869
870 return Result;
871}
872
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000873unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000874 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000875}
876
877std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000878ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000879 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000880
Justin Bogner57ba0b22014-03-28 22:03:24 +0000881 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
882 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 return std::make_pair(KeyLen, DataLen);
884}
885
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000886ASTIdentifierLookupTraitBase::internal_key_type
887ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000888 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890}
891
Douglas Gregordcf25082013-02-11 18:16:18 +0000892/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000893static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
894 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000895 return II.hadMacroDefinition() ||
896 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000897 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000898 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000899 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Richard Smitha534a312015-07-21 23:54:07 +0000900 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000901}
902
Richard Smith76c2f2c2015-07-17 20:09:43 +0000903static bool readBit(unsigned &Bits) {
904 bool Value = Bits & 0x1;
905 Bits >>= 1;
906 return Value;
907}
908
Richard Smith79bf9202015-08-24 03:33:22 +0000909IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
910 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000911
Richard Smith79bf9202015-08-24 03:33:22 +0000912 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
913 return Reader.getGlobalIdentifierID(F, RawID >> 1);
914}
915
Richard Smitheb4b58f62016-02-05 01:40:54 +0000916static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
917 if (!II.isFromAST()) {
918 II.setIsFromAST();
919 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
920 if (isInterestingIdentifier(Reader, II, IsModule))
921 II.setChangedSinceDeserialization();
922 }
923}
924
Guy Benyei11169dd2012-12-18 14:30:41 +0000925IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
926 const unsigned char* d,
927 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000928 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000929
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000931 bool IsInteresting = RawID & 0x01;
932
933 // Wipe out the "is interesting" bit.
934 RawID = RawID >> 1;
935
Richard Smith76c2f2c2015-07-17 20:09:43 +0000936 // Build the IdentifierInfo and link the identifier ID with it.
937 IdentifierInfo *II = KnownII;
938 if (!II) {
939 II = &Reader.getIdentifierTable().getOwn(k);
940 KnownII = II;
941 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000942 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000943 Reader.markIdentifierUpToDate(II);
944
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
946 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000947 // For uninteresting identifiers, there's nothing else to do. Just notify
948 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return II;
951 }
952
Justin Bogner57ba0b22014-03-28 22:03:24 +0000953 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
954 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000955 bool CPlusPlusOperatorKeyword = readBit(Bits);
956 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000957 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000958 bool Poisoned = readBit(Bits);
959 bool ExtensionToken = readBit(Bits);
960 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961
962 assert(Bits == 0 && "Extra bits in the identifier?");
963 DataLen -= 8;
964
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 // Set or check the various bits in the IdentifierInfo structure.
966 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000967 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000968 II->revertTokenIDToIdentifier();
969 if (!F.isModule())
970 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
971 else if (HasRevertedBuiltin && II->getBuiltinID()) {
972 II->revertBuiltin();
973 assert((II->hasRevertedBuiltin() ||
974 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
975 "Incorrect ObjC keyword or builtin ID");
976 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 assert(II->isExtensionToken() == ExtensionToken &&
978 "Incorrect extension token flag");
979 (void)ExtensionToken;
980 if (Poisoned)
981 II->setIsPoisoned(true);
982 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
983 "Incorrect C++ operator keyword flag");
984 (void)CPlusPlusOperatorKeyword;
985
986 // If this identifier is a macro, deserialize the macro
987 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000988 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000989 uint32_t MacroDirectivesOffset =
990 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000991 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000992
Richard Smithd7329392015-04-21 21:46:32 +0000993 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 Reader.SetIdentifierInfo(ID, II);
997
998 // Read all of the declarations visible at global scope with this
999 // name.
1000 if (DataLen > 0) {
1001 SmallVector<uint32_t, 4> DeclIDs;
1002 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001003 DeclIDs.push_back(Reader.getGlobalDeclID(
1004 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1006 }
1007
1008 return II;
1009}
1010
Richard Smitha06c7e62015-08-26 23:55:49 +00001011DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1012 : Kind(Name.getNameKind()) {
1013 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001015 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::ObjCZeroArgSelector:
1018 case DeclarationName::ObjCOneArgSelector:
1019 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 break;
1022 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001023 Data = Name.getCXXOverloadedOperator();
1024 break;
1025 case DeclarationName::CXXLiteralOperatorName:
1026 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1027 break;
Richard Smith35845152017-02-07 01:37:30 +00001028 case DeclarationName::CXXDeductionGuideName:
1029 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1030 ->getDeclName().getAsIdentifierInfo();
1031 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 case DeclarationName::CXXConstructorName:
1033 case DeclarationName::CXXDestructorName:
1034 case DeclarationName::CXXConversionFunctionName:
1035 case DeclarationName::CXXUsingDirective:
1036 Data = 0;
1037 break;
1038 }
1039}
1040
1041unsigned DeclarationNameKey::getHash() const {
1042 llvm::FoldingSetNodeID ID;
1043 ID.AddInteger(Kind);
1044
1045 switch (Kind) {
1046 case DeclarationName::Identifier:
1047 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001048 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001049 ID.AddString(((IdentifierInfo*)Data)->getName());
1050 break;
1051 case DeclarationName::ObjCZeroArgSelector:
1052 case DeclarationName::ObjCOneArgSelector:
1053 case DeclarationName::ObjCMultiArgSelector:
1054 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1055 break;
1056 case DeclarationName::CXXOperatorName:
1057 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 break;
1059 case DeclarationName::CXXConstructorName:
1060 case DeclarationName::CXXDestructorName:
1061 case DeclarationName::CXXConversionFunctionName:
1062 case DeclarationName::CXXUsingDirective:
1063 break;
1064 }
1065
1066 return ID.ComputeHash();
1067}
1068
Richard Smithd88a7f12015-09-01 20:35:42 +00001069ModuleFile *
1070ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1071 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001072
Richard Smithd88a7f12015-09-01 20:35:42 +00001073 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1074 return Reader.getLocalModuleFile(F, ModuleFileID);
1075}
1076
Guy Benyei11169dd2012-12-18 14:30:41 +00001077std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001078ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001079 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001080
Justin Bogner57ba0b22014-03-28 22:03:24 +00001081 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1082 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001083 return std::make_pair(KeyLen, DataLen);
1084}
1085
Richard Smitha06c7e62015-08-26 23:55:49 +00001086ASTDeclContextNameLookupTrait::internal_key_type
1087ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001088 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
Vedant Kumar48b4f762018-04-14 01:40:48 +00001090 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001091 uint64_t Data;
1092 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001094 case DeclarationName::CXXLiteralOperatorName:
1095 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001096 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001097 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 break;
1099 case DeclarationName::ObjCZeroArgSelector:
1100 case DeclarationName::ObjCOneArgSelector:
1101 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001102 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001103 (uint64_t)Reader.getLocalSelector(
1104 F, endian::readNext<uint32_t, little, unaligned>(
1105 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 break;
1107 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001108 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 case DeclarationName::CXXConstructorName:
1111 case DeclarationName::CXXDestructorName:
1112 case DeclarationName::CXXConversionFunctionName:
1113 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001114 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 break;
1116 }
1117
Richard Smitha06c7e62015-08-26 23:55:49 +00001118 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001119}
1120
Richard Smithd88a7f12015-09-01 20:35:42 +00001121void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1122 const unsigned char *d,
1123 unsigned DataLen,
1124 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001125 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001126
Richard Smithd88a7f12015-09-01 20:35:42 +00001127 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1128 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1129 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001131}
1132
Richard Smith0f4e2c42015-08-06 04:23:48 +00001133bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1134 BitstreamCursor &Cursor,
1135 uint64_t Offset,
1136 DeclContext *DC) {
1137 assert(Offset != 0);
1138
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001140 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001141
Richard Smith0f4e2c42015-08-06 04:23:48 +00001142 RecordData Record;
1143 StringRef Blob;
1144 unsigned Code = Cursor.ReadCode();
1145 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1146 if (RecCode != DECL_CONTEXT_LEXICAL) {
1147 Error("Expected lexical block");
1148 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 }
1150
Richard Smith82f8fcd2015-08-06 22:07:25 +00001151 assert(!isa<TranslationUnitDecl>(DC) &&
1152 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001153 // If we are handling a C++ class template instantiation, we can see multiple
1154 // lexical updates for the same record. It's important that we select only one
1155 // of them, so that field numbering works properly. Just pick the first one we
1156 // see.
1157 auto &Lex = LexicalDecls[DC];
1158 if (!Lex.first) {
1159 Lex = std::make_pair(
1160 &M, llvm::makeArrayRef(
1161 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1162 Blob.data()),
1163 Blob.size() / 4));
1164 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001165 DC->setHasExternalLexicalStorage(true);
1166 return false;
1167}
Guy Benyei11169dd2012-12-18 14:30:41 +00001168
Richard Smith0f4e2c42015-08-06 04:23:48 +00001169bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1170 BitstreamCursor &Cursor,
1171 uint64_t Offset,
1172 DeclID ID) {
1173 assert(Offset != 0);
1174
1175 SavedStreamPosition SavedPosition(Cursor);
1176 Cursor.JumpToBit(Offset);
1177
1178 RecordData Record;
1179 StringRef Blob;
1180 unsigned Code = Cursor.ReadCode();
1181 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1182 if (RecCode != DECL_CONTEXT_VISIBLE) {
1183 Error("Expected visible lookup table block");
1184 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 }
1186
Richard Smith0f4e2c42015-08-06 04:23:48 +00001187 // We can't safely determine the primary context yet, so delay attaching the
1188 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001189 auto *Data = (const unsigned char*)Blob.data();
1190 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 return false;
1192}
1193
Richard Smith37a93df2017-02-18 00:32:02 +00001194void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001196 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001197 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001198 Diag(diag::note_module_cache_path)
1199 << PP.getHeaderSearchInfo().getModuleCachePath();
1200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001201}
1202
1203void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001204 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 if (Diags.isDiagnosticInFlight())
1206 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1207 else
1208 Diag(DiagID) << Arg1 << Arg2;
1209}
1210
1211//===----------------------------------------------------------------------===//
1212// Source Manager Deserialization
1213//===----------------------------------------------------------------------===//
1214
1215/// \brief Read the line table in the source manager block.
1216/// \returns true if there was an error.
1217bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001218 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 unsigned Idx = 0;
1220 LineTableInfo &LineTable = SourceMgr.getLineTable();
1221
1222 // Parse the file names
1223 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001224 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001225 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001227 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1229 }
Richard Smith63078492015-09-01 07:41:55 +00001230 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001231
1232 // Parse the line entries
1233 std::vector<LineEntry> Entries;
1234 while (Idx < Record.size()) {
1235 int FID = Record[Idx++];
1236 assert(FID >= 0 && "Serialized line entries for non-local file.");
1237 // Remap FileID from 1-based old view.
1238 FID += F.SLocEntryBaseID - 1;
1239
1240 // Extract the line entries
1241 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001242 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 Entries.clear();
1244 Entries.reserve(NumEntries);
1245 for (unsigned I = 0; I != NumEntries; ++I) {
1246 unsigned FileOffset = Record[Idx++];
1247 unsigned LineNo = Record[Idx++];
1248 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001249 SrcMgr::CharacteristicKind FileKind
1250 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 unsigned IncludeOffset = Record[Idx++];
1252 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1253 FileKind, IncludeOffset));
1254 }
1255 LineTable.AddEntry(FileID::get(FID), Entries);
1256 }
1257
1258 return false;
1259}
1260
1261/// \brief Read a source manager block
1262bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1263 using namespace SrcMgr;
1264
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001265 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001266
1267 // Set the source-location entry cursor to the current position in
1268 // the stream. This cursor will be used to read the contents of the
1269 // source manager block initially, and then lazily read
1270 // source-location entries as needed.
1271 SLocEntryCursor = F.Stream;
1272
1273 // The stream itself is going to skip over the source manager block.
1274 if (F.Stream.SkipBlock()) {
1275 Error("malformed block record in AST file");
1276 return true;
1277 }
1278
1279 // Enter the source manager block.
1280 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1281 Error("malformed source manager block record in AST file");
1282 return true;
1283 }
1284
1285 RecordData Record;
1286 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001287 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001288
Chris Lattnere7b154b2013-01-19 21:39:22 +00001289 switch (E.Kind) {
1290 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1291 case llvm::BitstreamEntry::Error:
1292 Error("malformed block record in AST file");
1293 return true;
1294 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001296 case llvm::BitstreamEntry::Record:
1297 // The interesting case.
1298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001300
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001303 StringRef Blob;
1304 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 default: // Default behavior: ignore.
1306 break;
1307
1308 case SM_SLOC_FILE_ENTRY:
1309 case SM_SLOC_BUFFER_ENTRY:
1310 case SM_SLOC_EXPANSION_ENTRY:
1311 // Once we hit one of the source location entries, we're done.
1312 return false;
1313 }
1314 }
1315}
1316
1317/// \brief If a header file is not found at the path that we expect it to be
1318/// and the PCH file was moved from its original location, try to resolve the
1319/// file by assuming that header+PCH were moved together and the header is in
1320/// the same place relative to the PCH.
1321static std::string
1322resolveFileRelativeToOriginalDir(const std::string &Filename,
1323 const std::string &OriginalDir,
1324 const std::string &CurrDir) {
1325 assert(OriginalDir != CurrDir &&
1326 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001327
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001329
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 SmallString<128> filePath(Filename);
1331 fs::make_absolute(filePath);
1332 assert(path::is_absolute(OriginalDir));
1333 SmallString<128> currPCHPath(CurrDir);
1334
1335 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1336 fileDirE = path::end(path::parent_path(filePath));
1337 path::const_iterator origDirI = path::begin(OriginalDir),
1338 origDirE = path::end(OriginalDir);
1339 // Skip the common path components from filePath and OriginalDir.
1340 while (fileDirI != fileDirE && origDirI != origDirE &&
1341 *fileDirI == *origDirI) {
1342 ++fileDirI;
1343 ++origDirI;
1344 }
1345 for (; origDirI != origDirE; ++origDirI)
1346 path::append(currPCHPath, "..");
1347 path::append(currPCHPath, fileDirI, fileDirE);
1348 path::append(currPCHPath, path::filename(Filename));
1349 return currPCHPath.str();
1350}
1351
1352bool ASTReader::ReadSLocEntry(int ID) {
1353 if (ID == 0)
1354 return false;
1355
1356 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1357 Error("source location entry ID out-of-range for AST file");
1358 return true;
1359 }
1360
Richard Smithaada85c2016-02-06 02:06:43 +00001361 // Local helper to read the (possibly-compressed) buffer data following the
1362 // entry record.
1363 auto ReadBuffer = [this](
1364 BitstreamCursor &SLocEntryCursor,
1365 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1366 RecordData Record;
1367 StringRef Blob;
1368 unsigned Code = SLocEntryCursor.ReadCode();
1369 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1370
1371 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001372 if (!llvm::zlib::isAvailable()) {
1373 Error("zlib is not available");
1374 return nullptr;
1375 }
Richard Smithaada85c2016-02-06 02:06:43 +00001376 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001377 if (llvm::Error E =
1378 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1379 Error("could not decompress embedded file contents: " +
1380 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001381 return nullptr;
1382 }
1383 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1384 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1385 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1386 } else {
1387 Error("AST record has invalid code");
1388 return nullptr;
1389 }
1390 };
1391
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1393 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001394 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 unsigned BaseOffset = F->SLocEntryBaseOffset;
1396
1397 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001398 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1399 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 Error("incorrectly-formatted source location entry in AST file");
1401 return true;
1402 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001403
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001405 StringRef Blob;
1406 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 default:
1408 Error("incorrectly-formatted source location entry in AST file");
1409 return true;
1410
1411 case SM_SLOC_FILE_ENTRY: {
1412 // We will detect whether a file changed and return 'Failure' for it, but
1413 // we will also try to fail gracefully by setting up the SLocEntry.
1414 unsigned InputID = Record[4];
1415 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001416 const FileEntry *File = IF.getFile();
1417 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001419 // Note that we only check if a File was returned. If it was out-of-date
1420 // we have complained but we will continue creating a FileID to recover
1421 // gracefully.
1422 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 return true;
1424
1425 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1426 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1427 // This is the module's main file.
1428 IncludeLoc = getImportLocation(F);
1429 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001430 SrcMgr::CharacteristicKind
1431 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1433 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001434 SrcMgr::FileInfo &FileInfo =
1435 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 FileInfo.NumCreatedFIDs = Record[5];
1437 if (Record[3])
1438 FileInfo.setHasLineDirectives();
1439
1440 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1441 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001442 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1444 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1445 NumFileDecls));
1446 }
Richard Smithaada85c2016-02-06 02:06:43 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001449 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001451 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1452 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001453 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1454 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001456 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 }
1458
1459 break;
1460 }
1461
1462 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001463 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001464 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001465 SrcMgr::CharacteristicKind
1466 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001468 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 IncludeLoc = getImportLocation(F);
1470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001471
Richard Smithaada85c2016-02-06 02:06:43 +00001472 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1473 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001475 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001476 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 break;
1478 }
1479
1480 case SM_SLOC_EXPANSION_ENTRY: {
1481 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1482 SourceMgr.createExpansionLoc(SpellingLoc,
1483 ReadSourceLocation(*F, Record[2]),
1484 ReadSourceLocation(*F, Record[3]),
1485 Record[4],
1486 ID,
1487 BaseOffset + Record[0]);
1488 break;
1489 }
1490 }
1491
1492 return false;
1493}
1494
1495std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1496 if (ID == 0)
1497 return std::make_pair(SourceLocation(), "");
1498
1499 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1500 Error("source location entry ID out-of-range for AST file");
1501 return std::make_pair(SourceLocation(), "");
1502 }
1503
1504 // Find which module file this entry lands in.
1505 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001506 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 return std::make_pair(SourceLocation(), "");
1508
1509 // FIXME: Can we map this down to a particular submodule? That would be
1510 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001511 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
1513
1514/// \brief Find the location where the module F is imported.
1515SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1516 if (F->ImportLoc.isValid())
1517 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001518
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 // Otherwise we have a PCH. It's considered to be "imported" at the first
1520 // location of its includer.
1521 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001522 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001523 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001524 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 return F->ImportedBy[0]->FirstLoc;
1527}
1528
1529/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1530/// specified cursor. Read the abbreviations that are at the top of the block
1531/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001532bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001533 if (Cursor.EnterSubBlock(BlockID))
1534 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001535
1536 while (true) {
1537 uint64_t Offset = Cursor.GetCurrentBitNo();
1538 unsigned Code = Cursor.ReadCode();
1539
1540 // We expect all abbrevs to be at the start of the block.
1541 if (Code != llvm::bitc::DEFINE_ABBREV) {
1542 Cursor.JumpToBit(Offset);
1543 return false;
1544 }
1545 Cursor.ReadAbbrevRecord();
1546 }
1547}
1548
Richard Smithe40f2ba2013-08-07 21:41:30 +00001549Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001550 unsigned &Idx) {
1551 Token Tok;
1552 Tok.startToken();
1553 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1554 Tok.setLength(Record[Idx++]);
1555 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1556 Tok.setIdentifierInfo(II);
1557 Tok.setKind((tok::TokenKind)Record[Idx++]);
1558 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1559 return Tok;
1560}
1561
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001562MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001563 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001564
1565 // Keep track of where we are in the stream, then jump back there
1566 // after reading this macro.
1567 SavedStreamPosition SavedPosition(Stream);
1568
1569 Stream.JumpToBit(Offset);
1570 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001571 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001572 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001573
Guy Benyei11169dd2012-12-18 14:30:41 +00001574 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001575 // Advance to the next record, but if we get to the end of the block, don't
1576 // pop it (removing all the abbreviations from the cursor) since we want to
1577 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001578 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001579 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001580
Chris Lattnerefa77172013-01-20 00:00:22 +00001581 switch (Entry.Kind) {
1582 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1583 case llvm::BitstreamEntry::Error:
1584 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001585 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001586 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001587 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001588 case llvm::BitstreamEntry::Record:
1589 // The interesting case.
1590 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 }
1592
1593 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 Record.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00001595 PreprocessorRecordTypes RecType =
1596 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001598 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001599 case PP_MACRO_DIRECTIVE_HISTORY:
1600 return Macro;
1601
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 case PP_MACRO_OBJECT_LIKE:
1603 case PP_MACRO_FUNCTION_LIKE: {
1604 // If we already have a macro, that means that we've hit the end
1605 // of the definition of the macro we were looking for. We're
1606 // done.
1607 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001608 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001609
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001610 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001611 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001612 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001613 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001615 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001616
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1618 // Decode function-like macro info.
1619 bool isC99VarArgs = Record[NextIndex++];
1620 bool isGNUVarArgs = Record[NextIndex++];
1621 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001622 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 unsigned NumArgs = Record[NextIndex++];
1624 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001625 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001626
1627 // Install function-like macro info.
1628 MI->setIsFunctionLike();
1629 if (isC99VarArgs) MI->setIsC99Varargs();
1630 if (isGNUVarArgs) MI->setIsGNUVarargs();
1631 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001632 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 }
1634
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 // Remember that we saw this macro last so that we add the tokens that
1636 // form its body to it.
1637 Macro = MI;
1638
1639 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1640 Record[NextIndex]) {
1641 // We have a macro definition. Register the association
1642 PreprocessedEntityID
1643 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1644 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001645 PreprocessingRecord::PPEntityID PPID =
1646 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001647 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001648 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001649 if (PPDef)
1650 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 }
1652
1653 ++NumMacrosRead;
1654 break;
1655 }
1656
1657 case PP_TOKEN: {
1658 // If we see a TOKEN before a PP_MACRO_*, then the file is
1659 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001660 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661
John McCallf413f5e2013-05-03 00:10:13 +00001662 unsigned Idx = 0;
1663 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 Macro->AddTokenToBody(Tok);
1665 break;
1666 }
1667 }
1668 }
1669}
1670
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001671PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001672ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1673 unsigned LocalID) const {
1674 if (!M.ModuleOffsetMap.empty())
1675 ReadModuleOffsetMap(M);
1676
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001677 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001679 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682 return LocalID + I->second;
1683}
1684
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001685unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1686 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001687}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001688
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001689HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001690HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001691 internal_key_type ikey = {FE->getSize(),
1692 M.HasTimestamps ? FE->getModificationTime() : 0,
1693 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001694 return ikey;
1695}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001696
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001697bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001698 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001699 return false;
1700
Mehdi Amini004b9c72016-10-10 22:52:47 +00001701 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001702 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001703
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001705 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001706 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1707 if (!Key.Imported)
1708 return FileMgr.getFile(Key.Filename);
1709
1710 std::string Resolved = Key.Filename;
1711 Reader.ResolveImportedPath(M, Resolved);
1712 return FileMgr.getFile(Resolved);
1713 };
1714
1715 const FileEntry *FEA = GetFile(a);
1716 const FileEntry *FEB = GetFile(b);
1717 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001718}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001719
Guy Benyei11169dd2012-12-18 14:30:41 +00001720std::pair<unsigned, unsigned>
1721HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001722 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001723
Vedant Kumar48b4f762018-04-14 01:40:48 +00001724 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1725 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001726 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001727}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001728
1729HeaderFileInfoTrait::internal_key_type
1730HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001731 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001732
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001733 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001734 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1735 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001736 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001737 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001738 return ikey;
1739}
1740
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001741HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001742HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001744 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001745
1746 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 HeaderFileInfo HFI;
1748 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001749 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001750 HFI.isImport |= (Flags >> 5) & 0x01;
1751 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1752 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001754 // FIXME: Find a better way to handle this. Maybe just store a
1755 // "has been included" flag?
1756 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1757 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001758 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1759 M, endian::readNext<uint32_t, little, unaligned>(d));
1760 if (unsigned FrameworkOffset =
1761 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001762 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 // since 0 is used as an indicator for "no framework name".
1764 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1765 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1766 }
Richard Smith386bb072015-08-18 23:42:23 +00001767
1768 assert((End - d) % 4 == 0 &&
1769 "Wrong data length in HeaderFileInfo deserialization");
1770 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001771 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001772 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1773 LocalSMID >>= 2;
1774
1775 // This header is part of a module. Associate it with the module to enable
1776 // implicit module import.
1777 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1778 Module *Mod = Reader.getSubmodule(GlobalSMID);
1779 FileManager &FileMgr = Reader.getFileManager();
1780 ModuleMap &ModMap =
1781 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1782
1783 std::string Filename = key.Filename;
1784 if (key.Imported)
1785 Reader.ResolveImportedPath(M, Filename);
1786 // FIXME: This is not always the right filename-as-written, but we're not
1787 // going to use this information to rebuild the module, so it doesn't make
1788 // a lot of difference.
1789 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001790 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1791 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001792 }
1793
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 // This HeaderFileInfo was externally loaded.
1795 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001796 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 return HFI;
1798}
1799
Richard Smithd7329392015-04-21 21:46:32 +00001800void ASTReader::addPendingMacro(IdentifierInfo *II,
1801 ModuleFile *M,
1802 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001803 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1804 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001805}
1806
1807void ASTReader::ReadDefinedMacros() {
1808 // Note that we are loading defined macros.
1809 Deserializing Macros(this);
1810
Vedant Kumar48b4f762018-04-14 01:40:48 +00001811 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001812 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001813
1814 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001815 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 continue;
1817
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001818 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001819 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001820
1821 RecordData Record;
1822 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001823 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001824
Chris Lattnere7b154b2013-01-19 21:39:22 +00001825 switch (E.Kind) {
1826 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1827 case llvm::BitstreamEntry::Error:
1828 Error("malformed block record in AST file");
1829 return;
1830 case llvm::BitstreamEntry::EndBlock:
1831 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001832
Chris Lattnere7b154b2013-01-19 21:39:22 +00001833 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001834 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001835 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001836 default: // Default behavior: ignore.
1837 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001838
Chris Lattnere7b154b2013-01-19 21:39:22 +00001839 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001840 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001841 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001842 if (II->isOutOfDate())
1843 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001844 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001845 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001846
Chris Lattnere7b154b2013-01-19 21:39:22 +00001847 case PP_TOKEN:
1848 // Ignore tokens.
1849 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 break;
1852 }
1853 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001854 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 }
1856}
1857
1858namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001859
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 /// \brief Visitor class used to look up identifirs in an AST file.
1861 class IdentifierLookupVisitor {
1862 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001863 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001864 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001865 unsigned &NumIdentifierLookups;
1866 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001867 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001868
Guy Benyei11169dd2012-12-18 14:30:41 +00001869 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001870 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1871 unsigned &NumIdentifierLookups,
1872 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001873 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1874 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001875 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001876 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001877
1878 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001880 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001882
Vedant Kumar48b4f762018-04-14 01:40:48 +00001883 ASTIdentifierLookupTable *IdTable
1884 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 if (!IdTable)
1886 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001887
1888 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001889 Found);
1890 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001891 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001892 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 if (Pos == IdTable->end())
1894 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001895
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 // Dereferencing the iterator has the effect of building the
1897 // IdentifierInfo node and populating it with the various
1898 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001899 ++NumIdentifierLookupHits;
1900 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001901 return true;
1902 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001903
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 // \brief Retrieve the identifier info found within the module
1905 // files.
1906 IdentifierInfo *getIdentifierInfo() const { return Found; }
1907 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001908
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001909} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001910
1911void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1912 // Note that we are loading an identifier.
1913 Deserializing AnIdentifier(this);
1914
1915 unsigned PriorGeneration = 0;
1916 if (getContext().getLangOpts().Modules)
1917 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001918
1919 // If there is a global index, look there first to determine which modules
1920 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001921 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001922 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001923 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001924 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1925 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001926 }
1927 }
1928
Douglas Gregor7211ac12013-01-25 23:32:03 +00001929 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001930 NumIdentifierLookups,
1931 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001932 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 markIdentifierUpToDate(&II);
1934}
1935
1936void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1937 if (!II)
1938 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001939
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 II->setOutOfDate(false);
1941
1942 // Update the generation for this identifier.
1943 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001944 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001945}
1946
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001947void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1948 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001949 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001950
1951 BitstreamCursor &Cursor = M.MacroCursor;
1952 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001953 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001954
Richard Smith713369b2015-04-23 20:40:50 +00001955 struct ModuleMacroRecord {
1956 SubmoduleID SubModID;
1957 MacroInfo *MI;
1958 SmallVector<SubmoduleID, 8> Overrides;
1959 };
1960 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001961
Richard Smithd7329392015-04-21 21:46:32 +00001962 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1963 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1964 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001965 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001966 while (true) {
1967 llvm::BitstreamEntry Entry =
1968 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1969 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1970 Error("malformed block record in AST file");
1971 return;
1972 }
1973
1974 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001975 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001976 case PP_MACRO_DIRECTIVE_HISTORY:
1977 break;
1978
1979 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001980 ModuleMacros.push_back(ModuleMacroRecord());
1981 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001982 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1983 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001984 for (int I = 2, N = Record.size(); I != N; ++I)
1985 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001986 continue;
1987 }
1988
1989 default:
1990 Error("malformed block record in AST file");
1991 return;
1992 }
1993
1994 // We found the macro directive history; that's the last record
1995 // for this macro.
1996 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001997 }
1998
Richard Smithd7329392015-04-21 21:46:32 +00001999 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002000 {
2001 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002002 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002003 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002004 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002005 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002006 Module *Mod = getSubmodule(ModID);
2007 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002008 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002009 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002010 }
2011
2012 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002013 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002014 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002015 }
2016 }
2017
2018 // Don't read the directive history for a module; we don't have anywhere
2019 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002020 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002021 return;
2022
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002023 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002024 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002025 unsigned Idx = 0, N = Record.size();
2026 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002027 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002028 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002029 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002030 switch (K) {
2031 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002032 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002033 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002034 break;
2035 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002036 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002037 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002038 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002039 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002040 bool isPublic = Record[Idx++];
2041 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2042 break;
2043 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002044
2045 if (!Latest)
2046 Latest = MD;
2047 if (Earliest)
2048 Earliest->setPrevious(MD);
2049 Earliest = MD;
2050 }
2051
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002052 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002053 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002054}
2055
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002056ASTReader::InputFileInfo
2057ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002058 // Go find this input file.
2059 BitstreamCursor &Cursor = F.InputFilesCursor;
2060 SavedStreamPosition SavedPosition(Cursor);
2061 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2062
2063 unsigned Code = Cursor.ReadCode();
2064 RecordData Record;
2065 StringRef Blob;
2066
2067 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2068 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2069 "invalid record type for input file");
2070 (void)Result;
2071
2072 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002073 InputFileInfo R;
2074 R.StoredSize = static_cast<off_t>(Record[1]);
2075 R.StoredTime = static_cast<time_t>(Record[2]);
2076 R.Overridden = static_cast<bool>(Record[3]);
2077 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002078 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002079 R.Filename = Blob;
2080 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002081 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002082}
2083
Manman Renc8c94152016-10-21 23:35:03 +00002084static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002085InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 // If this ID is bogus, just return an empty input file.
2087 if (ID == 0 || ID > F.InputFilesLoaded.size())
2088 return InputFile();
2089
2090 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002091 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 return F.InputFilesLoaded[ID-1];
2093
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002094 if (F.InputFilesLoaded[ID-1].isNotFound())
2095 return InputFile();
2096
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002098 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 SavedStreamPosition SavedPosition(Cursor);
2100 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002101
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002102 InputFileInfo FI = readInputFileInfo(F, ID);
2103 off_t StoredSize = FI.StoredSize;
2104 time_t StoredTime = FI.StoredTime;
2105 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002106 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002107 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002108
Richard Smitha8cfffa2015-11-26 02:04:16 +00002109 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 // If we didn't find the file, resolve it relative to the
2111 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002112 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2113 F.OriginalDir != F.BaseDirectory) {
2114 std::string Resolved = resolveFileRelativeToOriginalDir(
2115 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002116 if (!Resolved.empty())
2117 File = FileMgr.getFile(Resolved);
2118 }
2119
2120 // For an overridden file, create a virtual file with the stored
2121 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002122 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002123 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002124
Craig Toppera13603a2014-05-22 05:54:18 +00002125 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002126 if (Complain) {
2127 std::string ErrorStr = "could not find file '";
2128 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002129 ErrorStr += "' referenced by AST file '";
2130 ErrorStr += F.FileName;
2131 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002132 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002133 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 // Record that we didn't find the file.
2135 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2136 return InputFile();
2137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002138
Ben Langmuir198c1682014-03-07 07:27:49 +00002139 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002140 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002141 // can lead to problems when lexing using the source locations from the
2142 // PCH.
2143 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002144 // FIXME: Reject if the overrides are different.
2145 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002146 if (Complain)
2147 Error(diag::err_fe_pch_file_overridden, Filename);
2148 // After emitting the diagnostic, recover by disabling the override so
2149 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002150 //
2151 // FIXME: This recovery is just as broken as the original state; there may
2152 // be another precompiled module that's using the overridden contents, or
2153 // we might be half way through parsing it. Instead, we should treat the
2154 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 SM.disableFileContentsOverride(File);
2156 // The FileEntry is a virtual file entry with the size of the contents
2157 // that would override the original contents. Set it to the original's
2158 // size/time.
2159 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2160 StoredSize, StoredTime);
2161 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002162
Ben Langmuir198c1682014-03-07 07:27:49 +00002163 bool IsOutOfDate = false;
2164
2165 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002166 if (!Overridden && //
2167 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002168 (StoredTime && StoredTime != File->getModificationTime() &&
2169 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002170 )) {
2171 if (Complain) {
2172 // Build a list of the PCH imports that got us here (in reverse).
2173 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002174 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002175 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002176
Ben Langmuir198c1682014-03-07 07:27:49 +00002177 // The top-level PCH is stale.
2178 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002179 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2180 if (DiagnosticKind == 0)
2181 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2182 else if (DiagnosticKind == 1)
2183 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2184 else
2185 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002186
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 // Print the import stack.
2188 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2189 Diag(diag::note_pch_required_by)
2190 << Filename << ImportStack[0]->FileName;
2191 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002192 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002193 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002194 }
2195
Ben Langmuir198c1682014-03-07 07:27:49 +00002196 if (!Diags.isDiagnosticInFlight())
2197 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 }
2199
Ben Langmuir198c1682014-03-07 07:27:49 +00002200 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002202 // FIXME: If the file is overridden and we've already opened it,
2203 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
Richard Smitha8cfffa2015-11-26 02:04:16 +00002205 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002206
2207 // Note that we've loaded this input file.
2208 F.InputFilesLoaded[ID-1] = IF;
2209 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002210}
2211
Richard Smith7ed1bc92014-12-05 22:42:13 +00002212/// \brief If we are loading a relocatable PCH or module file, and the filename
2213/// is not an absolute path, add the system or module root to the beginning of
2214/// the file name.
2215void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2216 // Resolve relative to the base directory, if we have one.
2217 if (!M.BaseDirectory.empty())
2218 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002219}
2220
Richard Smith7ed1bc92014-12-05 22:42:13 +00002221void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2223 return;
2224
Richard Smith7ed1bc92014-12-05 22:42:13 +00002225 SmallString<128> Buffer;
2226 llvm::sys::path::append(Buffer, Prefix, Filename);
2227 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002228}
2229
Richard Smith0f99d6a2015-08-09 08:48:41 +00002230static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2231 switch (ARR) {
2232 case ASTReader::Failure: return true;
2233 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2234 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2235 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2236 case ASTReader::ConfigurationMismatch:
2237 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2238 case ASTReader::HadErrors: return true;
2239 case ASTReader::Success: return false;
2240 }
2241
2242 llvm_unreachable("unknown ASTReadResult");
2243}
2244
Richard Smith0516b182015-09-08 19:40:14 +00002245ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2246 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2247 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002248 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002249 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2250 return Failure;
2251
2252 // Read all of the records in the options block.
2253 RecordData Record;
2254 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002255 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002256 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002257
Richard Smith0516b182015-09-08 19:40:14 +00002258 switch (Entry.Kind) {
2259 case llvm::BitstreamEntry::Error:
2260 case llvm::BitstreamEntry::SubBlock:
2261 return Failure;
2262
2263 case llvm::BitstreamEntry::EndBlock:
2264 return Result;
2265
2266 case llvm::BitstreamEntry::Record:
2267 // The interesting case.
2268 break;
2269 }
2270
2271 // Read and process a record.
2272 Record.clear();
2273 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2274 case LANGUAGE_OPTIONS: {
2275 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2276 if (ParseLanguageOptions(Record, Complain, Listener,
2277 AllowCompatibleConfigurationMismatch))
2278 Result = ConfigurationMismatch;
2279 break;
2280 }
2281
2282 case TARGET_OPTIONS: {
2283 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2284 if (ParseTargetOptions(Record, Complain, Listener,
2285 AllowCompatibleConfigurationMismatch))
2286 Result = ConfigurationMismatch;
2287 break;
2288 }
2289
Richard Smith0516b182015-09-08 19:40:14 +00002290 case FILE_SYSTEM_OPTIONS: {
2291 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2292 if (!AllowCompatibleConfigurationMismatch &&
2293 ParseFileSystemOptions(Record, Complain, Listener))
2294 Result = ConfigurationMismatch;
2295 break;
2296 }
2297
2298 case HEADER_SEARCH_OPTIONS: {
2299 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2300 if (!AllowCompatibleConfigurationMismatch &&
2301 ParseHeaderSearchOptions(Record, Complain, Listener))
2302 Result = ConfigurationMismatch;
2303 break;
2304 }
2305
2306 case PREPROCESSOR_OPTIONS:
2307 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2308 if (!AllowCompatibleConfigurationMismatch &&
2309 ParsePreprocessorOptions(Record, Complain, Listener,
2310 SuggestedPredefines))
2311 Result = ConfigurationMismatch;
2312 break;
2313 }
2314 }
2315}
2316
Guy Benyei11169dd2012-12-18 14:30:41 +00002317ASTReader::ASTReadResult
2318ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002319 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002320 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002321 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002322 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002323 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324
2325 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2326 Error("malformed block record in AST file");
2327 return Failure;
2328 }
2329
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002330 // Lambda to read the unhashed control block the first time it's called.
2331 //
2332 // For PCM files, the unhashed control block cannot be read until after the
2333 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2334 // need to look ahead before reading the IMPORTS record. For consistency,
2335 // this block is always read somehow (see BitstreamEntry::EndBlock).
2336 bool HasReadUnhashedControlBlock = false;
2337 auto readUnhashedControlBlockOnce = [&]() {
2338 if (!HasReadUnhashedControlBlock) {
2339 HasReadUnhashedControlBlock = true;
2340 if (ASTReadResult Result =
2341 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2342 return Result;
2343 }
2344 return Success;
2345 };
2346
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 // Read all of the records and blocks in the control block.
2348 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002349 unsigned NumInputs = 0;
2350 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002351 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002353
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354 switch (Entry.Kind) {
2355 case llvm::BitstreamEntry::Error:
2356 Error("malformed block record in AST file");
2357 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002358 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002359 // Validate the module before returning. This call catches an AST with
2360 // no module name and no imports.
2361 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2362 return Result;
2363
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002364 // Validate input files.
2365 const HeaderSearchOptions &HSOpts =
2366 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002367
Richard Smitha1825302014-10-23 22:18:29 +00002368 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002369 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2370 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002371 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2372 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002374
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002375 // If we are reading a module, we will create a verification timestamp,
2376 // so we verify all input files. Otherwise, verify only user input
2377 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002378
2379 unsigned N = NumUserInputs;
2380 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002381 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002382 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002383 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002384 N = NumInputs;
2385
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002386 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002387 InputFile IF = getInputFile(F, I+1, Complain);
2388 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002390 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002392
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002393 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002394 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002395
Ben Langmuircb69b572014-03-07 06:40:32 +00002396 if (Listener && Listener->needsInputFileVisitation()) {
2397 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2398 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002399 for (unsigned I = 0; I < N; ++I) {
2400 bool IsSystem = I >= NumUserInputs;
2401 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002402 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002403 F.Kind == MK_ExplicitModule ||
2404 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002405 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002406 }
2407
Richard Smith8a308ec2015-11-05 00:54:55 +00002408 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002409 }
2410
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411 case llvm::BitstreamEntry::SubBlock:
2412 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 case INPUT_FILES_BLOCK_ID:
2414 F.InputFilesCursor = Stream;
2415 if (Stream.SkipBlock() || // Skip with the main cursor
2416 // Read the abbreviations
2417 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2418 Error("malformed block record in AST file");
2419 return Failure;
2420 }
2421 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002422
2423 case OPTIONS_BLOCK_ID:
2424 // If we're reading the first module for this group, check its options
2425 // are compatible with ours. For modules it imports, no further checking
2426 // is required, because we checked them when we built it.
2427 if (Listener && !ImportedBy) {
2428 // Should we allow the configuration of the module file to differ from
2429 // the configuration of the current translation unit in a compatible
2430 // way?
2431 //
2432 // FIXME: Allow this for files explicitly specified with -include-pch.
2433 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002434 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002435
Richard Smith8a308ec2015-11-05 00:54:55 +00002436 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2437 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002438 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002439 if (Result == Failure) {
2440 Error("malformed block record in AST file");
2441 return Result;
2442 }
2443
Richard Smith8a308ec2015-11-05 00:54:55 +00002444 if (DisableValidation ||
2445 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2446 Result = Success;
2447
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002448 // If we can't load the module, exit early since we likely
2449 // will rebuild the module anyway. The stream may be in the
2450 // middle of a block.
2451 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002452 return Result;
2453 } else if (Stream.SkipBlock()) {
2454 Error("malformed block record in AST file");
2455 return Failure;
2456 }
2457 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002458
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002460 if (Stream.SkipBlock()) {
2461 Error("malformed block record in AST file");
2462 return Failure;
2463 }
2464 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002466
Chris Lattnere7b154b2013-01-19 21:39:22 +00002467 case llvm::BitstreamEntry::Record:
2468 // The interesting case.
2469 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 }
2471
2472 // Read and process a record.
2473 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002474 StringRef Blob;
2475 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 case METADATA: {
2477 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2478 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002479 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2480 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 return VersionMismatch;
2482 }
2483
Richard Smithe75ee0f2015-08-17 07:13:32 +00002484 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2486 Diag(diag::err_pch_with_compiler_errors);
2487 return HadErrors;
2488 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002489 if (hasErrors) {
2490 Diags.ErrorOccurred = true;
2491 Diags.UncompilableErrorOccurred = true;
2492 Diags.UnrecoverableErrorOccurred = true;
2493 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002494
2495 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002496 // Relative paths in a relocatable PCH are relative to our sysroot.
2497 if (F.RelocatablePCH)
2498 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499
Richard Smithe75ee0f2015-08-17 07:13:32 +00002500 F.HasTimestamps = Record[5];
2501
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002503 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2505 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002506 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 return VersionMismatch;
2508 }
2509 break;
2510 }
2511
2512 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002513 // Validate the AST before processing any imports (otherwise, untangling
2514 // them can be error-prone and expensive). A module will have a name and
2515 // will already have been validated, but this catches the PCH case.
2516 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2517 return Result;
2518
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002519 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 unsigned Idx = 0, N = Record.size();
2521 while (Idx < N) {
2522 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002523 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 // The import location will be the local one for now; we will adjust
2525 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002526 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002528 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002529 off_t StoredSize = (off_t)Record[Idx++];
2530 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002531 ASTFileSignature StoredSignature = {
2532 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2533 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2534 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002535
2536 std::string ImportedName = ReadString(Record, Idx);
2537 std::string ImportedFile;
2538
2539 // For prebuilt and explicit modules first consult the file map for
2540 // an override. Note that here we don't search prebuilt module
2541 // directories, only the explicit name to file mappings. Also, we will
2542 // still verify the size/signature making sure it is essentially the
2543 // same file but perhaps in a different location.
2544 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2545 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2546 ImportedName, /*FileMapOnly*/ true);
2547
2548 if (ImportedFile.empty())
2549 ImportedFile = ReadPath(F, Record, Idx);
2550 else
2551 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002552
Richard Smith0f99d6a2015-08-09 08:48:41 +00002553 // If our client can't cope with us being out of date, we can't cope with
2554 // our dependency being missing.
2555 unsigned Capabilities = ClientLoadCapabilities;
2556 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2557 Capabilities &= ~ARR_Missing;
2558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002560 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2561 Loaded, StoredSize, StoredModTime,
2562 StoredSignature, Capabilities);
2563
2564 // If we diagnosed a problem, produce a backtrace.
2565 if (isDiagnosedResult(Result, Capabilities))
2566 Diag(diag::note_module_file_imported_by)
2567 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2568
2569 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 case Failure: return Failure;
2571 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002572 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 case OutOfDate: return OutOfDate;
2574 case VersionMismatch: return VersionMismatch;
2575 case ConfigurationMismatch: return ConfigurationMismatch;
2576 case HadErrors: return HadErrors;
2577 case Success: break;
2578 }
2579 }
2580 break;
2581 }
2582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case ORIGINAL_FILE:
2584 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002585 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002587 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 break;
2589
2590 case ORIGINAL_FILE_ID:
2591 F.OriginalSourceFileID = FileID::get(Record[0]);
2592 break;
2593
2594 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002595 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 break;
2597
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002598 case MODULE_NAME:
2599 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002600 if (Listener)
2601 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002602
2603 // Validate the AST as soon as we have a name so we can exit early on
2604 // failure.
2605 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2606 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002607
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002608 break;
2609
Richard Smith223d3f22014-12-06 03:21:08 +00002610 case MODULE_DIRECTORY: {
2611 assert(!F.ModuleName.empty() &&
2612 "MODULE_DIRECTORY found before MODULE_NAME");
2613 // If we've already loaded a module map file covering this module, we may
2614 // have a better path for it (relative to the current build).
2615 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2616 if (M && M->Directory) {
2617 // If we're implicitly loading a module, the base directory can't
2618 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002619 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002620 const DirectoryEntry *BuildDir =
2621 PP.getFileManager().getDirectory(Blob);
2622 if (!BuildDir || BuildDir != M->Directory) {
2623 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2624 Diag(diag::err_imported_module_relocated)
2625 << F.ModuleName << Blob << M->Directory->getName();
2626 return OutOfDate;
2627 }
2628 }
2629 F.BaseDirectory = M->Directory->getName();
2630 } else {
2631 F.BaseDirectory = Blob;
2632 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002633 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002634 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002635
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002636 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002637 if (ASTReadResult Result =
2638 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2639 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002640 break;
2641
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002642 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002643 NumInputs = Record[0];
2644 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002645 F.InputFileOffsets =
2646 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002647 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002648 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 break;
2650 }
2651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002652}
2653
Ben Langmuir2c9af442014-04-10 17:57:43 +00002654ASTReader::ASTReadResult
2655ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002656 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657
2658 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2659 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002660 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 }
2662
2663 // Read all of the records and blocks for the AST file.
2664 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002665 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002666 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002667
Chris Lattnere7b154b2013-01-19 21:39:22 +00002668 switch (Entry.Kind) {
2669 case llvm::BitstreamEntry::Error:
2670 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002671 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002672 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002673 // Outside of C++, we do not store a lookup map for the translation unit.
2674 // Instead, mark it as needing a lookup map to be built if this module
2675 // contains any declarations lexically within it (which it always does!).
2676 // This usually has no cost, since we very rarely need the lookup map for
2677 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002678 if (ASTContext *Ctx = ContextObj) {
2679 DeclContext *DC = Ctx->getTranslationUnitDecl();
2680 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2681 DC->setMustBuildLookupTable();
2682 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002683
Ben Langmuir2c9af442014-04-10 17:57:43 +00002684 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002685 case llvm::BitstreamEntry::SubBlock:
2686 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 case DECLTYPES_BLOCK_ID:
2688 // We lazily load the decls block, but we want to set up the
2689 // DeclsCursor cursor to point into it. Clone our current bitcode
2690 // cursor to it, enter the block and read the abbrevs in that block.
2691 // With the main cursor, we just skip over it.
2692 F.DeclsCursor = Stream;
2693 if (Stream.SkipBlock() || // Skip with the main cursor.
2694 // Read the abbrevs.
2695 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2696 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002697 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 }
2699 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 case PREPROCESSOR_BLOCK_ID:
2702 F.MacroCursor = Stream;
2703 if (!PP.getExternalSource())
2704 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002705
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 if (Stream.SkipBlock() ||
2707 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2708 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002709 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 }
2711 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2712 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002713
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 case PREPROCESSOR_DETAIL_BLOCK_ID:
2715 F.PreprocessorDetailCursor = Stream;
2716 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002717 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002719 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002720 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002721 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002723 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002724
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 if (!PP.getPreprocessingRecord())
2726 PP.createPreprocessingRecord();
2727 if (!PP.getPreprocessingRecord()->getExternalSource())
2728 PP.getPreprocessingRecord()->SetExternalSource(*this);
2729 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002730
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 case SOURCE_MANAGER_BLOCK_ID:
2732 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002733 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002735
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002737 if (ASTReadResult Result =
2738 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002739 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002741
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002743 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 if (Stream.SkipBlock() ||
2745 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2746 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002747 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 }
2749 CommentsCursors.push_back(std::make_pair(C, &F));
2750 break;
2751 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002752
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002754 if (Stream.SkipBlock()) {
2755 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002756 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002757 }
2758 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 }
2760 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002761
Chris Lattnere7b154b2013-01-19 21:39:22 +00002762 case llvm::BitstreamEntry::Record:
2763 // The interesting case.
2764 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 }
2766
2767 // Read and process a record.
2768 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002769 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002770 auto RecordType =
2771 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2772
2773 // If we're not loading an AST context, we don't care about most records.
2774 if (!ContextObj) {
2775 switch (RecordType) {
2776 case IDENTIFIER_TABLE:
2777 case IDENTIFIER_OFFSET:
2778 case INTERESTING_IDENTIFIERS:
2779 case STATISTICS:
2780 case PP_CONDITIONAL_STACK:
2781 case PP_COUNTER_VALUE:
2782 case SOURCE_LOCATION_OFFSETS:
2783 case MODULE_OFFSET_MAP:
2784 case SOURCE_MANAGER_LINE_TABLE:
2785 case SOURCE_LOCATION_PRELOADS:
2786 case PPD_ENTITIES_OFFSETS:
2787 case HEADER_SEARCH_TABLE:
2788 case IMPORTED_MODULES:
2789 case MACRO_OFFSET:
2790 break;
2791 default:
2792 continue;
2793 }
2794 }
2795
2796 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 default: // Default behavior: ignore.
2798 break;
2799
2800 case TYPE_OFFSET: {
2801 if (F.LocalNumTypes != 0) {
2802 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002803 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002805 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 F.LocalNumTypes = Record[0];
2807 unsigned LocalBaseTypeIndex = Record[1];
2808 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002809
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 if (F.LocalNumTypes > 0) {
2811 // Introduce the global -> local mapping for types within this module.
2812 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002813
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 // Introduce the local -> global mapping for types within this module.
2815 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002816 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002817 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002818
2819 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 }
2821 break;
2822 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 case DECL_OFFSET: {
2825 if (F.LocalNumDecls != 0) {
2826 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002827 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002829 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 F.LocalNumDecls = Record[0];
2831 unsigned LocalBaseDeclID = Record[1];
2832 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002833
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002835 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 // module.
2837 GlobalDeclMap.insert(
2838 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002839
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 // Introduce the local -> global mapping for declarations within this
2841 // module.
2842 F.DeclRemap.insertOrReplace(
2843 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002844
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 // Introduce the global -> local mapping for declarations within this
2846 // module.
2847 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002848
Ben Langmuir52ca6782014-10-20 16:27:32 +00002849 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2850 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 break;
2852 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002855 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002856 LexicalContents Contents(
2857 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2858 Blob.data()),
2859 static_cast<unsigned int>(Blob.size() / 4));
2860 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 TU->setHasExternalLexicalStorage(true);
2862 break;
2863 }
2864
2865 case UPDATE_VISIBLE: {
2866 unsigned Idx = 0;
2867 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002868 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002869 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002870 // If we've already loaded the decl, perform the updates when we finish
2871 // loading this block.
2872 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002873 PendingUpdateRecords.push_back(
2874 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 break;
2876 }
2877
2878 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002879 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002881 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2882 (const unsigned char *)F.IdentifierTableData + Record[0],
2883 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2884 (const unsigned char *)F.IdentifierTableData,
2885 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002886
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2888 }
2889 break;
2890
2891 case IDENTIFIER_OFFSET: {
2892 if (F.LocalNumIdentifiers != 0) {
2893 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002894 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002896 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 F.LocalNumIdentifiers = Record[0];
2898 unsigned LocalBaseIdentifierID = Record[1];
2899 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002900
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 if (F.LocalNumIdentifiers > 0) {
2902 // Introduce the global -> local mapping for identifiers within this
2903 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002904 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002906
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 // Introduce the local -> global mapping for identifiers within this
2908 // module.
2909 F.IdentifierRemap.insertOrReplace(
2910 std::make_pair(LocalBaseIdentifierID,
2911 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002912
Ben Langmuir52ca6782014-10-20 16:27:32 +00002913 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2914 + F.LocalNumIdentifiers);
2915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002916 break;
2917 }
2918
Richard Smith33e0f7e2015-07-22 02:08:40 +00002919 case INTERESTING_IDENTIFIERS:
2920 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2921 break;
2922
Ben Langmuir332aafe2014-01-31 01:06:56 +00002923 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002924 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2925 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002927 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 break;
2929
David Blaikie9ffe5a32017-01-30 05:00:26 +00002930 case MODULAR_CODEGEN_DECLS:
2931 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2932 // them (ie: if we're not codegenerating this module).
2933 if (F.Kind == MK_MainFile)
2934 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2935 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2936 break;
2937
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002939 if (SpecialTypes.empty()) {
2940 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2941 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2942 break;
2943 }
2944
2945 if (SpecialTypes.size() != Record.size()) {
2946 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002947 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002948 }
2949
2950 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2951 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2952 if (!SpecialTypes[I])
2953 SpecialTypes[I] = ID;
2954 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2955 // merge step?
2956 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 break;
2958
2959 case STATISTICS:
2960 TotalNumStatements += Record[0];
2961 TotalNumMacros += Record[1];
2962 TotalLexicalDeclContexts += Record[2];
2963 TotalVisibleDeclContexts += Record[3];
2964 break;
2965
2966 case UNUSED_FILESCOPED_DECLS:
2967 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2968 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2969 break;
2970
2971 case DELEGATING_CTORS:
2972 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2973 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2974 break;
2975
2976 case WEAK_UNDECLARED_IDENTIFIERS:
2977 if (Record.size() % 4 != 0) {
2978 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002979 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002981
2982 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 // files. This isn't the way to do it :)
2984 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002985
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 // Translate the weak, undeclared identifiers into global IDs.
2987 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2988 WeakUndeclaredIdentifiers.push_back(
2989 getGlobalIdentifierID(F, Record[I++]));
2990 WeakUndeclaredIdentifiers.push_back(
2991 getGlobalIdentifierID(F, Record[I++]));
2992 WeakUndeclaredIdentifiers.push_back(
2993 ReadSourceLocation(F, Record, I).getRawEncoding());
2994 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2995 }
2996 break;
2997
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002999 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 F.LocalNumSelectors = Record[0];
3001 unsigned LocalBaseSelectorID = Record[1];
3002 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003003
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003005 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 // module.
3007 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003008
3009 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 // module.
3011 F.SelectorRemap.insertOrReplace(
3012 std::make_pair(LocalBaseSelectorID,
3013 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003014
3015 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 }
3017 break;
3018 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003019
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003021 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 if (Record[0])
3023 F.SelectorLookupTable
3024 = ASTSelectorLookupTable::Create(
3025 F.SelectorLookupTableData + Record[0],
3026 F.SelectorLookupTableData,
3027 ASTSelectorLookupTrait(*this, F));
3028 TotalNumMethodPoolEntries += Record[1];
3029 break;
3030
3031 case REFERENCED_SELECTOR_POOL:
3032 if (!Record.empty()) {
3033 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003034 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 Record[Idx++]));
3036 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3037 getRawEncoding());
3038 }
3039 }
3040 break;
3041
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003042 case PP_CONDITIONAL_STACK:
3043 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003044 unsigned Idx = 0, End = Record.size() - 1;
3045 bool ReachedEOFWhileSkipping = Record[Idx++];
3046 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3047 if (ReachedEOFWhileSkipping) {
3048 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3049 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3050 bool FoundNonSkipPortion = Record[Idx++];
3051 bool FoundElse = Record[Idx++];
3052 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3053 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3054 FoundElse, ElseLoc);
3055 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003056 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003057 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003058 auto Loc = ReadSourceLocation(F, Record, Idx);
3059 bool WasSkipping = Record[Idx++];
3060 bool FoundNonSkip = Record[Idx++];
3061 bool FoundElse = Record[Idx++];
3062 ConditionalStack.push_back(
3063 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3064 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003065 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003066 }
3067 break;
3068
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 case PP_COUNTER_VALUE:
3070 if (!Record.empty() && Listener)
3071 Listener->ReadCounter(F, Record[0]);
3072 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003073
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003075 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 F.NumFileSortedDecls = Record[0];
3077 break;
3078
3079 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003080 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 F.LocalNumSLocEntries = Record[0];
3082 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003083 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003084 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003086 if (!F.SLocEntryBaseID) {
3087 Error("ran out of source locations");
3088 break;
3089 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 // Make our entry in the range map. BaseID is negative and growing, so
3091 // we invert it. Because we invert it, though, we need the other end of
3092 // the range.
3093 unsigned RangeStart =
3094 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3095 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3096 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3097
3098 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3099 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3100 GlobalSLocOffsetMap.insert(
3101 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3102 - SLocSpaceSize,&F));
3103
3104 // Initialize the remapping table.
3105 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003106 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003108 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 TotalNumSLocEntries += F.LocalNumSLocEntries;
3112 break;
3113 }
3114
Richard Smith37a93df2017-02-18 00:32:02 +00003115 case MODULE_OFFSET_MAP:
3116 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118
3119 case SOURCE_MANAGER_LINE_TABLE:
3120 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003121 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 break;
3123
3124 case SOURCE_LOCATION_PRELOADS: {
3125 // Need to transform from the local view (1-based IDs) to the global view,
3126 // which is based off F.SLocEntryBaseID.
3127 if (!F.PreloadSLocEntries.empty()) {
3128 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003129 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 F.PreloadSLocEntries.swap(Record);
3133 break;
3134 }
3135
3136 case EXT_VECTOR_DECLS:
3137 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3138 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3139 break;
3140
3141 case VTABLE_USES:
3142 if (Record.size() % 3 != 0) {
3143 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003144 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003146
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 // Later tables overwrite earlier ones.
3148 // FIXME: Modules will have some trouble with this. This is clearly not
3149 // the right way to do this.
3150 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3153 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3154 VTableUses.push_back(
3155 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3156 VTableUses.push_back(Record[Idx++]);
3157 }
3158 break;
3159
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 case PENDING_IMPLICIT_INSTANTIATIONS:
3161 if (PendingInstantiations.size() % 2 != 0) {
3162 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003163 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 }
3165
3166 if (Record.size() % 2 != 0) {
3167 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003168 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 }
3170
3171 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3172 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3173 PendingInstantiations.push_back(
3174 ReadSourceLocation(F, Record, I).getRawEncoding());
3175 }
3176 break;
3177
3178 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003179 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003180 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003181 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003182 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3184 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3185 break;
3186
3187 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003188 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3189 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3190 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003191
3192 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003193
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 unsigned StartingID;
3195 if (!PP.getPreprocessingRecord())
3196 PP.createPreprocessingRecord();
3197 if (!PP.getPreprocessingRecord()->getExternalSource())
3198 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003199 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003201 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 F.BasePreprocessedEntityID = StartingID;
3203
3204 if (F.NumPreprocessedEntities > 0) {
3205 // Introduce the global -> local mapping for preprocessed entities in
3206 // this module.
3207 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003208
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 // Introduce the local -> global mapping for preprocessed entities in
3210 // this module.
3211 F.PreprocessedEntityRemap.insertOrReplace(
3212 std::make_pair(LocalBasePreprocessedEntityID,
3213 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3214 }
3215
3216 break;
3217 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003218
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003219 case PPD_SKIPPED_RANGES: {
3220 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3221 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3222 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3223
3224 if (!PP.getPreprocessingRecord())
3225 PP.createPreprocessingRecord();
3226 if (!PP.getPreprocessingRecord()->getExternalSource())
3227 PP.getPreprocessingRecord()->SetExternalSource(*this);
3228 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3229 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003230
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003231 if (F.NumPreprocessedSkippedRanges > 0)
3232 GlobalSkippedRangeMap.insert(
3233 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3234 break;
3235 }
3236
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003237 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 if (Record.size() % 2 != 0) {
3239 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003240 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003242 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3243 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3244 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3245
3246 // If we've already loaded the decl, perform the updates when we finish
3247 // loading this block.
3248 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003249 PendingUpdateRecords.push_back(
3250 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003251 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003253
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003254 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 if (F.LocalNumObjCCategoriesInMap != 0) {
3256 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003257 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003259
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003261 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003263
Guy Benyei11169dd2012-12-18 14:30:41 +00003264 case OBJC_CATEGORIES:
3265 F.ObjCCategories.swap(Record);
3266 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003267
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 case CUDA_SPECIAL_DECL_REFS:
3269 // Later tables overwrite earlier ones.
3270 // FIXME: Modules will have trouble with this.
3271 CUDASpecialDeclRefs.clear();
3272 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3273 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3274 break;
3275
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003276 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003277 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 if (Record[0]) {
3280 F.HeaderFileInfoTable
3281 = HeaderFileInfoLookupTable::Create(
3282 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3283 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003284 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003286 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003287
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 PP.getHeaderSearchInfo().SetExternalSource(this);
3289 if (!PP.getHeaderSearchInfo().getExternalLookup())
3290 PP.getHeaderSearchInfo().SetExternalLookup(this);
3291 }
3292 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003293
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 case FP_PRAGMA_OPTIONS:
3295 // Later tables overwrite earlier ones.
3296 FPPragmaOptions.swap(Record);
3297 break;
3298
3299 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003300 for (unsigned I = 0, E = Record.size(); I != E; ) {
3301 auto Name = ReadString(Record, I);
3302 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003303 Opt.Supported = Record[I++] != 0;
3304 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003305 Opt.Avail = Record[I++];
3306 Opt.Core = Record[I++];
3307 }
3308 break;
3309
3310 case OPENCL_EXTENSION_TYPES:
3311 for (unsigned I = 0, E = Record.size(); I != E;) {
3312 auto TypeID = static_cast<::TypeID>(Record[I++]);
3313 auto *Type = GetType(TypeID).getTypePtr();
3314 auto NumExt = static_cast<unsigned>(Record[I++]);
3315 for (unsigned II = 0; II != NumExt; ++II) {
3316 auto Ext = ReadString(Record, I);
3317 OpenCLTypeExtMap[Type].insert(Ext);
3318 }
3319 }
3320 break;
3321
3322 case OPENCL_EXTENSION_DECLS:
3323 for (unsigned I = 0, E = Record.size(); I != E;) {
3324 auto DeclID = static_cast<::DeclID>(Record[I++]);
3325 auto *Decl = GetDecl(DeclID);
3326 auto NumExt = static_cast<unsigned>(Record[I++]);
3327 for (unsigned II = 0; II != NumExt; ++II) {
3328 auto Ext = ReadString(Record, I);
3329 OpenCLDeclExtMap[Decl].insert(Ext);
3330 }
3331 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 break;
3333
3334 case TENTATIVE_DEFINITIONS:
3335 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3336 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3337 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003338
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 case KNOWN_NAMESPACES:
3340 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3341 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3342 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003343
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003344 case UNDEFINED_BUT_USED:
3345 if (UndefinedButUsed.size() % 2 != 0) {
3346 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003347 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003348 }
3349
3350 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003351 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003352 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003353 }
3354 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003355 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3356 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003357 ReadSourceLocation(F, Record, I).getRawEncoding());
3358 }
3359 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003360
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003361 case DELETE_EXPRS_TO_ANALYZE:
3362 for (unsigned I = 0, N = Record.size(); I != N;) {
3363 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3364 const uint64_t Count = Record[I++];
3365 DelayedDeleteExprs.push_back(Count);
3366 for (uint64_t C = 0; C < Count; ++C) {
3367 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3368 bool IsArrayForm = Record[I++] == 1;
3369 DelayedDeleteExprs.push_back(IsArrayForm);
3370 }
3371 }
3372 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003373
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003374 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003375 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 // If we aren't loading a module (which has its own exports), make
3377 // all of the imported modules visible.
3378 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003379 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3380 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3381 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003382 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003383 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003384 if (DeserializationListener)
3385 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3386 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 }
3388 }
3389 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003390
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 case MACRO_OFFSET: {
3392 if (F.LocalNumMacros != 0) {
3393 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003394 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003396 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 F.LocalNumMacros = Record[0];
3398 unsigned LocalBaseMacroID = Record[1];
3399 F.BaseMacroID = getTotalNumMacros();
3400
3401 if (F.LocalNumMacros > 0) {
3402 // Introduce the global -> local mapping for macros within this module.
3403 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3404
3405 // Introduce the local -> global mapping for macros within this module.
3406 F.MacroRemap.insertOrReplace(
3407 std::make_pair(LocalBaseMacroID,
3408 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003409
3410 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 }
3412 break;
3413 }
3414
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003415 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003416 LateParsedTemplates.append(Record.begin(), Record.end());
3417 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003418
3419 case OPTIMIZE_PRAGMA_OPTIONS:
3420 if (Record.size() != 1) {
3421 Error("invalid pragma optimize record");
3422 return Failure;
3423 }
3424 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3425 break;
Nico Weber72889432014-09-06 01:25:55 +00003426
Nico Weber779355f2016-03-02 23:22:00 +00003427 case MSSTRUCT_PRAGMA_OPTIONS:
3428 if (Record.size() != 1) {
3429 Error("invalid pragma ms_struct record");
3430 return Failure;
3431 }
3432 PragmaMSStructState = Record[0];
3433 break;
3434
Nico Weber42932312016-03-03 00:17:35 +00003435 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3436 if (Record.size() != 2) {
3437 Error("invalid pragma ms_struct record");
3438 return Failure;
3439 }
3440 PragmaMSPointersToMembersState = Record[0];
3441 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3442 break;
3443
Nico Weber72889432014-09-06 01:25:55 +00003444 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3445 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3446 UnusedLocalTypedefNameCandidates.push_back(
3447 getGlobalDeclID(F, Record[I]));
3448 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003449
3450 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3451 if (Record.size() != 1) {
3452 Error("invalid cuda pragma options record");
3453 return Failure;
3454 }
3455 ForceCUDAHostDeviceDepth = Record[0];
3456 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003457
3458 case PACK_PRAGMA_OPTIONS: {
3459 if (Record.size() < 3) {
3460 Error("invalid pragma pack record");
3461 return Failure;
3462 }
3463 PragmaPackCurrentValue = Record[0];
3464 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3465 unsigned NumStackEntries = Record[2];
3466 unsigned Idx = 3;
3467 // Reset the stack when importing a new module.
3468 PragmaPackStack.clear();
3469 for (unsigned I = 0; I < NumStackEntries; ++I) {
3470 PragmaPackStackEntry Entry;
3471 Entry.Value = Record[Idx++];
3472 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003473 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003474 PragmaPackStrings.push_back(ReadString(Record, Idx));
3475 Entry.SlotLabel = PragmaPackStrings.back();
3476 PragmaPackStack.push_back(Entry);
3477 }
3478 break;
3479 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 }
3481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003482}
3483
Richard Smith37a93df2017-02-18 00:32:02 +00003484void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3485 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3486
3487 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003488 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003489 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3490 F.ModuleOffsetMap = StringRef();
3491
3492 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3493 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3494 F.SLocRemap.insert(std::make_pair(0U, 0));
3495 F.SLocRemap.insert(std::make_pair(2U, 1));
3496 }
3497
3498 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003499 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003500 RemapBuilder SLocRemap(F.SLocRemap);
3501 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3502 RemapBuilder MacroRemap(F.MacroRemap);
3503 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3504 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3505 RemapBuilder SelectorRemap(F.SelectorRemap);
3506 RemapBuilder DeclRemap(F.DeclRemap);
3507 RemapBuilder TypeRemap(F.TypeRemap);
3508
3509 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003510 // FIXME: Looking up dependency modules by filename is horrible. Let's
3511 // start fixing this with prebuilt and explicit modules and see how it
3512 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003513 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003514 ModuleKind Kind = static_cast<ModuleKind>(
3515 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003516 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3517 StringRef Name = StringRef((const char*)Data, Len);
3518 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003519 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3520 ? ModuleMgr.lookupByModuleName(Name)
3521 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003522 if (!OM) {
3523 std::string Msg =
3524 "SourceLocation remap refers to unknown module, cannot find ";
3525 Msg.append(Name);
3526 Error(Msg);
3527 return;
3528 }
3529
3530 uint32_t SLocOffset =
3531 endian::readNext<uint32_t, little, unaligned>(Data);
3532 uint32_t IdentifierIDOffset =
3533 endian::readNext<uint32_t, little, unaligned>(Data);
3534 uint32_t MacroIDOffset =
3535 endian::readNext<uint32_t, little, unaligned>(Data);
3536 uint32_t PreprocessedEntityIDOffset =
3537 endian::readNext<uint32_t, little, unaligned>(Data);
3538 uint32_t SubmoduleIDOffset =
3539 endian::readNext<uint32_t, little, unaligned>(Data);
3540 uint32_t SelectorIDOffset =
3541 endian::readNext<uint32_t, little, unaligned>(Data);
3542 uint32_t DeclIDOffset =
3543 endian::readNext<uint32_t, little, unaligned>(Data);
3544 uint32_t TypeIndexOffset =
3545 endian::readNext<uint32_t, little, unaligned>(Data);
3546
3547 uint32_t None = std::numeric_limits<uint32_t>::max();
3548
3549 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3550 RemapBuilder &Remap) {
3551 if (Offset != None)
3552 Remap.insert(std::make_pair(Offset,
3553 static_cast<int>(BaseOffset - Offset)));
3554 };
3555 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3556 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3557 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3558 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3559 PreprocessedEntityRemap);
3560 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3561 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3562 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3563 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3564
3565 // Global -> local mappings.
3566 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3567 }
3568}
3569
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003570ASTReader::ASTReadResult
3571ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3572 const ModuleFile *ImportedBy,
3573 unsigned ClientLoadCapabilities) {
3574 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003575 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003576
3577 // Try to resolve ModuleName in the current header search context and
3578 // verify that it is found in the same module map file as we saved. If the
3579 // top-level AST file is a main file, skip this check because there is no
3580 // usable header search context.
3581 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003582 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003583 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003584 // An implicitly-loaded module file should have its module listed in some
3585 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003586 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003587 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3588 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3589 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003590 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003591 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003592 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003593 // This module was defined by an imported (explicit) module.
3594 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3595 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003596 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003597 // This module was built with a different module map.
3598 Diag(diag::err_imported_module_not_found)
3599 << F.ModuleName << F.FileName << ImportedBy->FileName
3600 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003601 // In case it was imported by a PCH, there's a chance the user is
3602 // just missing to include the search path to the directory containing
3603 // the modulemap.
3604 if (ImportedBy->Kind == MK_PCH)
3605 Diag(diag::note_imported_by_pch_module_not_found)
3606 << llvm::sys::path::parent_path(F.ModuleMapPath);
3607 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003608 }
3609 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003610 }
3611
Richard Smithe842a472014-10-22 02:05:46 +00003612 assert(M->Name == F.ModuleName && "found module with different name");
3613
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003614 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003615 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003616 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3617 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003618 assert(ImportedBy && "top-level import should be verified");
3619 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3620 Diag(diag::err_imported_module_modmap_changed)
3621 << F.ModuleName << ImportedBy->FileName
3622 << ModMap->getName() << F.ModuleMapPath;
3623 return OutOfDate;
3624 }
3625
3626 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3627 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3628 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003629 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003630 const FileEntry *F =
3631 FileMgr.getFile(Filename, false, false);
3632 if (F == nullptr) {
3633 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3634 Error("could not find file '" + Filename +"' referenced by AST file");
3635 return OutOfDate;
3636 }
3637 AdditionalStoredMaps.insert(F);
3638 }
3639
3640 // Check any additional module map files (e.g. module.private.modulemap)
3641 // that are not in the pcm.
3642 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003643 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003644 // Remove files that match
3645 // Note: SmallPtrSet::erase is really remove
3646 if (!AdditionalStoredMaps.erase(ModMap)) {
3647 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3648 Diag(diag::err_module_different_modmap)
3649 << F.ModuleName << /*new*/0 << ModMap->getName();
3650 return OutOfDate;
3651 }
3652 }
3653 }
3654
3655 // Check any additional module map files that are in the pcm, but not
3656 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003657 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003658 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3659 Diag(diag::err_module_different_modmap)
3660 << F.ModuleName << /*not new*/1 << ModMap->getName();
3661 return OutOfDate;
3662 }
3663 }
3664
3665 if (Listener)
3666 Listener->ReadModuleMapFile(F.ModuleMapPath);
3667 return Success;
3668}
3669
Douglas Gregorc1489562013-02-12 23:36:21 +00003670/// \brief Move the given method to the back of the global list of methods.
3671static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3672 // Find the entry for this selector in the method pool.
3673 Sema::GlobalMethodPool::iterator Known
3674 = S.MethodPool.find(Method->getSelector());
3675 if (Known == S.MethodPool.end())
3676 return;
3677
3678 // Retrieve the appropriate method list.
3679 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3680 : Known->second.second;
3681 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003682 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003683 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003684 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003685 Found = true;
3686 } else {
3687 // Keep searching.
3688 continue;
3689 }
3690 }
3691
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003692 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003693 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003694 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003695 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003696 }
3697}
3698
Richard Smithde711422015-04-23 21:20:19 +00003699void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003700 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003701 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003702 bool wasHidden = D->isHidden();
3703 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003704
Vedant Kumar48b4f762018-04-14 01:40:48 +00003705 if (wasHidden && SemaObj) {
3706 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003707 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003708 }
3709 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 }
3711}
3712
Richard Smith49f906a2014-03-01 00:08:04 +00003713void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003714 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003715 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003717 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003718 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003720 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003721
3722 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003723 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 // there is nothing more to do.
3725 continue;
3726 }
Richard Smith49f906a2014-03-01 00:08:04 +00003727
Guy Benyei11169dd2012-12-18 14:30:41 +00003728 if (!Mod->isAvailable()) {
3729 // Modules that aren't available cannot be made visible.
3730 continue;
3731 }
3732
3733 // Update the module's name visibility.
3734 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003735
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 // If we've already deserialized any names from this module,
3737 // mark them as visible.
3738 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3739 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003740 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003742 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003743 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3744 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003746
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003748 SmallVector<Module *, 16> Exports;
3749 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003750 for (SmallVectorImpl<Module *>::iterator
3751 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3752 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003753 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003754 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003756 }
3757}
3758
Richard Smith6561f922016-09-12 21:06:40 +00003759/// We've merged the definition \p MergedDef into the existing definition
3760/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3761/// visible.
3762void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3763 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003764 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3765 // in modules other than its owning module. We should instead give the
3766 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003767 if (Def->isHidden()) {
3768 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003769 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003770 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003771 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3772 getContext().mergeDefinitionIntoModule(
3773 Def, MergedDef->getImportedOwningModule(),
3774 /*NotifyListeners*/ false);
3775 PendingMergedDefinitionsToDeduplicate.insert(Def);
3776 } else {
3777 auto SubmoduleID = MergedDef->getOwningModuleID();
3778 assert(SubmoduleID && "hidden definition in no module");
3779 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3780 }
Richard Smith6561f922016-09-12 21:06:40 +00003781 }
3782}
3783
Douglas Gregore060e572013-01-25 01:03:03 +00003784bool ASTReader::loadGlobalIndex() {
3785 if (GlobalIndex)
3786 return false;
3787
3788 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003789 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003790 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003791
Douglas Gregore060e572013-01-25 01:03:03 +00003792 // Try to load the global index.
3793 TriedLoadingGlobalIndex = true;
3794 StringRef ModuleCachePath
3795 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3796 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003797 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003798 if (!Result.first)
3799 return true;
3800
3801 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003802 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003803 return false;
3804}
3805
3806bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003807 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003808 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3809}
3810
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003811static void updateModuleTimestamp(ModuleFile &MF) {
3812 // Overwrite the timestamp file contents so that file's mtime changes.
3813 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003814 std::error_code EC;
3815 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3816 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003817 return;
3818 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003819 OS.close();
3820 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003821}
3822
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003823/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3824/// cursor into the start of the given block ID, returning false on success and
3825/// true on failure.
3826static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003827 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003828 llvm::BitstreamEntry Entry = Cursor.advance();
3829 switch (Entry.Kind) {
3830 case llvm::BitstreamEntry::Error:
3831 case llvm::BitstreamEntry::EndBlock:
3832 return true;
3833
3834 case llvm::BitstreamEntry::Record:
3835 // Ignore top-level records.
3836 Cursor.skipRecord(Entry.ID);
3837 break;
3838
3839 case llvm::BitstreamEntry::SubBlock:
3840 if (Entry.ID == BlockID) {
3841 if (Cursor.EnterSubBlock(BlockID))
3842 return true;
3843 // Found it!
3844 return false;
3845 }
3846
3847 if (Cursor.SkipBlock())
3848 return true;
3849 }
3850 }
3851}
3852
Benjamin Kramer0772c422016-02-13 13:42:54 +00003853ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 ModuleKind Type,
3855 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003856 unsigned ClientLoadCapabilities,
3857 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003858 llvm::SaveAndRestore<SourceLocation>
3859 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3860
Richard Smithd1c46742014-04-30 02:24:17 +00003861 // Defer any pending actions until we get to the end of reading the AST file.
3862 Deserializing AnASTFile(this);
3863
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003865 unsigned PreviousGeneration = 0;
3866 if (ContextObj)
3867 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003868
3869 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003870 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003871 switch (ASTReadResult ReadResult =
3872 ReadASTCore(FileName, Type, ImportLoc,
3873 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3874 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003876 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 case OutOfDate:
3878 case VersionMismatch:
3879 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003880 case HadErrors: {
3881 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003882 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00003883 LoadedSet.insert(IM.Mod);
3884
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003885 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003886 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003887 ? &PP.getHeaderSearchInfo().getModuleMap()
3888 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003889
3890 // If we find that any modules are unusable, the global index is going
3891 // to be out-of-date. Just remove it.
3892 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003893 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003895 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 case Success:
3897 break;
3898 }
3899
3900 // Here comes stuff that we only do once the entire chain is loaded.
3901
3902 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003903 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3904 MEnd = Loaded.end();
3905 M != MEnd; ++M) {
3906 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00003907
3908 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003909 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3910 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003911
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003912 // Read the extension blocks.
3913 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3914 if (ASTReadResult Result = ReadExtensionBlock(F))
3915 return Result;
3916 }
3917
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003918 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 // bits of all files we've seen.
3920 F.GlobalBitOffset = TotalModulesSizeInBits;
3921 TotalModulesSizeInBits += F.SizeInBits;
3922 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003923
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003925 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3926 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 // Load it through the SourceManager and don't call ReadSLocEntry()
3928 // directly because the entry may have already been loaded in which case
3929 // calling ReadSLocEntry() directly would trigger an assertion in
3930 // SourceManager.
3931 SourceMgr.getLoadedSLocEntryByID(Index);
3932 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003933
Richard Smithea741482017-05-01 22:10:47 +00003934 // Map the original source file ID into the ID space of the current
3935 // compilation.
3936 if (F.OriginalSourceFileID.isValid()) {
3937 F.OriginalSourceFileID = FileID::get(
3938 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3939 }
3940
Richard Smith33e0f7e2015-07-22 02:08:40 +00003941 // Preload all the pending interesting identifiers by marking them out of
3942 // date.
3943 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003944 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00003945 F.IdentifierTableData + Offset);
3946
3947 ASTIdentifierLookupTrait Trait(*this, F);
3948 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3949 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003950 auto &II = PP.getIdentifierTable().getOwn(Key);
3951 II.setOutOfDate(true);
3952
3953 // Mark this identifier as being from an AST file so that we can track
3954 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003955 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003956
3957 // Associate the ID with the identifier so that the writer can reuse it.
3958 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3959 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 }
3962
Douglas Gregor603cd862013-03-22 18:50:14 +00003963 // Setup the import locations and notify the module manager that we've
3964 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003965 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3966 MEnd = Loaded.end();
3967 M != MEnd; ++M) {
3968 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003969
3970 ModuleMgr.moduleFileAccepted(&F);
3971
3972 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003973 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003974 // FIXME: We assume that locations from PCH / preamble do not need
3975 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003976 if (!M->ImportedBy)
3977 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00003979 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 }
3981
Richard Smithdbafb6c2017-06-29 23:23:46 +00003982 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003983 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3984 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003985 // Mark all of the identifiers in the identifier table as being out of date,
3986 // so that various accessors know to check the loaded modules when the
3987 // identifier is used.
3988 //
3989 // For C++ modules, we don't need information on many identifiers (just
3990 // those that provide macros or are poisoned), so we mark all of
3991 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003992 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3993 IdEnd = PP.getIdentifierTable().end();
3994 Id != IdEnd; ++Id)
3995 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003996 }
Manman Rena0f31a02016-04-29 19:04:05 +00003997 // Mark selectors as out of date.
3998 for (auto Sel : SelectorGeneration)
3999 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004000
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004002 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4003 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4005 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004006
4007 switch (Unresolved.Kind) {
4008 case UnresolvedModuleRef::Conflict:
4009 if (ResolvedMod) {
4010 Module::Conflict Conflict;
4011 Conflict.Other = ResolvedMod;
4012 Conflict.Message = Unresolved.String.str();
4013 Unresolved.Mod->Conflicts.push_back(Conflict);
4014 }
4015 continue;
4016
4017 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004019 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004021
Douglas Gregorfb912652013-03-20 21:10:35 +00004022 case UnresolvedModuleRef::Export:
4023 if (ResolvedMod || Unresolved.IsWildcard)
4024 Unresolved.Mod->Exports.push_back(
4025 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4026 continue;
4027 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004029 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004030
Graydon Hoaree7196af2016-12-09 21:45:49 +00004031 if (Imported)
4032 Imported->append(ImportedModules.begin(),
4033 ImportedModules.end());
4034
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004035 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4036 // Might be unnecessary as use declarations are only used to build the
4037 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004038
Richard Smithdbafb6c2017-06-29 23:23:46 +00004039 if (ContextObj)
4040 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004041
Richard Smith3d8e97e2013-10-18 06:54:39 +00004042 if (SemaObj)
4043 UpdateSema();
4044
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 if (DeserializationListener)
4046 DeserializationListener->ReaderInitialized(this);
4047
4048 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004049 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 // If this AST file is a precompiled preamble, then set the
4051 // preamble file ID of the source manager to the file source file
4052 // from which the preamble was built.
4053 if (Type == MK_Preamble) {
4054 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4055 } else if (Type == MK_MainFile) {
4056 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4057 }
4058 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004059
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 // For any Objective-C class definitions we have already loaded, make sure
4061 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004062 if (ContextObj) {
4063 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4064 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4065 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004066 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004067 }
4068 }
Douglas Gregore060e572013-01-25 01:03:03 +00004069
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004070 if (PP.getHeaderSearchInfo()
4071 .getHeaderSearchOpts()
4072 .ModulesValidateOncePerBuildSession) {
4073 // Now we are certain that the module and all modules it depends on are
4074 // up to date. Create or update timestamp files for modules that are
4075 // located in the module cache (not for PCH files that could be anywhere
4076 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004077 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4078 ImportedModule &M = Loaded[I];
4079 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004080 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004081 }
4082 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004083 }
4084
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 return Success;
4086}
4087
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004088static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004089
Ben Langmuir70a1b812015-03-24 04:43:52 +00004090/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
4091static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004092 return Stream.canSkipToPos(4) &&
4093 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004094 Stream.Read(8) == 'P' &&
4095 Stream.Read(8) == 'C' &&
4096 Stream.Read(8) == 'H';
4097}
4098
Richard Smith0f99d6a2015-08-09 08:48:41 +00004099static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4100 switch (Kind) {
4101 case MK_PCH:
4102 return 0; // PCH
4103 case MK_ImplicitModule:
4104 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004105 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004106 return 1; // module
4107 case MK_MainFile:
4108 case MK_Preamble:
4109 return 2; // main source file
4110 }
4111 llvm_unreachable("unknown module kind");
4112}
4113
Guy Benyei11169dd2012-12-18 14:30:41 +00004114ASTReader::ASTReadResult
4115ASTReader::ReadASTCore(StringRef FileName,
4116 ModuleKind Type,
4117 SourceLocation ImportLoc,
4118 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004119 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004120 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004121 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 unsigned ClientLoadCapabilities) {
4123 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004125 ModuleManager::AddModuleResult AddResult
4126 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004127 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004128 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004129 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004130
Douglas Gregor7029ce12013-03-19 00:28:20 +00004131 switch (AddResult) {
4132 case ModuleManager::AlreadyLoaded:
4133 return Success;
4134
4135 case ModuleManager::NewlyLoaded:
4136 // Load module file below.
4137 break;
4138
4139 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004140 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004141 // it.
4142 if (ClientLoadCapabilities & ARR_Missing)
4143 return Missing;
4144
4145 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004146 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004147 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004148 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004149 return Failure;
4150
4151 case ModuleManager::OutOfDate:
4152 // We couldn't load the module file because it is out-of-date. If the
4153 // client can handle out-of-date, return it.
4154 if (ClientLoadCapabilities & ARR_OutOfDate)
4155 return OutOfDate;
4156
4157 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004158 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004159 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004160 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 return Failure;
4162 }
4163
Douglas Gregor7029ce12013-03-19 00:28:20 +00004164 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004165
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004167 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004168 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004169 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004170
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004172 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004173 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4174 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 return Failure;
4176 }
4177
4178 // This is used for compatibility with older PCH formats.
4179 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004180 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004181 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004182
Chris Lattnerefa77172013-01-20 00:00:22 +00004183 switch (Entry.Kind) {
4184 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004185 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004186 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 Error("invalid record at top-level of AST file");
4188 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004189
Chris Lattnerefa77172013-01-20 00:00:22 +00004190 case llvm::BitstreamEntry::SubBlock:
4191 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 }
4193
Chris Lattnerefa77172013-01-20 00:00:22 +00004194 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 case CONTROL_BLOCK_ID:
4196 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004197 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004199 // Check that we didn't try to load a non-module AST file as a module.
4200 //
4201 // FIXME: Should we also perform the converse check? Loading a module as
4202 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004203 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4204 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004205 F.ModuleName.empty()) {
4206 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4207 if (Result != OutOfDate ||
4208 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4209 Diag(diag::err_module_file_not_module) << FileName;
4210 return Result;
4211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 break;
4213
4214 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004215 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 case OutOfDate: return OutOfDate;
4217 case VersionMismatch: return VersionMismatch;
4218 case ConfigurationMismatch: return ConfigurationMismatch;
4219 case HadErrors: return HadErrors;
4220 }
4221 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004222
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 case AST_BLOCK_ID:
4224 if (!HaveReadControlBlock) {
4225 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004226 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 return VersionMismatch;
4228 }
4229
4230 // Record that we've loaded this module.
4231 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4232 return Success;
4233
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004234 case UNHASHED_CONTROL_BLOCK_ID:
4235 // This block is handled using look-ahead during ReadControlBlock. We
4236 // shouldn't get here!
4237 Error("malformed block record in AST file");
4238 return Failure;
4239
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 default:
4241 if (Stream.SkipBlock()) {
4242 Error("malformed block record in AST file");
4243 return Failure;
4244 }
4245 break;
4246 }
4247 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004248
4249 return Success;
4250}
4251
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004252ASTReader::ASTReadResult
4253ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4254 unsigned ClientLoadCapabilities) {
4255 const HeaderSearchOptions &HSOpts =
4256 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4257 bool AllowCompatibleConfigurationMismatch =
4258 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4259
4260 ASTReadResult Result = readUnhashedControlBlockImpl(
4261 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4262 Listener.get(),
4263 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4264
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004265 // If F was directly imported by another module, it's implicitly validated by
4266 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004267 if (DisableValidation || WasImportedBy ||
4268 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4269 return Success;
4270
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004271 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004272 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004273 return Failure;
4274 }
4275
4276 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4277 // If this module has already been finalized in the PCMCache, we're stuck
4278 // with it; we can only load a single version of each module.
4279 //
4280 // This can happen when a module is imported in two contexts: in one, as a
4281 // user module; in another, as a system module (due to an import from
4282 // another module marked with the [system] flag). It usually indicates a
4283 // bug in the module map: this module should also be marked with [system].
4284 //
4285 // If -Wno-system-headers (the default), and the first import is as a
4286 // system module, then validation will fail during the as-user import,
4287 // since -Werror flags won't have been validated. However, it's reasonable
4288 // to treat this consistently as a system module.
4289 //
4290 // If -Wsystem-headers, the PCM on disk was built with
4291 // -Wno-system-headers, and the first import is as a user module, then
4292 // validation will fail during the as-system import since the PCM on disk
4293 // doesn't guarantee that -Werror was respected. However, the -Werror
4294 // flags were checked during the initial as-user import.
4295 if (PCMCache.isBufferFinal(F.FileName)) {
4296 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4297 return Success;
4298 }
4299 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004300
4301 return Result;
4302}
4303
4304ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4305 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4306 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4307 bool ValidateDiagnosticOptions) {
4308 // Initialize a stream.
4309 BitstreamCursor Stream(StreamData);
4310
4311 // Sniff for the signature.
4312 if (!startsWithASTFileMagic(Stream))
4313 return Failure;
4314
4315 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4316 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4317 return Failure;
4318
4319 // Read all of the records in the options block.
4320 RecordData Record;
4321 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004322 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004323 llvm::BitstreamEntry Entry = Stream.advance();
4324
4325 switch (Entry.Kind) {
4326 case llvm::BitstreamEntry::Error:
4327 case llvm::BitstreamEntry::SubBlock:
4328 return Failure;
4329
4330 case llvm::BitstreamEntry::EndBlock:
4331 return Result;
4332
4333 case llvm::BitstreamEntry::Record:
4334 // The interesting case.
4335 break;
4336 }
4337
4338 // Read and process a record.
4339 Record.clear();
4340 switch (
4341 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004342 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004343 if (F)
4344 std::copy(Record.begin(), Record.end(), F->Signature.data());
4345 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004346 case DIAGNOSTIC_OPTIONS: {
4347 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4348 if (Listener && ValidateDiagnosticOptions &&
4349 !AllowCompatibleConfigurationMismatch &&
4350 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004351 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004352 break;
4353 }
4354 case DIAG_PRAGMA_MAPPINGS:
4355 if (!F)
4356 break;
4357 if (F->PragmaDiagMappings.empty())
4358 F->PragmaDiagMappings.swap(Record);
4359 else
4360 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4361 Record.begin(), Record.end());
4362 break;
4363 }
4364 }
4365}
4366
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004367/// Parse a record and blob containing module file extension metadata.
4368static bool parseModuleFileExtensionMetadata(
4369 const SmallVectorImpl<uint64_t> &Record,
4370 StringRef Blob,
4371 ModuleFileExtensionMetadata &Metadata) {
4372 if (Record.size() < 4) return true;
4373
4374 Metadata.MajorVersion = Record[0];
4375 Metadata.MinorVersion = Record[1];
4376
4377 unsigned BlockNameLen = Record[2];
4378 unsigned UserInfoLen = Record[3];
4379
4380 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4381
4382 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4383 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4384 Blob.data() + BlockNameLen + UserInfoLen);
4385 return false;
4386}
4387
4388ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4389 BitstreamCursor &Stream = F.Stream;
4390
4391 RecordData Record;
4392 while (true) {
4393 llvm::BitstreamEntry Entry = Stream.advance();
4394 switch (Entry.Kind) {
4395 case llvm::BitstreamEntry::SubBlock:
4396 if (Stream.SkipBlock())
4397 return Failure;
4398
4399 continue;
4400
4401 case llvm::BitstreamEntry::EndBlock:
4402 return Success;
4403
4404 case llvm::BitstreamEntry::Error:
4405 return HadErrors;
4406
4407 case llvm::BitstreamEntry::Record:
4408 break;
4409 }
4410
4411 Record.clear();
4412 StringRef Blob;
4413 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4414 switch (RecCode) {
4415 case EXTENSION_METADATA: {
4416 ModuleFileExtensionMetadata Metadata;
4417 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4418 return Failure;
4419
4420 // Find a module file extension with this block name.
4421 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4422 if (Known == ModuleFileExtensions.end()) break;
4423
4424 // Form a reader.
4425 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4426 F, Stream)) {
4427 F.ExtensionReaders.push_back(std::move(Reader));
4428 }
4429
4430 break;
4431 }
4432 }
4433 }
4434
4435 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004436}
4437
Richard Smitha7e2cc62015-05-01 01:53:09 +00004438void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004439 assert(ContextObj && "no context to initialize");
4440 ASTContext &Context = *ContextObj;
4441
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 // If there's a listener, notify them that we "read" the translation unit.
4443 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004444 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 Context.getTranslationUnitDecl());
4446
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 // FIXME: Find a better way to deal with collisions between these
4448 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004449
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 // Load the special types.
4451 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4452 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4453 if (!Context.CFConstantStringTypeDecl)
4454 Context.setCFConstantStringType(GetType(String));
4455 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004456
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4458 QualType FileType = GetType(File);
4459 if (FileType.isNull()) {
4460 Error("FILE type is NULL");
4461 return;
4462 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004463
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004465 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 Context.setFILEDecl(Typedef->getDecl());
4467 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004468 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 if (!Tag) {
4470 Error("Invalid FILE type in AST file");
4471 return;
4472 }
4473 Context.setFILEDecl(Tag->getDecl());
4474 }
4475 }
4476 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004477
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4479 QualType Jmp_bufType = GetType(Jmp_buf);
4480 if (Jmp_bufType.isNull()) {
4481 Error("jmp_buf type is NULL");
4482 return;
4483 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004484
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004486 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 Context.setjmp_bufDecl(Typedef->getDecl());
4488 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004489 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 if (!Tag) {
4491 Error("Invalid jmp_buf type in AST file");
4492 return;
4493 }
4494 Context.setjmp_bufDecl(Tag->getDecl());
4495 }
4496 }
4497 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004498
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4500 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4501 if (Sigjmp_bufType.isNull()) {
4502 Error("sigjmp_buf type is NULL");
4503 return;
4504 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004505
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004507 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 Context.setsigjmp_bufDecl(Typedef->getDecl());
4509 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004510 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 assert(Tag && "Invalid sigjmp_buf type in AST file");
4512 Context.setsigjmp_bufDecl(Tag->getDecl());
4513 }
4514 }
4515 }
4516
4517 if (unsigned ObjCIdRedef
4518 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4519 if (Context.ObjCIdRedefinitionType.isNull())
4520 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4521 }
4522
4523 if (unsigned ObjCClassRedef
4524 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4525 if (Context.ObjCClassRedefinitionType.isNull())
4526 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4527 }
4528
4529 if (unsigned ObjCSelRedef
4530 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4531 if (Context.ObjCSelRedefinitionType.isNull())
4532 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4533 }
4534
4535 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4536 QualType Ucontext_tType = GetType(Ucontext_t);
4537 if (Ucontext_tType.isNull()) {
4538 Error("ucontext_t type is NULL");
4539 return;
4540 }
4541
4542 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004543 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 Context.setucontext_tDecl(Typedef->getDecl());
4545 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004546 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 assert(Tag && "Invalid ucontext_t type in AST file");
4548 Context.setucontext_tDecl(Tag->getDecl());
4549 }
4550 }
4551 }
4552 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004553
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4555
4556 // If there were any CUDA special declarations, deserialize them.
4557 if (!CUDASpecialDeclRefs.empty()) {
4558 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4559 Context.setcudaConfigureCallDecl(
4560 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4561 }
Richard Smith56be7542014-03-21 00:33:59 +00004562
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004564 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004565 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004566 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004567 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004568 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004569 if (Import.ImportLoc.isValid())
4570 PP.makeModuleVisible(Imported, Import.ImportLoc);
4571 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
4574 ImportedModules.clear();
4575}
4576
4577void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004578 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004579}
4580
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004581/// \brief Reads and return the signature record from \p PCH's control block, or
4582/// else returns 0.
4583static ASTFileSignature readASTFileSignature(StringRef PCH) {
4584 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004585 if (!startsWithASTFileMagic(Stream))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004586 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004587
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004588 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4589 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004590 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004591
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004592 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004593 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004594 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004595 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004596 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004597 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004598
4599 Record.clear();
4600 StringRef Blob;
4601 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004602 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4603 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004604 }
4605}
4606
Guy Benyei11169dd2012-12-18 14:30:41 +00004607/// \brief Retrieve the name of the original source file name
4608/// directly from the AST file, without actually loading the AST
4609/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004610std::string ASTReader::getOriginalSourceFile(
4611 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004612 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004614 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004616 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4617 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004618 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
4620
4621 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004622 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004623
4624 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004625 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004627 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004629
Chris Lattnere7b154b2013-01-19 21:39:22 +00004630 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004631 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004632 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004633 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004635
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004636 // Scan for ORIGINAL_FILE inside the control block.
4637 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004638 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004639 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004640 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004641 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004642
Chris Lattnere7b154b2013-01-19 21:39:22 +00004643 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4644 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004645 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004647
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004649 StringRef Blob;
4650 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4651 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004653}
4654
4655namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004656
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 class SimplePCHValidator : public ASTReaderListener {
4658 const LangOptions &ExistingLangOpts;
4659 const TargetOptions &ExistingTargetOpts;
4660 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004661 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004663
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 public:
4665 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4666 const TargetOptions &ExistingTargetOpts,
4667 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004668 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 FileManager &FileMgr)
4670 : ExistingLangOpts(ExistingLangOpts),
4671 ExistingTargetOpts(ExistingTargetOpts),
4672 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004673 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004674 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004675
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004676 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4677 bool AllowCompatibleDifferences) override {
4678 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4679 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004681
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004682 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4683 bool AllowCompatibleDifferences) override {
4684 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4685 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004687
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004688 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4689 StringRef SpecificModuleCachePath,
4690 bool Complain) override {
4691 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4692 ExistingModuleCachePath,
4693 nullptr, ExistingLangOpts);
4694 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004695
Craig Topper3e89dfe2014-03-13 02:13:41 +00004696 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4697 bool Complain,
4698 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004699 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004700 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 }
4702 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004703
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004704} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004705
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004706bool ASTReader::readASTFileControlBlock(
4707 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004708 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004709 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004710 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004712 // FIXME: This allows use of the VFS; we do not allow use of the
4713 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004714 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 if (!Buffer) {
4716 return true;
4717 }
4718
4719 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004720 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4721 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004722
4723 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004724 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004726
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004727 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004728 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004729 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004730
4731 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004732 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004733 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004734 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004735
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004737 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004738 bool DoneWithControlBlock = false;
4739 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004740 llvm::BitstreamEntry Entry = Stream.advance();
4741
4742 switch (Entry.Kind) {
4743 case llvm::BitstreamEntry::SubBlock: {
4744 switch (Entry.ID) {
4745 case OPTIONS_BLOCK_ID: {
4746 std::string IgnoredSuggestedPredefines;
4747 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4748 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004749 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004750 return true;
4751 break;
4752 }
4753
4754 case INPUT_FILES_BLOCK_ID:
4755 InputFilesCursor = Stream;
4756 if (Stream.SkipBlock() ||
4757 (NeedsInputFiles &&
4758 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4759 return true;
4760 break;
4761
4762 default:
4763 if (Stream.SkipBlock())
4764 return true;
4765 break;
4766 }
4767
4768 continue;
4769 }
4770
4771 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004772 DoneWithControlBlock = true;
4773 break;
Richard Smith0516b182015-09-08 19:40:14 +00004774
4775 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004776 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004777
4778 case llvm::BitstreamEntry::Record:
4779 break;
4780 }
4781
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004782 if (DoneWithControlBlock) break;
4783
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004785 StringRef Blob;
4786 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004787 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004788 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004789 if (Record[0] != VERSION_MAJOR)
4790 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004791 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004792 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004793 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004794 case MODULE_NAME:
4795 Listener.ReadModuleName(Blob);
4796 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004797 case MODULE_DIRECTORY:
4798 ModuleDir = Blob;
4799 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004800 case MODULE_MAP_FILE: {
4801 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004802 auto Path = ReadString(Record, Idx);
4803 ResolveImportedPath(Path, ModuleDir);
4804 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004805 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004806 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004807 case INPUT_FILE_OFFSETS: {
4808 if (!NeedsInputFiles)
4809 break;
4810
4811 unsigned NumInputFiles = Record[0];
4812 unsigned NumUserFiles = Record[1];
Vedant Kumar48b4f762018-04-14 01:40:48 +00004813 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004814 for (unsigned I = 0; I != NumInputFiles; ++I) {
4815 // Go find this input file.
4816 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004817
4818 if (isSystemFile && !NeedsSystemInputFiles)
4819 break; // the rest are system input files
4820
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004821 BitstreamCursor &Cursor = InputFilesCursor;
4822 SavedStreamPosition SavedPosition(Cursor);
4823 Cursor.JumpToBit(InputFileOffs[I]);
4824
4825 unsigned Code = Cursor.ReadCode();
4826 RecordData Record;
4827 StringRef Blob;
4828 bool shouldContinue = false;
4829 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4830 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00004831 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004832 std::string Filename = Blob;
4833 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004834 shouldContinue = Listener.visitInputFile(
4835 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004836 break;
4837 }
4838 if (!shouldContinue)
4839 break;
4840 }
4841 break;
4842 }
4843
Richard Smithd4b230b2014-10-27 23:01:16 +00004844 case IMPORTS: {
4845 if (!NeedsImports)
4846 break;
4847
4848 unsigned Idx = 0, N = Record.size();
4849 while (Idx < N) {
4850 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004851 Idx += 5; // ImportLoc, Size, ModTime, Signature
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004852 SkipString(Record, Idx); // Module name; FIXME: pass to listener?
Richard Smith7ed1bc92014-12-05 22:42:13 +00004853 std::string Filename = ReadString(Record, Idx);
4854 ResolveImportedPath(Filename, ModuleDir);
4855 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004856 }
4857 break;
4858 }
4859
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004860 default:
4861 // No other validation to perform.
4862 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 }
4864 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004865
4866 // Look for module file extension blocks, if requested.
4867 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004868 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004869 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4870 bool DoneWithExtensionBlock = false;
4871 while (!DoneWithExtensionBlock) {
4872 llvm::BitstreamEntry Entry = Stream.advance();
4873
4874 switch (Entry.Kind) {
4875 case llvm::BitstreamEntry::SubBlock:
4876 if (Stream.SkipBlock())
4877 return true;
4878
4879 continue;
4880
4881 case llvm::BitstreamEntry::EndBlock:
4882 DoneWithExtensionBlock = true;
4883 continue;
4884
4885 case llvm::BitstreamEntry::Error:
4886 return true;
4887
4888 case llvm::BitstreamEntry::Record:
4889 break;
4890 }
4891
4892 Record.clear();
4893 StringRef Blob;
4894 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4895 switch (RecCode) {
4896 case EXTENSION_METADATA: {
4897 ModuleFileExtensionMetadata Metadata;
4898 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4899 return true;
4900
4901 Listener.readModuleFileExtension(Metadata);
4902 break;
4903 }
4904 }
4905 }
4906 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004907 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004908 }
4909
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004910 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4911 if (readUnhashedControlBlockImpl(
4912 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4913 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4914 ValidateDiagnosticOptions) != Success)
4915 return true;
4916
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004917 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004918}
4919
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004920bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4921 const PCHContainerReader &PCHContainerRdr,
4922 const LangOptions &LangOpts,
4923 const TargetOptions &TargetOpts,
4924 const PreprocessorOptions &PPOpts,
4925 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004926 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4927 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004928 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004929 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004930 validator,
4931 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004932}
4933
Ben Langmuir2c9af442014-04-10 17:57:43 +00004934ASTReader::ASTReadResult
4935ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 // Enter the submodule block.
4937 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4938 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004939 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 }
4941
4942 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4943 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004944 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 RecordData Record;
4946 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004947 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004948
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004949 switch (Entry.Kind) {
4950 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4951 case llvm::BitstreamEntry::Error:
4952 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004953 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004954 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004955 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004956 case llvm::BitstreamEntry::Record:
4957 // The interesting case.
4958 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004960
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004962 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004964 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4965
4966 if ((Kind == SUBMODULE_METADATA) != First) {
4967 Error("submodule metadata record should be at beginning of block");
4968 return Failure;
4969 }
4970 First = false;
4971
4972 // Submodule information is only valid if we have a current module.
4973 // FIXME: Should we error on these cases?
4974 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4975 Kind != SUBMODULE_DEFINITION)
4976 continue;
4977
4978 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 default: // Default behavior: ignore.
4980 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004981
Richard Smith03478d92014-10-23 22:12:14 +00004982 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004983 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004985 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 }
Richard Smith03478d92014-10-23 22:12:14 +00004987
Chris Lattner0e6c9402013-01-20 02:38:54 +00004988 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004989 unsigned Idx = 0;
4990 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4991 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004992 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00004993 bool IsFramework = Record[Idx++];
4994 bool IsExplicit = Record[Idx++];
4995 bool IsSystem = Record[Idx++];
4996 bool IsExternC = Record[Idx++];
4997 bool InferSubmodules = Record[Idx++];
4998 bool InferExplicitSubmodules = Record[Idx++];
4999 bool InferExportWildcard = Record[Idx++];
5000 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005001
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005002 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005003 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005005
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 // Retrieve this (sub)module from the module map, creating it if
5007 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005008 CurrentModule =
5009 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5010 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005011
5012 // FIXME: set the definition loc for CurrentModule, or call
5013 // ModMap.setInferredModuleAllowedBy()
5014
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5016 if (GlobalIndex >= SubmodulesLoaded.size() ||
5017 SubmodulesLoaded[GlobalIndex]) {
5018 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005021
Douglas Gregor7029ce12013-03-19 00:28:20 +00005022 if (!ParentModule) {
5023 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5024 if (CurFile != F.File) {
5025 if (!Diags.isDiagnosticInFlight()) {
5026 Diag(diag::err_module_file_conflict)
5027 << CurrentModule->getTopLevelModuleName()
5028 << CurFile->getName()
5029 << F.File->getName();
5030 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005031 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005032 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005033 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005034
5035 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005036 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005037 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005038
Richard Smithdd8b5332017-09-04 05:37:53 +00005039 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005040 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 CurrentModule->IsFromModuleFile = true;
5042 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005043 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 CurrentModule->InferSubmodules = InferSubmodules;
5045 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5046 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005047 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 if (DeserializationListener)
5049 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005050
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005052
Richard Smith8a3e39a2016-03-28 21:31:09 +00005053 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005054 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005055 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005056 CurrentModule->UnresolvedConflicts.clear();
5057 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005058
5059 // The module is available unless it's missing a requirement; relevant
5060 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5061 // Missing headers that were present when the module was built do not
5062 // make it unavailable -- if we got this far, this must be an explicitly
5063 // imported module file.
5064 CurrentModule->Requirements.clear();
5065 CurrentModule->MissingHeaders.clear();
5066 CurrentModule->IsMissingRequirement =
5067 ParentModule && ParentModule->IsMissingRequirement;
5068 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 break;
5070 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005071
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005073 std::string Filename = Blob;
5074 ResolveImportedPath(F, Filename);
5075 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005077 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5078 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005079 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5080 Error("mismatched umbrella headers in submodule");
5081 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 }
5083 }
5084 break;
5085 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005086
Richard Smith202210b2014-10-24 20:23:01 +00005087 case SUBMODULE_HEADER:
5088 case SUBMODULE_EXCLUDED_HEADER:
5089 case SUBMODULE_PRIVATE_HEADER:
5090 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005091 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5092 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005093 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005094
Richard Smith202210b2014-10-24 20:23:01 +00005095 case SUBMODULE_TEXTUAL_HEADER:
5096 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5097 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5098 // them here.
5099 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005100
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005101 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005102 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005104
5105 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005106 std::string Dirname = Blob;
5107 ResolveImportedPath(F, Dirname);
5108 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005110 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5111 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005112 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5113 Error("mismatched umbrella directories in submodule");
5114 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 }
5116 }
5117 break;
5118 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005119
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 F.BaseSubmoduleID = getTotalNumSubmodules();
5122 F.LocalNumSubmodules = Record[0];
5123 unsigned LocalBaseSubmoduleID = Record[1];
5124 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005125 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 // module.
5127 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005128
5129 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 // module.
5131 F.SubmoduleRemap.insertOrReplace(
5132 std::make_pair(LocalBaseSubmoduleID,
5133 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005134
Ben Langmuir52ca6782014-10-20 16:27:32 +00005135 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5136 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 break;
5138 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005139
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005140 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005142 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 Unresolved.File = &F;
5144 Unresolved.Mod = CurrentModule;
5145 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005146 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005148 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 }
5150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005151
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005152 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005154 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 Unresolved.File = &F;
5156 Unresolved.Mod = CurrentModule;
5157 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005158 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005160 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005162
5163 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 // the parsed, unresolved exports around.
5165 CurrentModule->UnresolvedExports.clear();
5166 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005167
5168 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005169 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5170 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005172
5173 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005174 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005175 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005176 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005177 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005178
5179 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005180 CurrentModule->ConfigMacros.push_back(Blob.str());
5181 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005182
5183 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005184 UnresolvedModuleRef Unresolved;
5185 Unresolved.File = &F;
5186 Unresolved.Mod = CurrentModule;
5187 Unresolved.ID = Record[0];
5188 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5189 Unresolved.IsWildcard = false;
5190 Unresolved.String = Blob;
5191 UnresolvedModuleRefs.push_back(Unresolved);
5192 break;
5193 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005194
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005195 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005196 if (!ContextObj)
5197 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005198 SmallVector<uint32_t, 16> Inits;
5199 for (auto &ID : Record)
5200 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005201 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005202 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005204
5205 case SUBMODULE_EXPORT_AS:
5206 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005207 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005208 break;
5209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 }
5211}
5212
5213/// \brief Parse the record that corresponds to a LangOptions data
5214/// structure.
5215///
5216/// This routine parses the language options from the AST file and then gives
5217/// them to the AST listener if one is set.
5218///
5219/// \returns true if the listener deems the file unacceptable, false otherwise.
5220bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5221 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005222 ASTReaderListener &Listener,
5223 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 LangOptions LangOpts;
5225 unsigned Idx = 0;
5226#define LANGOPT(Name, Bits, Default, Description) \
5227 LangOpts.Name = Record[Idx++];
5228#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5229 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5230#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005231#define SANITIZER(NAME, ID) \
5232 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005233#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005234
Ben Langmuircd98cb72015-06-23 18:20:18 +00005235 for (unsigned N = Record[Idx++]; N; --N)
5236 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5237
Vedant Kumar48b4f762018-04-14 01:40:48 +00005238 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5240 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005241
Ben Langmuird4a667a2015-06-23 18:20:23 +00005242 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005243
5244 // Comment options.
5245 for (unsigned N = Record[Idx++]; N; --N) {
5246 LangOpts.CommentOpts.BlockCommandNames.push_back(
5247 ReadString(Record, Idx));
5248 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005249 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005250
Samuel Antaoee8fb302016-01-06 13:42:12 +00005251 // OpenMP offloading options.
5252 for (unsigned N = Record[Idx++]; N; --N) {
5253 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5254 }
5255
5256 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5257
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005258 return Listener.ReadLanguageOptions(LangOpts, Complain,
5259 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005260}
5261
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005262bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5263 ASTReaderListener &Listener,
5264 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 unsigned Idx = 0;
5266 TargetOptions TargetOpts;
5267 TargetOpts.Triple = ReadString(Record, Idx);
5268 TargetOpts.CPU = ReadString(Record, Idx);
5269 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 for (unsigned N = Record[Idx++]; N; --N) {
5271 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5272 }
5273 for (unsigned N = Record[Idx++]; N; --N) {
5274 TargetOpts.Features.push_back(ReadString(Record, Idx));
5275 }
5276
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005277 return Listener.ReadTargetOptions(TargetOpts, Complain,
5278 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005279}
5280
5281bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5282 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005283 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005285#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005286#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005287 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005288#include "clang/Basic/DiagnosticOptions.def"
5289
Richard Smith3be1cb22014-08-07 00:24:21 +00005290 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005291 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005292 for (unsigned N = Record[Idx++]; N; --N)
5293 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005294
5295 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5296}
5297
5298bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5299 ASTReaderListener &Listener) {
5300 FileSystemOptions FSOpts;
5301 unsigned Idx = 0;
5302 FSOpts.WorkingDir = ReadString(Record, Idx);
5303 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5304}
5305
5306bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5307 bool Complain,
5308 ASTReaderListener &Listener) {
5309 HeaderSearchOptions HSOpts;
5310 unsigned Idx = 0;
5311 HSOpts.Sysroot = ReadString(Record, Idx);
5312
5313 // Include entries.
5314 for (unsigned N = Record[Idx++]; N; --N) {
5315 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005316 frontend::IncludeDirGroup Group
5317 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 bool IsFramework = Record[Idx++];
5319 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005320 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5321 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 }
5323
5324 // System header prefixes.
5325 for (unsigned N = Record[Idx++]; N; --N) {
5326 std::string Prefix = ReadString(Record, Idx);
5327 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005328 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 }
5330
5331 HSOpts.ResourceDir = ReadString(Record, Idx);
5332 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005333 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005335 HSOpts.ImplicitModuleMaps = Record[Idx++];
5336 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 HSOpts.UseBuiltinIncludes = Record[Idx++];
5338 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5339 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5340 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005341 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005342
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005343 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5344 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005345}
5346
5347bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5348 bool Complain,
5349 ASTReaderListener &Listener,
5350 std::string &SuggestedPredefines) {
5351 PreprocessorOptions PPOpts;
5352 unsigned Idx = 0;
5353
5354 // Macro definitions/undefs
5355 for (unsigned N = Record[Idx++]; N; --N) {
5356 std::string Macro = ReadString(Record, Idx);
5357 bool IsUndef = Record[Idx++];
5358 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5359 }
5360
5361 // Includes
5362 for (unsigned N = Record[Idx++]; N; --N) {
5363 PPOpts.Includes.push_back(ReadString(Record, Idx));
5364 }
5365
5366 // Macro Includes
5367 for (unsigned N = Record[Idx++]; N; --N) {
5368 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5369 }
5370
5371 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005372 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5374 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5375 PPOpts.ObjCXXARCStandardLibrary =
5376 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5377 SuggestedPredefines.clear();
5378 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5379 SuggestedPredefines);
5380}
5381
5382std::pair<ModuleFile *, unsigned>
5383ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5384 GlobalPreprocessedEntityMapType::iterator
5385 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005386 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 "Corrupted global preprocessed entity map");
5388 ModuleFile *M = I->second;
5389 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5390 return std::make_pair(M, LocalIndex);
5391}
5392
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005393llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005394ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5395 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5396 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5397 Mod.NumPreprocessedEntities);
5398
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005399 return llvm::make_range(PreprocessingRecord::iterator(),
5400 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005401}
5402
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005403llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005404ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005405 return llvm::make_range(
5406 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5407 ModuleDeclIterator(this, &Mod,
5408 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005409}
5410
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005411SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5412 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5413 assert(I != GlobalSkippedRangeMap.end() &&
5414 "Corrupted global skipped range map");
5415 ModuleFile *M = I->second;
5416 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5417 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5418 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5419 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5420 TranslateSourceLocation(*M, RawRange.getEnd()));
5421 assert(Range.isValid());
5422 return Range;
5423}
5424
Guy Benyei11169dd2012-12-18 14:30:41 +00005425PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5426 PreprocessedEntityID PPID = Index+1;
5427 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5428 ModuleFile &M = *PPInfo.first;
5429 unsigned LocalIndex = PPInfo.second;
5430 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5431
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 if (!PP.getPreprocessingRecord()) {
5433 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005434 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005436
5437 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005438 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5439
5440 llvm::BitstreamEntry Entry =
5441 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5442 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005443 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005444
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005446 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5447 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005449 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 RecordData Record;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005451 PreprocessorDetailRecordTypes RecType =
5452 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5453 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 switch (RecType) {
5455 case PPD_MACRO_EXPANSION: {
5456 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005457 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005458 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 if (isBuiltin)
5460 Name = getLocalIdentifier(M, Record[1]);
5461 else {
Richard Smith66a81862015-05-04 02:25:31 +00005462 PreprocessedEntityID GlobalID =
5463 getGlobalPreprocessedEntityID(M, Record[1]);
5464 Def = cast<MacroDefinitionRecord>(
5465 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 }
5467
5468 MacroExpansion *ME;
5469 if (isBuiltin)
5470 ME = new (PPRec) MacroExpansion(Name, Range);
5471 else
5472 ME = new (PPRec) MacroExpansion(Def, Range);
5473
5474 return ME;
5475 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005476
Guy Benyei11169dd2012-12-18 14:30:41 +00005477 case PPD_MACRO_DEFINITION: {
5478 // Decode the identifier info and then check again; if the macro is
5479 // still defined and associated with the identifier,
5480 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005481 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005482
5483 if (DeserializationListener)
5484 DeserializationListener->MacroDefinitionRead(PPID, MD);
5485
5486 return MD;
5487 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005488
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005490 const char *FullFileNameStart = Blob.data() + Record[0];
5491 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005492 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 if (!FullFileName.empty())
5494 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005495
Guy Benyei11169dd2012-12-18 14:30:41 +00005496 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005497 InclusionDirective::InclusionKind Kind
5498 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5499 InclusionDirective *ID
5500 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005501 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005502 Record[1], Record[3],
5503 File,
5504 Range);
5505 return ID;
5506 }
5507 }
5508
5509 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5510}
5511
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005512/// \brief Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005513/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005514///
5515/// \param SLocMapI points at a chunk of a module that contains no
5516/// preprocessed entities or the entities it contains are not the ones we are
5517/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005518PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5519 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5520 ++SLocMapI;
5521 for (GlobalSLocOffsetMapType::const_iterator
5522 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5523 ModuleFile &M = *SLocMapI->second;
5524 if (M.NumPreprocessedEntities)
5525 return M.BasePreprocessedEntityID;
5526 }
5527
5528 return getTotalNumPreprocessedEntities();
5529}
5530
5531namespace {
5532
Guy Benyei11169dd2012-12-18 14:30:41 +00005533struct PPEntityComp {
5534 const ASTReader &Reader;
5535 ModuleFile &M;
5536
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005537 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005538
5539 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5540 SourceLocation LHS = getLoc(L);
5541 SourceLocation RHS = getLoc(R);
5542 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5543 }
5544
5545 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5546 SourceLocation LHS = getLoc(L);
5547 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5548 }
5549
5550 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5551 SourceLocation RHS = getLoc(R);
5552 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5553 }
5554
5555 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005556 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 }
5558};
5559
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005560} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005561
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005562PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5563 bool EndsAfter) const {
5564 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 return getTotalNumPreprocessedEntities();
5566
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005567 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5568 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005569 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5570 "Corrupted global sloc offset map");
5571
5572 if (SLocMapI->second->NumPreprocessedEntities == 0)
5573 return findNextPreprocessedEntity(SLocMapI);
5574
5575 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005576
5577 using pp_iterator = const PPEntityOffset *;
5578
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5580 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5581
5582 size_t Count = M.NumPreprocessedEntities;
5583 size_t Half;
5584 pp_iterator First = pp_begin;
5585 pp_iterator PPI;
5586
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005587 if (EndsAfter) {
5588 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005589 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005590 } else {
5591 // Do a binary search manually instead of using std::lower_bound because
5592 // The end locations of entities may be unordered (when a macro expansion
5593 // is inside another macro argument), but for this case it is not important
5594 // whether we get the first macro expansion or its containing macro.
5595 while (Count > 0) {
5596 Half = Count / 2;
5597 PPI = First;
5598 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005599 if (SourceMgr.isBeforeInTranslationUnit(
5600 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005601 First = PPI;
5602 ++First;
5603 Count = Count - Half - 1;
5604 } else
5605 Count = Half;
5606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 }
5608
5609 if (PPI == pp_end)
5610 return findNextPreprocessedEntity(SLocMapI);
5611
5612 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5613}
5614
Guy Benyei11169dd2012-12-18 14:30:41 +00005615/// \brief Returns a pair of [Begin, End) indices of preallocated
5616/// preprocessed entities that \arg Range encompasses.
5617std::pair<unsigned, unsigned>
5618 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5619 if (Range.isInvalid())
5620 return std::make_pair(0,0);
5621 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5622
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005623 PreprocessedEntityID BeginID =
5624 findPreprocessedEntity(Range.getBegin(), false);
5625 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 return std::make_pair(BeginID, EndID);
5627}
5628
5629/// \brief Optionally returns true or false if the preallocated preprocessed
5630/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005631Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005632 FileID FID) {
5633 if (FID.isInvalid())
5634 return false;
5635
5636 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5637 ModuleFile &M = *PPInfo.first;
5638 unsigned LocalIndex = PPInfo.second;
5639 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005640
Richard Smithcb34bd32016-03-27 07:28:06 +00005641 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 if (Loc.isInvalid())
5643 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005644
Guy Benyei11169dd2012-12-18 14:30:41 +00005645 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5646 return true;
5647 else
5648 return false;
5649}
5650
5651namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005652
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 /// \brief Visitor used to search for information about a header file.
5654 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005656 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005657
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005659 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005660
5661 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00005662 HeaderFileInfoLookupTable *Table
5663 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00005664 if (!Table)
5665 return false;
5666
5667 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005668 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 if (Pos == Table->end())
5670 return false;
5671
Richard Smithbdf2d932015-07-30 03:37:16 +00005672 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 return true;
5674 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005675
David Blaikie05785d12013-02-20 22:23:23 +00005676 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005678
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005679} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005680
5681HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005682 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005683 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005684 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005685 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005686
Guy Benyei11169dd2012-12-18 14:30:41 +00005687 return HeaderFileInfo();
5688}
5689
5690void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005691 using DiagState = DiagnosticsEngine::DiagState;
5692 SmallVector<DiagState *, 32> DiagStates;
5693
Vedant Kumar48b4f762018-04-14 01:40:48 +00005694 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005696 auto &Record = F.PragmaDiagMappings;
5697 if (Record.empty())
5698 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005699
Richard Smithd230de22017-01-26 01:01:01 +00005700 DiagStates.clear();
5701
5702 auto ReadDiagState =
5703 [&](const DiagState &BasedOn, SourceLocation Loc,
5704 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5705 unsigned BackrefID = Record[Idx++];
5706 if (BackrefID != 0)
5707 return DiagStates[BackrefID - 1];
5708
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005710 Diag.DiagStates.push_back(BasedOn);
5711 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005713 unsigned Size = Record[Idx++];
5714 assert(Idx + Size * 2 <= Record.size() &&
5715 "Invalid data, not enough diag/map pairs");
5716 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005717 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005718 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005719 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005720 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5721 continue;
5722
5723 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5724
5725 // If this mapping was specified as a warning but the severity was
5726 // upgraded due to diagnostic settings, simulate the current diagnostic
5727 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005728 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5729 NewMapping.setSeverity(diag::Severity::Warning);
5730 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005731 }
5732
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005733 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005734 }
Richard Smithd230de22017-01-26 01:01:01 +00005735 return NewState;
5736 };
5737
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005738 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005739 DiagState *FirstState;
5740 if (F.Kind == MK_ImplicitModule) {
5741 // Implicitly-built modules are reused with different diagnostic
5742 // settings. Use the initial diagnostic state from Diag to simulate this
5743 // compilation's diagnostic settings.
5744 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5745 DiagStates.push_back(FirstState);
5746
5747 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005748 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005749 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005750 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005751 assert(Idx < Record.size() &&
5752 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005753 } else if (F.isModule()) {
5754 // For an explicit module, preserve the flags from the module build
5755 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5756 // -Wblah flags.
5757 unsigned Flags = Record[Idx++];
5758 DiagState Initial;
5759 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5760 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5761 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5762 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5763 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5764 Initial.ExtBehavior = (diag::Severity)Flags;
5765 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005766
Richard Smith6c2b5a82018-02-09 01:15:13 +00005767 assert(F.OriginalSourceFileID.isValid());
5768
Richard Smithe37391c2017-05-03 00:28:49 +00005769 // Set up the root buffer of the module to start with the initial
5770 // diagnostic state of the module itself, to cover files that contain no
5771 // explicit transitions (for which we did not serialize anything).
5772 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5773 .StateTransitions.push_back({FirstState, 0});
5774 } else {
5775 // For prefix ASTs, start with whatever the user configured on the
5776 // command line.
5777 Idx++; // Skip flags.
5778 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5779 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005780 }
Richard Smithd230de22017-01-26 01:01:01 +00005781
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005782 // Read the state transitions.
5783 unsigned NumLocations = Record[Idx++];
5784 while (NumLocations--) {
5785 assert(Idx < Record.size() &&
5786 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005787 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5788 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00005789 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00005790 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5791 unsigned Transitions = Record[Idx++];
5792
5793 // Note that we don't need to set up Parent/ParentOffset here, because
5794 // we won't be changing the diagnostic state within imported FileIDs
5795 // (other than perhaps appending to the main source file, which has no
5796 // parent).
5797 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5798 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5799 for (unsigned I = 0; I != Transitions; ++I) {
5800 unsigned Offset = Record[Idx++];
5801 auto *State =
5802 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5803 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 }
5805 }
Richard Smithd230de22017-01-26 01:01:01 +00005806
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005807 // Read the final state.
5808 assert(Idx < Record.size() &&
5809 "Invalid data, missing final pragma diagnostic state");
5810 SourceLocation CurStateLoc =
5811 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5812 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5813
5814 if (!F.isModule()) {
5815 Diag.DiagStatesByLoc.CurDiagState = CurState;
5816 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5817
5818 // Preserve the property that the imaginary root file describes the
5819 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005820 FileID NullFile;
5821 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005822 if (T.empty())
5823 T.push_back({CurState, 0});
5824 else
5825 T[0].State = CurState;
5826 }
5827
Richard Smithd230de22017-01-26 01:01:01 +00005828 // Don't try to read these mappings again.
5829 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005830 }
5831}
5832
5833/// \brief Get the correct cursor and offset for loading a type.
5834ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5835 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5836 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5837 ModuleFile *M = I->second;
5838 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5839}
5840
5841/// \brief Read and return the type with the given index..
5842///
5843/// The index is the type ID, shifted and minus the number of predefs. This
5844/// routine actually reads the record corresponding to the type at the given
5845/// location. It is a helper routine for GetType, which deals with reading type
5846/// IDs.
5847QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005848 assert(ContextObj && "reading type with no AST context");
5849 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005850 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005851 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005852
5853 // Keep track of where we are in the stream, then jump back there
5854 // after reading this type.
5855 SavedStreamPosition SavedPosition(DeclsCursor);
5856
5857 ReadingKindTracker ReadingKind(Read_Type, *this);
5858
5859 // Note that we are loading a type record.
5860 Deserializing AType(this);
5861
5862 unsigned Idx = 0;
5863 DeclsCursor.JumpToBit(Loc.Offset);
5864 RecordData Record;
5865 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005866 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 case TYPE_EXT_QUAL: {
5868 if (Record.size() != 2) {
5869 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005870 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 }
5872 QualType Base = readType(*Loc.F, Record, Idx);
5873 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5874 return Context.getQualifiedType(Base, Quals);
5875 }
5876
5877 case TYPE_COMPLEX: {
5878 if (Record.size() != 1) {
5879 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005880 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 }
5882 QualType ElemType = readType(*Loc.F, Record, Idx);
5883 return Context.getComplexType(ElemType);
5884 }
5885
5886 case TYPE_POINTER: {
5887 if (Record.size() != 1) {
5888 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005889 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 }
5891 QualType PointeeType = readType(*Loc.F, Record, Idx);
5892 return Context.getPointerType(PointeeType);
5893 }
5894
Reid Kleckner8a365022013-06-24 17:51:48 +00005895 case TYPE_DECAYED: {
5896 if (Record.size() != 1) {
5897 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005898 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00005899 }
5900 QualType OriginalType = readType(*Loc.F, Record, Idx);
5901 QualType DT = Context.getAdjustedParameterType(OriginalType);
5902 if (!isa<DecayedType>(DT))
5903 Error("Decayed type does not decay");
5904 return DT;
5905 }
5906
Reid Kleckner0503a872013-12-05 01:23:43 +00005907 case TYPE_ADJUSTED: {
5908 if (Record.size() != 2) {
5909 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005910 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00005911 }
5912 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5913 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5914 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5915 }
5916
Guy Benyei11169dd2012-12-18 14:30:41 +00005917 case TYPE_BLOCK_POINTER: {
5918 if (Record.size() != 1) {
5919 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005920 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 }
5922 QualType PointeeType = readType(*Loc.F, Record, Idx);
5923 return Context.getBlockPointerType(PointeeType);
5924 }
5925
5926 case TYPE_LVALUE_REFERENCE: {
5927 if (Record.size() != 2) {
5928 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005929 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005930 }
5931 QualType PointeeType = readType(*Loc.F, Record, Idx);
5932 return Context.getLValueReferenceType(PointeeType, Record[1]);
5933 }
5934
5935 case TYPE_RVALUE_REFERENCE: {
5936 if (Record.size() != 1) {
5937 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005938 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 }
5940 QualType PointeeType = readType(*Loc.F, Record, Idx);
5941 return Context.getRValueReferenceType(PointeeType);
5942 }
5943
5944 case TYPE_MEMBER_POINTER: {
5945 if (Record.size() != 2) {
5946 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005947 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 }
5949 QualType PointeeType = readType(*Loc.F, Record, Idx);
5950 QualType ClassType = readType(*Loc.F, Record, Idx);
5951 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00005952 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005953
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5955 }
5956
5957 case TYPE_CONSTANT_ARRAY: {
5958 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005959 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 unsigned IndexTypeQuals = Record[2];
5961 unsigned Idx = 3;
5962 llvm::APInt Size = ReadAPInt(Record, Idx);
5963 return Context.getConstantArrayType(ElementType, Size,
5964 ASM, IndexTypeQuals);
5965 }
5966
5967 case TYPE_INCOMPLETE_ARRAY: {
5968 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005969 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 unsigned IndexTypeQuals = Record[2];
5971 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5972 }
5973
5974 case TYPE_VARIABLE_ARRAY: {
5975 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005976 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005977 unsigned IndexTypeQuals = Record[2];
5978 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5979 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5980 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5981 ASM, IndexTypeQuals,
5982 SourceRange(LBLoc, RBLoc));
5983 }
5984
5985 case TYPE_VECTOR: {
5986 if (Record.size() != 3) {
5987 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005988 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 }
5990
5991 QualType ElementType = readType(*Loc.F, Record, Idx);
5992 unsigned NumElements = Record[1];
5993 unsigned VecKind = Record[2];
5994 return Context.getVectorType(ElementType, NumElements,
5995 (VectorType::VectorKind)VecKind);
5996 }
5997
5998 case TYPE_EXT_VECTOR: {
5999 if (Record.size() != 3) {
6000 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006001 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006002 }
6003
6004 QualType ElementType = readType(*Loc.F, Record, Idx);
6005 unsigned NumElements = Record[1];
6006 return Context.getExtVectorType(ElementType, NumElements);
6007 }
6008
6009 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006010 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006012 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006013 }
6014 QualType ResultType = readType(*Loc.F, Record, Idx);
6015 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006016 (CallingConv)Record[4], Record[5], Record[6],
6017 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 return Context.getFunctionNoProtoType(ResultType, Info);
6019 }
6020
6021 case TYPE_FUNCTION_PROTO: {
6022 QualType ResultType = readType(*Loc.F, Record, Idx);
6023
6024 FunctionProtoType::ExtProtoInfo EPI;
6025 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6026 /*hasregparm*/ Record[2],
6027 /*regparm*/ Record[3],
6028 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006029 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006030 /*nocallersavedregs*/ Record[6],
6031 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006032
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006033 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006034
6035 EPI.Variadic = Record[Idx++];
6036 EPI.HasTrailingReturn = Record[Idx++];
6037 EPI.TypeQuals = Record[Idx++];
6038 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006039 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006040 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006041
6042 unsigned NumParams = Record[Idx++];
6043 SmallVector<QualType, 16> ParamTypes;
6044 for (unsigned I = 0; I != NumParams; ++I)
6045 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6046
John McCall18afab72016-03-01 00:49:02 +00006047 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6048 if (Idx != Record.size()) {
6049 for (unsigned I = 0; I != NumParams; ++I)
6050 ExtParameterInfos.push_back(
6051 FunctionProtoType::ExtParameterInfo
6052 ::getFromOpaqueValue(Record[Idx++]));
6053 EPI.ExtParameterInfos = ExtParameterInfos.data();
6054 }
6055
6056 assert(Idx == Record.size());
6057
Jordan Rose5c382722013-03-08 21:51:21 +00006058 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 }
6060
6061 case TYPE_UNRESOLVED_USING: {
6062 unsigned Idx = 0;
6063 return Context.getTypeDeclType(
6064 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6065 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006066
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 case TYPE_TYPEDEF: {
6068 if (Record.size() != 2) {
6069 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006070 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 }
6072 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006073 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 QualType Canonical = readType(*Loc.F, Record, Idx);
6075 if (!Canonical.isNull())
6076 Canonical = Context.getCanonicalType(Canonical);
6077 return Context.getTypedefType(Decl, Canonical);
6078 }
6079
6080 case TYPE_TYPEOF_EXPR:
6081 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6082
6083 case TYPE_TYPEOF: {
6084 if (Record.size() != 1) {
6085 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006086 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 }
6088 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6089 return Context.getTypeOfType(UnderlyingType);
6090 }
6091
6092 case TYPE_DECLTYPE: {
6093 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6094 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6095 }
6096
6097 case TYPE_UNARY_TRANSFORM: {
6098 QualType BaseType = readType(*Loc.F, Record, Idx);
6099 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006100 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6102 }
6103
Richard Smith74aeef52013-04-26 16:15:35 +00006104 case TYPE_AUTO: {
6105 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006106 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006107 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006108 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006109 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006110
Richard Smith600b5262017-01-26 20:40:47 +00006111 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6112 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6113 QualType Deduced = readType(*Loc.F, Record, Idx);
6114 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6115 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6116 IsDependent);
6117 }
6118
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 case TYPE_RECORD: {
6120 if (Record.size() != 2) {
6121 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006122 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 }
6124 unsigned Idx = 0;
6125 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006126 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6128 QualType T = Context.getRecordType(RD);
6129 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6130 return T;
6131 }
6132
6133 case TYPE_ENUM: {
6134 if (Record.size() != 2) {
6135 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006136 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 }
6138 unsigned Idx = 0;
6139 bool IsDependent = Record[Idx++];
6140 QualType T
6141 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6142 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6143 return T;
6144 }
6145
6146 case TYPE_ATTRIBUTED: {
6147 if (Record.size() != 3) {
6148 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006149 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 }
6151 QualType modifiedType = readType(*Loc.F, Record, Idx);
6152 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006153 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 return Context.getAttributedType(kind, modifiedType, equivalentType);
6155 }
6156
6157 case TYPE_PAREN: {
6158 if (Record.size() != 1) {
6159 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006160 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 }
6162 QualType InnerType = readType(*Loc.F, Record, Idx);
6163 return Context.getParenType(InnerType);
6164 }
6165
6166 case TYPE_PACK_EXPANSION: {
6167 if (Record.size() != 2) {
6168 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006169 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 }
6171 QualType Pattern = readType(*Loc.F, Record, Idx);
6172 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006173 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006174 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 if (Record[1])
6176 NumExpansions = Record[1] - 1;
6177 return Context.getPackExpansionType(Pattern, NumExpansions);
6178 }
6179
6180 case TYPE_ELABORATED: {
6181 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006182 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6184 QualType NamedType = readType(*Loc.F, Record, Idx);
6185 return Context.getElaboratedType(Keyword, NNS, NamedType);
6186 }
6187
6188 case TYPE_OBJC_INTERFACE: {
6189 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006190 ObjCInterfaceDecl *ItfD
6191 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6193 }
6194
Manman Rene6be26c2016-09-13 17:25:08 +00006195 case TYPE_OBJC_TYPE_PARAM: {
6196 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006197 ObjCTypeParamDecl *Decl
6198 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006199 unsigned NumProtos = Record[Idx++];
6200 SmallVector<ObjCProtocolDecl*, 4> Protos;
6201 for (unsigned I = 0; I != NumProtos; ++I)
6202 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6203 return Context.getObjCTypeParamType(Decl, Protos);
6204 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006205
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 case TYPE_OBJC_OBJECT: {
6207 unsigned Idx = 0;
6208 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006209 unsigned NumTypeArgs = Record[Idx++];
6210 SmallVector<QualType, 4> TypeArgs;
6211 for (unsigned I = 0; I != NumTypeArgs; ++I)
6212 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 unsigned NumProtos = Record[Idx++];
6214 SmallVector<ObjCProtocolDecl*, 4> Protos;
6215 for (unsigned I = 0; I != NumProtos; ++I)
6216 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006217 bool IsKindOf = Record[Idx++];
6218 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 }
6220
6221 case TYPE_OBJC_OBJECT_POINTER: {
6222 unsigned Idx = 0;
6223 QualType Pointee = readType(*Loc.F, Record, Idx);
6224 return Context.getObjCObjectPointerType(Pointee);
6225 }
6226
6227 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6228 unsigned Idx = 0;
6229 QualType Parm = readType(*Loc.F, Record, Idx);
6230 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006231 return Context.getSubstTemplateTypeParmType(
6232 cast<TemplateTypeParmType>(Parm),
6233 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 }
6235
6236 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6237 unsigned Idx = 0;
6238 QualType Parm = readType(*Loc.F, Record, Idx);
6239 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6240 return Context.getSubstTemplateTypeParmPackType(
6241 cast<TemplateTypeParmType>(Parm),
6242 ArgPack);
6243 }
6244
6245 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006246 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6248 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6249 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006250 const Type *T = nullptr;
6251 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6252 if (const Type *Existing = DI->getTypeForDecl()) {
6253 T = Existing;
6254 break;
6255 }
6256 }
6257 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006258 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006259 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6260 DI->setTypeForDecl(T);
6261 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006262 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 }
6264
6265 case TYPE_TEMPLATE_TYPE_PARM: {
6266 unsigned Idx = 0;
6267 unsigned Depth = Record[Idx++];
6268 unsigned Index = Record[Idx++];
6269 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006270 TemplateTypeParmDecl *D
6271 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6273 }
6274
6275 case TYPE_DEPENDENT_NAME: {
6276 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006277 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006279 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 QualType Canon = readType(*Loc.F, Record, Idx);
6281 if (!Canon.isNull())
6282 Canon = Context.getCanonicalType(Canon);
6283 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6284 }
6285
6286 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6287 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006288 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006289 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006290 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 unsigned NumArgs = Record[Idx++];
6292 SmallVector<TemplateArgument, 8> Args;
6293 Args.reserve(NumArgs);
6294 while (NumArgs--)
6295 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6296 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006297 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 }
6299
6300 case TYPE_DEPENDENT_SIZED_ARRAY: {
6301 unsigned Idx = 0;
6302
6303 // ArrayType
6304 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006305 ArrayType::ArraySizeModifier ASM
6306 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 unsigned IndexTypeQuals = Record[Idx++];
6308
6309 // DependentSizedArrayType
6310 Expr *NumElts = ReadExpr(*Loc.F);
6311 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6312
6313 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6314 IndexTypeQuals, Brackets);
6315 }
6316
6317 case TYPE_TEMPLATE_SPECIALIZATION: {
6318 unsigned Idx = 0;
6319 bool IsDependent = Record[Idx++];
6320 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6321 SmallVector<TemplateArgument, 8> Args;
6322 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6323 QualType Underlying = readType(*Loc.F, Record, Idx);
6324 QualType T;
6325 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006326 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006328 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6330 return T;
6331 }
6332
6333 case TYPE_ATOMIC: {
6334 if (Record.size() != 1) {
6335 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006336 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 }
6338 QualType ValueType = readType(*Loc.F, Record, Idx);
6339 return Context.getAtomicType(ValueType);
6340 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006341
Joey Goulye3c85de2016-12-01 11:30:49 +00006342 case TYPE_PIPE: {
6343 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006344 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006345 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006346 }
6347
6348 // Reading the pipe element type.
6349 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006350 unsigned ReadOnly = Record[1];
6351 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006352 }
6353
Alex Lorenz00aee432017-03-22 10:04:48 +00006354 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6355 unsigned Idx = 0;
6356
6357 // DependentSizedExtVectorType
6358 QualType ElementType = readType(*Loc.F, Record, Idx);
6359 Expr *SizeExpr = ReadExpr(*Loc.F);
6360 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6361
6362 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6363 AttrLoc);
6364 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006365
6366 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6367 unsigned Idx = 0;
6368
6369 // DependentAddressSpaceType
6370 QualType PointeeType = readType(*Loc.F, Record, Idx);
6371 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6372 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6373
6374 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6375 AttrLoc);
6376 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 }
6378 llvm_unreachable("Invalid TypeCode!");
6379}
6380
Richard Smith564417a2014-03-20 21:47:22 +00006381void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6382 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006383 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006384 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006385 ExceptionSpecificationType EST =
6386 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006387 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006388 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006389 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006390 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006391 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006392 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006393 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006394 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006395 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6396 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006397 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006398 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006399 }
6400}
6401
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006402namespace clang {
6403
6404class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006405 ModuleFile *F;
6406 ASTReader *Reader;
6407 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 unsigned &Idx;
6409
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006410 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006411 return Reader->ReadSourceLocation(*F, Record, Idx);
6412 }
6413
6414 TypeSourceInfo *GetTypeSourceInfo() {
6415 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6416 }
6417
6418 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6419 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 }
6421
Guy Benyei11169dd2012-12-18 14:30:41 +00006422public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006423 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006425 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006426
6427 // We want compile-time assurance that we've enumerated all of
6428 // these, so unfortunately we have to declare them first, then
6429 // define them out-of-line.
6430#define ABSTRACT_TYPELOC(CLASS, PARENT)
6431#define TYPELOC(CLASS, PARENT) \
6432 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6433#include "clang/AST/TypeLocNodes.def"
6434
6435 void VisitFunctionTypeLoc(FunctionTypeLoc);
6436 void VisitArrayTypeLoc(ArrayTypeLoc);
6437};
6438
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006439} // namespace clang
6440
Guy Benyei11169dd2012-12-18 14:30:41 +00006441void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6442 // nothing to do
6443}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006446 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006448 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6449 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6450 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6451 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 }
6453}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006456 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006457}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006460 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006462
Reid Kleckner8a365022013-06-24 17:51:48 +00006463void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6464 // nothing to do
6465}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006466
Reid Kleckner0503a872013-12-05 01:23:43 +00006467void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6468 // nothing to do
6469}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006470
Guy Benyei11169dd2012-12-18 14:30:41 +00006471void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006472 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006473}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006474
Guy Benyei11169dd2012-12-18 14:30:41 +00006475void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006476 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006480 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006481}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006482
Guy Benyei11169dd2012-12-18 14:30:41 +00006483void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006484 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006485 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006486}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006487
Guy Benyei11169dd2012-12-18 14:30:41 +00006488void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006489 TL.setLBracketLoc(ReadSourceLocation());
6490 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006491 if (Record[Idx++])
6492 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 else
Craig Toppera13603a2014-05-22 05:54:18 +00006494 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006495}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006496
Guy Benyei11169dd2012-12-18 14:30:41 +00006497void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6498 VisitArrayTypeLoc(TL);
6499}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006500
Guy Benyei11169dd2012-12-18 14:30:41 +00006501void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6502 VisitArrayTypeLoc(TL);
6503}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006504
Guy Benyei11169dd2012-12-18 14:30:41 +00006505void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6506 VisitArrayTypeLoc(TL);
6507}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006508
Guy Benyei11169dd2012-12-18 14:30:41 +00006509void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6510 DependentSizedArrayTypeLoc TL) {
6511 VisitArrayTypeLoc(TL);
6512}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006513
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006514void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6515 DependentAddressSpaceTypeLoc TL) {
6516
6517 TL.setAttrNameLoc(ReadSourceLocation());
6518 SourceRange range;
6519 range.setBegin(ReadSourceLocation());
6520 range.setEnd(ReadSourceLocation());
6521 TL.setAttrOperandParensRange(range);
6522 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6523}
6524
Guy Benyei11169dd2012-12-18 14:30:41 +00006525void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6526 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006527 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006528}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006529
Guy Benyei11169dd2012-12-18 14:30:41 +00006530void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006531 TL.setNameLoc(ReadSourceLocation());
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::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006535 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006536}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006537
Guy Benyei11169dd2012-12-18 14:30:41 +00006538void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006539 TL.setLocalRangeBegin(ReadSourceLocation());
6540 TL.setLParenLoc(ReadSourceLocation());
6541 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006542 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6543 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006544 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006545 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006546 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 }
6548}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006549
Guy Benyei11169dd2012-12-18 14:30:41 +00006550void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6551 VisitFunctionTypeLoc(TL);
6552}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006553
Guy Benyei11169dd2012-12-18 14:30:41 +00006554void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6555 VisitFunctionTypeLoc(TL);
6556}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006557
Guy Benyei11169dd2012-12-18 14:30:41 +00006558void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006559 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006560}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006561
Guy Benyei11169dd2012-12-18 14:30:41 +00006562void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006563 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006564}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006565
Guy Benyei11169dd2012-12-18 14:30:41 +00006566void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006567 TL.setTypeofLoc(ReadSourceLocation());
6568 TL.setLParenLoc(ReadSourceLocation());
6569 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006570}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006571
Guy Benyei11169dd2012-12-18 14:30:41 +00006572void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006573 TL.setTypeofLoc(ReadSourceLocation());
6574 TL.setLParenLoc(ReadSourceLocation());
6575 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006576 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006577}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006578
Guy Benyei11169dd2012-12-18 14:30:41 +00006579void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006580 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006581}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006584 TL.setKWLoc(ReadSourceLocation());
6585 TL.setLParenLoc(ReadSourceLocation());
6586 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006587 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006588}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006589
Guy Benyei11169dd2012-12-18 14:30:41 +00006590void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006591 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006592}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006593
Richard Smith600b5262017-01-26 20:40:47 +00006594void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6595 DeducedTemplateSpecializationTypeLoc TL) {
6596 TL.setTemplateNameLoc(ReadSourceLocation());
6597}
6598
Guy Benyei11169dd2012-12-18 14:30:41 +00006599void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006600 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006601}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006602
Guy Benyei11169dd2012-12-18 14:30:41 +00006603void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006604 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006605}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006606
Guy Benyei11169dd2012-12-18 14:30:41 +00006607void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006608 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 if (TL.hasAttrOperand()) {
6610 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006611 range.setBegin(ReadSourceLocation());
6612 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 TL.setAttrOperandParensRange(range);
6614 }
6615 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006616 if (Record[Idx++])
6617 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 else
Craig Toppera13603a2014-05-22 05:54:18 +00006619 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006621 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006622}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006623
Guy Benyei11169dd2012-12-18 14:30:41 +00006624void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006625 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006626}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006627
Guy Benyei11169dd2012-12-18 14:30:41 +00006628void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6629 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006630 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006631}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6634 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006635 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006636}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6639 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006640 TL.setTemplateKeywordLoc(ReadSourceLocation());
6641 TL.setTemplateNameLoc(ReadSourceLocation());
6642 TL.setLAngleLoc(ReadSourceLocation());
6643 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006645 TL.setArgLocInfo(
6646 i,
6647 Reader->GetTemplateArgumentLocInfo(
6648 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006649}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006650
Guy Benyei11169dd2012-12-18 14:30:41 +00006651void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006652 TL.setLParenLoc(ReadSourceLocation());
6653 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006654}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006655
Guy Benyei11169dd2012-12-18 14:30:41 +00006656void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006657 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006658 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006660
Guy Benyei11169dd2012-12-18 14:30:41 +00006661void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006662 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006663}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006664
Guy Benyei11169dd2012-12-18 14:30:41 +00006665void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006666 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006667 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006668 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006669}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006670
Guy Benyei11169dd2012-12-18 14:30:41 +00006671void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6672 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006673 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006674 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006675 TL.setTemplateKeywordLoc(ReadSourceLocation());
6676 TL.setTemplateNameLoc(ReadSourceLocation());
6677 TL.setLAngleLoc(ReadSourceLocation());
6678 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006679 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006680 TL.setArgLocInfo(
6681 I,
6682 Reader->GetTemplateArgumentLocInfo(
6683 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006684}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006685
Guy Benyei11169dd2012-12-18 14:30:41 +00006686void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006687 TL.setEllipsisLoc(ReadSourceLocation());
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::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc 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
Manman Rene6be26c2016-09-13 17:25:08 +00006694void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6695 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006696 TL.setProtocolLAngleLoc(ReadSourceLocation());
6697 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006698 }
6699 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006700 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006701}
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006704 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006705 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6706 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006707 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006708 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006709 TL.setProtocolLAngleLoc(ReadSourceLocation());
6710 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006712 TL.setProtocolLoc(i, ReadSourceLocation());
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::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006716 TL.setStarLoc(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::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006720 TL.setKWLoc(ReadSourceLocation());
6721 TL.setLParenLoc(ReadSourceLocation());
6722 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006723}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006724
Xiuli Pan9c14e282016-01-09 12:53:17 +00006725void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006726 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006727}
Guy Benyei11169dd2012-12-18 14:30:41 +00006728
David L. Jonesbe1557a2016-12-21 00:17:49 +00006729TypeSourceInfo *
6730ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6731 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 QualType InfoTy = readType(F, Record, Idx);
6733 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006734 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006735
6736 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006737 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6739 TLR.Visit(TL);
6740 return TInfo;
6741}
6742
6743QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006744 assert(ContextObj && "reading type with no AST context");
6745 ASTContext &Context = *ContextObj;
6746
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 unsigned FastQuals = ID & Qualifiers::FastMask;
6748 unsigned Index = ID >> Qualifiers::FastWidth;
6749
6750 if (Index < NUM_PREDEF_TYPE_IDS) {
6751 QualType T;
6752 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006753 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006754 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006755 case PREDEF_TYPE_VOID_ID:
6756 T = Context.VoidTy;
6757 break;
6758 case PREDEF_TYPE_BOOL_ID:
6759 T = Context.BoolTy;
6760 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 case PREDEF_TYPE_CHAR_U_ID:
6762 case PREDEF_TYPE_CHAR_S_ID:
6763 // FIXME: Check that the signedness of CharTy is correct!
6764 T = Context.CharTy;
6765 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006766 case PREDEF_TYPE_UCHAR_ID:
6767 T = Context.UnsignedCharTy;
6768 break;
6769 case PREDEF_TYPE_USHORT_ID:
6770 T = Context.UnsignedShortTy;
6771 break;
6772 case PREDEF_TYPE_UINT_ID:
6773 T = Context.UnsignedIntTy;
6774 break;
6775 case PREDEF_TYPE_ULONG_ID:
6776 T = Context.UnsignedLongTy;
6777 break;
6778 case PREDEF_TYPE_ULONGLONG_ID:
6779 T = Context.UnsignedLongLongTy;
6780 break;
6781 case PREDEF_TYPE_UINT128_ID:
6782 T = Context.UnsignedInt128Ty;
6783 break;
6784 case PREDEF_TYPE_SCHAR_ID:
6785 T = Context.SignedCharTy;
6786 break;
6787 case PREDEF_TYPE_WCHAR_ID:
6788 T = Context.WCharTy;
6789 break;
6790 case PREDEF_TYPE_SHORT_ID:
6791 T = Context.ShortTy;
6792 break;
6793 case PREDEF_TYPE_INT_ID:
6794 T = Context.IntTy;
6795 break;
6796 case PREDEF_TYPE_LONG_ID:
6797 T = Context.LongTy;
6798 break;
6799 case PREDEF_TYPE_LONGLONG_ID:
6800 T = Context.LongLongTy;
6801 break;
6802 case PREDEF_TYPE_INT128_ID:
6803 T = Context.Int128Ty;
6804 break;
6805 case PREDEF_TYPE_HALF_ID:
6806 T = Context.HalfTy;
6807 break;
6808 case PREDEF_TYPE_FLOAT_ID:
6809 T = Context.FloatTy;
6810 break;
6811 case PREDEF_TYPE_DOUBLE_ID:
6812 T = Context.DoubleTy;
6813 break;
6814 case PREDEF_TYPE_LONGDOUBLE_ID:
6815 T = Context.LongDoubleTy;
6816 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006817 case PREDEF_TYPE_FLOAT16_ID:
6818 T = Context.Float16Ty;
6819 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006820 case PREDEF_TYPE_FLOAT128_ID:
6821 T = Context.Float128Ty;
6822 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006823 case PREDEF_TYPE_OVERLOAD_ID:
6824 T = Context.OverloadTy;
6825 break;
6826 case PREDEF_TYPE_BOUND_MEMBER:
6827 T = Context.BoundMemberTy;
6828 break;
6829 case PREDEF_TYPE_PSEUDO_OBJECT:
6830 T = Context.PseudoObjectTy;
6831 break;
6832 case PREDEF_TYPE_DEPENDENT_ID:
6833 T = Context.DependentTy;
6834 break;
6835 case PREDEF_TYPE_UNKNOWN_ANY:
6836 T = Context.UnknownAnyTy;
6837 break;
6838 case PREDEF_TYPE_NULLPTR_ID:
6839 T = Context.NullPtrTy;
6840 break;
6841 case PREDEF_TYPE_CHAR16_ID:
6842 T = Context.Char16Ty;
6843 break;
6844 case PREDEF_TYPE_CHAR32_ID:
6845 T = Context.Char32Ty;
6846 break;
6847 case PREDEF_TYPE_OBJC_ID:
6848 T = Context.ObjCBuiltinIdTy;
6849 break;
6850 case PREDEF_TYPE_OBJC_CLASS:
6851 T = Context.ObjCBuiltinClassTy;
6852 break;
6853 case PREDEF_TYPE_OBJC_SEL:
6854 T = Context.ObjCBuiltinSelTy;
6855 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006856#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6857 case PREDEF_TYPE_##Id##_ID: \
6858 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006859 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006860#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006861 case PREDEF_TYPE_SAMPLER_ID:
6862 T = Context.OCLSamplerTy;
6863 break;
6864 case PREDEF_TYPE_EVENT_ID:
6865 T = Context.OCLEventTy;
6866 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006867 case PREDEF_TYPE_CLK_EVENT_ID:
6868 T = Context.OCLClkEventTy;
6869 break;
6870 case PREDEF_TYPE_QUEUE_ID:
6871 T = Context.OCLQueueTy;
6872 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006873 case PREDEF_TYPE_RESERVE_ID_ID:
6874 T = Context.OCLReserveIDTy;
6875 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006876 case PREDEF_TYPE_AUTO_DEDUCT:
6877 T = Context.getAutoDeductType();
6878 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006879 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6880 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006882 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6883 T = Context.ARCUnbridgedCastTy;
6884 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 case PREDEF_TYPE_BUILTIN_FN:
6886 T = Context.BuiltinFnTy;
6887 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006888 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6889 T = Context.OMPArraySectionTy;
6890 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 }
6892
6893 assert(!T.isNull() && "Unknown predefined type");
6894 return T.withFastQualifiers(FastQuals);
6895 }
6896
6897 Index -= NUM_PREDEF_TYPE_IDS;
6898 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6899 if (TypesLoaded[Index].isNull()) {
6900 TypesLoaded[Index] = readTypeRecord(Index);
6901 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006902 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006903
6904 TypesLoaded[Index]->setFromAST();
6905 if (DeserializationListener)
6906 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6907 TypesLoaded[Index]);
6908 }
6909
6910 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6911}
6912
6913QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6914 return GetType(getGlobalTypeID(F, LocalID));
6915}
6916
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006917serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006918ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6919 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6920 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006921
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6923 return LocalID;
6924
Richard Smith37a93df2017-02-18 00:32:02 +00006925 if (!F.ModuleOffsetMap.empty())
6926 ReadModuleOffsetMap(F);
6927
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6929 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6930 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006931
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 unsigned GlobalIndex = LocalIndex + I->second;
6933 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6934}
6935
6936TemplateArgumentLocInfo
6937ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6938 TemplateArgument::ArgKind Kind,
6939 const RecordData &Record,
6940 unsigned &Index) {
6941 switch (Kind) {
6942 case TemplateArgument::Expression:
6943 return ReadExpr(F);
6944 case TemplateArgument::Type:
6945 return GetTypeSourceInfo(F, Record, Index);
6946 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006947 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 Index);
6949 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6950 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6951 SourceLocation());
6952 }
6953 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006954 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 Index);
6956 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6957 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006958 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 EllipsisLoc);
6960 }
6961 case TemplateArgument::Null:
6962 case TemplateArgument::Integral:
6963 case TemplateArgument::Declaration:
6964 case TemplateArgument::NullPtr:
6965 case TemplateArgument::Pack:
6966 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00006967 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 }
6969 llvm_unreachable("unexpected template argument loc");
6970}
6971
6972TemplateArgumentLoc
6973ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6974 const RecordData &Record, unsigned &Index) {
6975 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6976
6977 if (Arg.getKind() == TemplateArgument::Expression) {
6978 if (Record[Index++]) // bool InfoHasSameExpr.
6979 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6980 }
6981 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6982 Record, Index));
6983}
6984
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006985const ASTTemplateArgumentListInfo*
6986ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6987 const RecordData &Record,
6988 unsigned &Index) {
6989 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6990 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6991 unsigned NumArgsAsWritten = Record[Index++];
6992 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6993 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6994 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6995 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6996}
6997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6999 return GetDecl(ID);
7000}
7001
Richard Smith053f6c62014-05-16 23:01:30 +00007002void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007003 if (NumCurrentElementsDeserializing) {
7004 // We arrange to not care about the complete redeclaration chain while we're
7005 // deserializing. Just remember that the AST has marked this one as complete
7006 // but that it's not actually complete yet, so we know we still need to
7007 // complete it later.
7008 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7009 return;
7010 }
7011
Richard Smith053f6c62014-05-16 23:01:30 +00007012 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7013
Richard Smith053f6c62014-05-16 23:01:30 +00007014 // If this is a named declaration, complete it by looking it up
7015 // within its context.
7016 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007017 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007018 // all mergeable entities within it.
7019 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7020 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7021 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007022 if (!getContext().getLangOpts().CPlusPlus &&
7023 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007024 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007025 // the identifier instead. (For C++ modules, we don't store decls
7026 // in the serialized identifier table, so we do the lookup in the TU.)
7027 auto *II = Name.getAsIdentifierInfo();
7028 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007029 if (II->isOutOfDate())
7030 updateOutOfDateIdentifier(*II);
7031 } else
7032 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007033 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007034 // Find all declarations of this kind from the relevant context.
7035 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7036 auto *DC = cast<DeclContext>(DCDecl);
7037 SmallVector<Decl*, 8> Decls;
7038 FindExternalLexicalDecls(
7039 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7040 }
Richard Smith053f6c62014-05-16 23:01:30 +00007041 }
7042 }
Richard Smith50895422015-01-31 03:04:55 +00007043
7044 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7045 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7046 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7047 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7048 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7049 if (auto *Template = FD->getPrimaryTemplate())
7050 Template->LoadLazySpecializations();
7051 }
Richard Smith053f6c62014-05-16 23:01:30 +00007052}
7053
Richard Smithc2bb8182015-03-24 06:36:48 +00007054CXXCtorInitializer **
7055ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7056 RecordLocation Loc = getLocalBitOffset(Offset);
7057 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7058 SavedStreamPosition SavedPosition(Cursor);
7059 Cursor.JumpToBit(Loc.Offset);
7060 ReadingKindTracker ReadingKind(Read_Decl, *this);
7061
7062 RecordData Record;
7063 unsigned Code = Cursor.ReadCode();
7064 unsigned RecCode = Cursor.readRecord(Code, Record);
7065 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7066 Error("malformed AST file: missing C++ ctor initializers");
7067 return nullptr;
7068 }
7069
7070 unsigned Idx = 0;
7071 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7072}
7073
Guy Benyei11169dd2012-12-18 14:30:41 +00007074CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007075 assert(ContextObj && "reading base specifiers with no AST context");
7076 ASTContext &Context = *ContextObj;
7077
Guy Benyei11169dd2012-12-18 14:30:41 +00007078 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007079 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 SavedStreamPosition SavedPosition(Cursor);
7081 Cursor.JumpToBit(Loc.Offset);
7082 ReadingKindTracker ReadingKind(Read_Decl, *this);
7083 RecordData Record;
7084 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007085 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007087 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007088 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007089 }
7090
7091 unsigned Idx = 0;
7092 unsigned NumBases = Record[Idx++];
7093 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007094 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007095 for (unsigned I = 0; I != NumBases; ++I)
7096 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7097 return Bases;
7098}
7099
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007100serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007101ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7102 if (LocalID < NUM_PREDEF_DECL_IDS)
7103 return LocalID;
7104
Richard Smith37a93df2017-02-18 00:32:02 +00007105 if (!F.ModuleOffsetMap.empty())
7106 ReadModuleOffsetMap(F);
7107
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7109 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7110 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 return LocalID + I->second;
7113}
7114
7115bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7116 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007117 // Predefined decls aren't from any module.
7118 if (ID < NUM_PREDEF_DECL_IDS)
7119 return false;
7120
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007121 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007122 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007123}
7124
Douglas Gregor9f782892013-01-21 15:25:38 +00007125ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007127 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7129 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7130 return I->second;
7131}
7132
7133SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7134 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007135 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007136
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7138
7139 if (Index > DeclsLoaded.size()) {
7140 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007141 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007143
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 if (Decl *D = DeclsLoaded[Index])
7145 return D->getLocation();
7146
Richard Smithcb34bd32016-03-27 07:28:06 +00007147 SourceLocation Loc;
7148 DeclCursorForID(ID, Loc);
7149 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007150}
7151
Richard Smithfe620d22015-03-05 23:24:12 +00007152static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7153 switch (ID) {
7154 case PREDEF_DECL_NULL_ID:
7155 return nullptr;
7156
7157 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7158 return Context.getTranslationUnitDecl();
7159
7160 case PREDEF_DECL_OBJC_ID_ID:
7161 return Context.getObjCIdDecl();
7162
7163 case PREDEF_DECL_OBJC_SEL_ID:
7164 return Context.getObjCSelDecl();
7165
7166 case PREDEF_DECL_OBJC_CLASS_ID:
7167 return Context.getObjCClassDecl();
7168
7169 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7170 return Context.getObjCProtocolDecl();
7171
7172 case PREDEF_DECL_INT_128_ID:
7173 return Context.getInt128Decl();
7174
7175 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7176 return Context.getUInt128Decl();
7177
7178 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7179 return Context.getObjCInstanceTypeDecl();
7180
7181 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7182 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007183
Richard Smith9b88a4c2015-07-27 05:40:23 +00007184 case PREDEF_DECL_VA_LIST_TAG:
7185 return Context.getVaListTagDecl();
7186
Charles Davisc7d5c942015-09-17 20:55:33 +00007187 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7188 return Context.getBuiltinMSVaListDecl();
7189
Richard Smithf19e1272015-03-07 00:04:49 +00007190 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7191 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007192
7193 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7194 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007195
7196 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7197 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007198
7199 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7200 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007201
7202 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7203 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007204 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007205 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007206}
7207
Richard Smithcd45dbc2014-04-19 03:48:30 +00007208Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007209 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007210 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007211 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007212 if (D) {
7213 // Track that we have merged the declaration with ID \p ID into the
7214 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007215 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007216 if (Merged.empty())
7217 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 }
Richard Smithfe620d22015-03-05 23:24:12 +00007219 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7223
7224 if (Index >= DeclsLoaded.size()) {
7225 assert(0 && "declaration ID out-of-range for AST file");
7226 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007227 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007229
7230 return DeclsLoaded[Index];
7231}
7232
7233Decl *ASTReader::GetDecl(DeclID ID) {
7234 if (ID < NUM_PREDEF_DECL_IDS)
7235 return GetExistingDecl(ID);
7236
7237 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7238
7239 if (Index >= DeclsLoaded.size()) {
7240 assert(0 && "declaration ID out-of-range for AST file");
7241 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007242 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007243 }
7244
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 if (!DeclsLoaded[Index]) {
7246 ReadDeclRecord(ID);
7247 if (DeserializationListener)
7248 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7249 }
7250
7251 return DeclsLoaded[Index];
7252}
7253
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007254DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 DeclID GlobalID) {
7256 if (GlobalID < NUM_PREDEF_DECL_IDS)
7257 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007258
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7260 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7261 ModuleFile *Owner = I->second;
7262
7263 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7264 = M.GlobalToLocalDeclIDs.find(Owner);
7265 if (Pos == M.GlobalToLocalDeclIDs.end())
7266 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 return GlobalID - Owner->BaseDeclID + Pos->second;
7269}
7270
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007271serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 const RecordData &Record,
7273 unsigned &Idx) {
7274 if (Idx >= Record.size()) {
7275 Error("Corrupted AST file");
7276 return 0;
7277 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007278
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 return getGlobalDeclID(F, Record[Idx++]);
7280}
7281
7282/// \brief Resolve the offset of a statement into a statement.
7283///
7284/// This operation will read a new statement from the external
7285/// source each time it is called, and is meant to be used via a
7286/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7287Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7288 // Switch case IDs are per Decl.
7289 ClearSwitchCaseIDs();
7290
7291 // Offset here is a global offset across the entire chain.
7292 RecordLocation Loc = getLocalBitOffset(Offset);
7293 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007294 assert(NumCurrentElementsDeserializing == 0 &&
7295 "should not be called while already deserializing");
7296 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 return ReadStmtFromStream(*Loc.F);
7298}
7299
Richard Smith3cb15722015-08-05 22:41:45 +00007300void ASTReader::FindExternalLexicalDecls(
7301 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7302 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007303 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7304
Richard Smith9ccdd932015-08-06 22:14:12 +00007305 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007306 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7307 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7308 auto K = (Decl::Kind)+LexicalDecls[I];
7309 if (!IsKindWeWant(K))
7310 continue;
7311
7312 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7313
7314 // Don't add predefined declarations to the lexical context more
7315 // than once.
7316 if (ID < NUM_PREDEF_DECL_IDS) {
7317 if (PredefsVisited[ID])
7318 continue;
7319
7320 PredefsVisited[ID] = true;
7321 }
7322
7323 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007324 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007325 if (!DC->isDeclInLexicalTraversal(D))
7326 Decls.push_back(D);
7327 }
7328 }
7329 };
7330
7331 if (isa<TranslationUnitDecl>(DC)) {
7332 for (auto Lexical : TULexicalDecls)
7333 Visit(Lexical.first, Lexical.second);
7334 } else {
7335 auto I = LexicalDecls.find(DC);
7336 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007337 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007338 }
7339
Guy Benyei11169dd2012-12-18 14:30:41 +00007340 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007341}
7342
7343namespace {
7344
7345class DeclIDComp {
7346 ASTReader &Reader;
7347 ModuleFile &Mod;
7348
7349public:
7350 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7351
7352 bool operator()(LocalDeclID L, LocalDeclID R) const {
7353 SourceLocation LHS = getLocation(L);
7354 SourceLocation RHS = getLocation(R);
7355 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7356 }
7357
7358 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7359 SourceLocation RHS = getLocation(R);
7360 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7361 }
7362
7363 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7364 SourceLocation LHS = getLocation(L);
7365 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7366 }
7367
7368 SourceLocation getLocation(LocalDeclID ID) const {
7369 return Reader.getSourceManager().getFileLoc(
7370 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7371 }
7372};
7373
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007374} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007375
7376void ASTReader::FindFileRegionDecls(FileID File,
7377 unsigned Offset, unsigned Length,
7378 SmallVectorImpl<Decl *> &Decls) {
7379 SourceManager &SM = getSourceManager();
7380
7381 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7382 if (I == FileDeclIDs.end())
7383 return;
7384
7385 FileDeclsInfo &DInfo = I->second;
7386 if (DInfo.Decls.empty())
7387 return;
7388
7389 SourceLocation
7390 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7391 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7392
7393 DeclIDComp DIDComp(*this, *DInfo.Mod);
7394 ArrayRef<serialization::LocalDeclID>::iterator
7395 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7396 BeginLoc, DIDComp);
7397 if (BeginIt != DInfo.Decls.begin())
7398 --BeginIt;
7399
7400 // If we are pointing at a top-level decl inside an objc container, we need
7401 // to backtrack until we find it otherwise we will fail to report that the
7402 // region overlaps with an objc container.
7403 while (BeginIt != DInfo.Decls.begin() &&
7404 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7405 ->isTopLevelDeclInObjCContainer())
7406 --BeginIt;
7407
7408 ArrayRef<serialization::LocalDeclID>::iterator
7409 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7410 EndLoc, DIDComp);
7411 if (EndIt != DInfo.Decls.end())
7412 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007413
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 for (ArrayRef<serialization::LocalDeclID>::iterator
7415 DIt = BeginIt; DIt != EndIt; ++DIt)
7416 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7417}
7418
Richard Smith9ce12e32013-02-07 03:30:24 +00007419bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007420ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7421 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007422 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 "DeclContext has no visible decls in storage");
7424 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007425 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007426
Richard Smithd88a7f12015-09-01 20:35:42 +00007427 auto It = Lookups.find(DC);
7428 if (It == Lookups.end())
7429 return false;
7430
Richard Smith8c913ec2014-08-14 02:21:01 +00007431 Deserializing LookupResults(this);
7432
Richard Smithd88a7f12015-09-01 20:35:42 +00007433 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007435 for (DeclID ID : It->second.Table.find(Name)) {
7436 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007437 if (ND->getDeclName() == Name)
7438 Decls.push_back(ND);
7439 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007440
Guy Benyei11169dd2012-12-18 14:30:41 +00007441 ++NumVisibleDeclContextsRead;
7442 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007443 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007444}
7445
Guy Benyei11169dd2012-12-18 14:30:41 +00007446void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7447 if (!DC->hasExternalVisibleStorage())
7448 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007449
7450 auto It = Lookups.find(DC);
7451 assert(It != Lookups.end() &&
7452 "have external visible storage but no lookup tables");
7453
Craig Topper79be4cd2013-07-05 04:33:53 +00007454 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007455
Vedant Kumar48b4f762018-04-14 01:40:48 +00007456 for (DeclID ID : It->second.Table.findAll()) {
7457 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007458 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 }
7460
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 ++NumVisibleDeclContextsRead;
7462
Vedant Kumar48b4f762018-04-14 01:40:48 +00007463 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7464 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7465 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7467}
7468
Richard Smithd88a7f12015-09-01 20:35:42 +00007469const serialization::reader::DeclContextLookupTable *
7470ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7471 auto I = Lookups.find(Primary);
7472 return I == Lookups.end() ? nullptr : &I->second;
7473}
7474
Guy Benyei11169dd2012-12-18 14:30:41 +00007475/// \brief Under non-PCH compilation the consumer receives the objc methods
7476/// before receiving the implementation, and codegen depends on this.
7477/// We simulate this by deserializing and passing to consumer the methods of the
7478/// implementation before passing the deserialized implementation decl.
7479static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7480 ASTConsumer *Consumer) {
7481 assert(ImplD && Consumer);
7482
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007483 for (auto *I : ImplD->methods())
7484 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007485
7486 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7487}
7488
Guy Benyei11169dd2012-12-18 14:30:41 +00007489void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007490 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007491 PassObjCImplDeclToConsumer(ImplD, Consumer);
7492 else
7493 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7494}
7495
7496void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7497 this->Consumer = Consumer;
7498
Richard Smith9e2341d2015-03-23 03:25:59 +00007499 if (Consumer)
7500 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007501
7502 if (DeserializationListener)
7503 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007504}
7505
7506void ASTReader::PrintStats() {
7507 std::fprintf(stderr, "*** AST File Statistics:\n");
7508
7509 unsigned NumTypesLoaded
7510 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7511 QualType());
7512 unsigned NumDeclsLoaded
7513 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007514 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 unsigned NumIdentifiersLoaded
7516 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7517 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007518 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 unsigned NumMacrosLoaded
7520 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7521 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007522 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 unsigned NumSelectorsLoaded
7524 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7525 SelectorsLoaded.end(),
7526 Selector());
7527
7528 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7529 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7530 NumSLocEntriesRead, TotalNumSLocEntries,
7531 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7532 if (!TypesLoaded.empty())
7533 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7534 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7535 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7536 if (!DeclsLoaded.empty())
7537 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7538 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7539 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7540 if (!IdentifiersLoaded.empty())
7541 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7542 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7543 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7544 if (!MacrosLoaded.empty())
7545 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7546 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7547 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7548 if (!SelectorsLoaded.empty())
7549 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7550 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7551 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7552 if (TotalNumStatements)
7553 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7554 NumStatementsRead, TotalNumStatements,
7555 ((float)NumStatementsRead/TotalNumStatements * 100));
7556 if (TotalNumMacros)
7557 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7558 NumMacrosRead, TotalNumMacros,
7559 ((float)NumMacrosRead/TotalNumMacros * 100));
7560 if (TotalLexicalDeclContexts)
7561 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7562 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7563 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7564 * 100));
7565 if (TotalVisibleDeclContexts)
7566 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7567 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7568 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7569 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007570 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7572 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7573 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7574 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007575 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007576 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7577 NumMethodPoolHits, NumMethodPoolLookups,
7578 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007579 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007580 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7581 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7582 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7583 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007584 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007585 std::fprintf(stderr,
7586 " %u / %u identifier table lookups succeeded (%f%%)\n",
7587 NumIdentifierLookupHits, NumIdentifierLookups,
7588 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007589
Douglas Gregore060e572013-01-25 01:03:03 +00007590 if (GlobalIndex) {
7591 std::fprintf(stderr, "\n");
7592 GlobalIndex->printStats();
7593 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007594
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 std::fprintf(stderr, "\n");
7596 dump();
7597 std::fprintf(stderr, "\n");
7598}
7599
7600template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007601LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007602dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007603 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 InitialCapacity> &Map) {
7605 if (Map.begin() == Map.end())
7606 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007607
Vedant Kumar48b4f762018-04-14 01:40:48 +00007608 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007611 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7612 I != IEnd; ++I) {
7613 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7614 << "\n";
7615 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007616}
7617
Yaron Kerencdae9412016-01-29 19:38:18 +00007618LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7620 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7621 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7622 dumpModuleIDMap("Global type map", GlobalTypeMap);
7623 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7624 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7625 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7626 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7627 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007628 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007630
Guy Benyei11169dd2012-12-18 14:30:41 +00007631 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007632 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007633 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007634}
7635
7636/// Return the amount of memory used by memory buffers, breaking down
7637/// by heap-backed versus mmap'ed memory.
7638void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007639 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007640 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 size_t bytes = buf->getBufferSize();
7642 switch (buf->getBufferKind()) {
7643 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7644 sizes.malloc_bytes += bytes;
7645 break;
7646 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7647 sizes.mmap_bytes += bytes;
7648 break;
7649 }
7650 }
7651 }
7652}
7653
7654void ASTReader::InitializeSema(Sema &S) {
7655 SemaObj = &S;
7656 S.addExternalSource(this);
7657
7658 // Makes sure any declarations that were deserialized "too early"
7659 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007660 for (uint64_t ID : PreloadedDeclIDs) {
7661 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007662 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007663 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007664 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007665
Richard Smith3d8e97e2013-10-18 06:54:39 +00007666 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007667 if (!FPPragmaOptions.empty()) {
7668 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007669 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007670 }
7671
Yaxun Liu5b746652016-12-18 05:18:55 +00007672 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7673 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7674 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007675
7676 UpdateSema();
7677}
7678
7679void ASTReader::UpdateSema() {
7680 assert(SemaObj && "no Sema to update");
7681
7682 // Load the offsets of the declarations that Sema references.
7683 // They will be lazily deserialized when needed.
7684 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007685 assert(SemaDeclRefs.size() % 3 == 0);
7686 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007687 if (!SemaObj->StdNamespace)
7688 SemaObj->StdNamespace = SemaDeclRefs[I];
7689 if (!SemaObj->StdBadAlloc)
7690 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007691 if (!SemaObj->StdAlignValT)
7692 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007693 }
7694 SemaDeclRefs.clear();
7695 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007696
Nico Weber779355f2016-03-02 23:22:00 +00007697 // Update the state of pragmas. Use the same API as if we had encountered the
7698 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007699 if(OptimizeOffPragmaLocation.isValid())
7700 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007701 if (PragmaMSStructState != -1)
7702 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007703 if (PointersToMembersPragmaLocation.isValid()) {
7704 SemaObj->ActOnPragmaMSPointersToMembers(
7705 (LangOptions::PragmaMSPointersToMembersKind)
7706 PragmaMSPointersToMembersState,
7707 PointersToMembersPragmaLocation);
7708 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007709 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007710
7711 if (PragmaPackCurrentValue) {
7712 // The bottom of the stack might have a default value. It must be adjusted
7713 // to the current value to ensure that the packing state is preserved after
7714 // popping entries that were included/imported from a PCH/module.
7715 bool DropFirst = false;
7716 if (!PragmaPackStack.empty() &&
7717 PragmaPackStack.front().Location.isInvalid()) {
7718 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7719 "Expected a default alignment value");
7720 SemaObj->PackStack.Stack.emplace_back(
7721 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007722 SemaObj->PackStack.CurrentPragmaLocation,
7723 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007724 DropFirst = true;
7725 }
7726 for (const auto &Entry :
7727 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7728 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007729 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007730 if (PragmaPackCurrentLocation.isInvalid()) {
7731 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7732 "Expected a default alignment value");
7733 // Keep the current values.
7734 } else {
7735 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7736 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7737 }
7738 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007739}
7740
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007741IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007742 // Note that we are loading an identifier.
7743 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007744
Douglas Gregor7211ac12013-01-25 23:32:03 +00007745 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007746 NumIdentifierLookups,
7747 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007748
7749 // We don't need to do identifier table lookups in C++ modules (we preload
7750 // all interesting declarations, and don't need to use the scope for name
7751 // lookups). Perform the lookup in PCH files, though, since we don't build
7752 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007753 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007754 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007755 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007756 break;
7757 } else {
7758 // If there is a global index, look there first to determine which modules
7759 // provably do not have any results for this identifier.
7760 GlobalModuleIndex::HitSet Hits;
7761 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7762 if (!loadGlobalIndex()) {
7763 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7764 HitsPtr = &Hits;
7765 }
7766 }
7767
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007768 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007769 }
7770
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 IdentifierInfo *II = Visitor.getIdentifierInfo();
7772 markIdentifierUpToDate(II);
7773 return II;
7774}
7775
7776namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007777
Guy Benyei11169dd2012-12-18 14:30:41 +00007778 /// \brief An identifier-lookup iterator that enumerates all of the
7779 /// identifiers stored within a set of AST files.
7780 class ASTIdentifierIterator : public IdentifierIterator {
7781 /// \brief The AST reader whose identifiers are being enumerated.
7782 const ASTReader &Reader;
7783
7784 /// \brief The current index into the chain of AST files stored in
7785 /// the AST reader.
7786 unsigned Index;
7787
7788 /// \brief The current position within the identifier lookup table
7789 /// of the current AST file.
7790 ASTIdentifierLookupTable::key_iterator Current;
7791
7792 /// \brief The end position within the identifier lookup table of
7793 /// the current AST file.
7794 ASTIdentifierLookupTable::key_iterator End;
7795
Ben Langmuir537c5b52016-05-04 00:53:13 +00007796 /// \brief Whether to skip any modules in the ASTReader.
7797 bool SkipModules;
7798
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007800 explicit ASTIdentifierIterator(const ASTReader &Reader,
7801 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007802
Craig Topper3e89dfe2014-03-13 02:13:41 +00007803 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007805
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007806} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007807
Ben Langmuir537c5b52016-05-04 00:53:13 +00007808ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7809 bool SkipModules)
7810 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007811}
7812
7813StringRef ASTIdentifierIterator::Next() {
7814 while (Current == End) {
7815 // If we have exhausted all of our AST files, we're done.
7816 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007817 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007818
7819 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007820 ModuleFile &F = Reader.ModuleMgr[Index];
7821 if (SkipModules && F.isModule())
7822 continue;
7823
Vedant Kumar48b4f762018-04-14 01:40:48 +00007824 ASTIdentifierLookupTable *IdTable =
7825 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 Current = IdTable->key_begin();
7827 End = IdTable->key_end();
7828 }
7829
7830 // We have any identifiers remaining in the current AST file; return
7831 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007832 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007833 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007834 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007835}
7836
Ben Langmuir537c5b52016-05-04 00:53:13 +00007837namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007838
Ben Langmuir537c5b52016-05-04 00:53:13 +00007839/// A utility for appending two IdentifierIterators.
7840class ChainedIdentifierIterator : public IdentifierIterator {
7841 std::unique_ptr<IdentifierIterator> Current;
7842 std::unique_ptr<IdentifierIterator> Queued;
7843
7844public:
7845 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7846 std::unique_ptr<IdentifierIterator> Second)
7847 : Current(std::move(First)), Queued(std::move(Second)) {}
7848
7849 StringRef Next() override {
7850 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007851 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007852
7853 StringRef result = Current->Next();
7854 if (!result.empty())
7855 return result;
7856
7857 // Try the queued iterator, which may itself be empty.
7858 Current.reset();
7859 std::swap(Current, Queued);
7860 return Next();
7861 }
7862};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007863
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007864} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007865
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007866IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007867 if (!loadGlobalIndex()) {
7868 std::unique_ptr<IdentifierIterator> ReaderIter(
7869 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7870 std::unique_ptr<IdentifierIterator> ModulesIter(
7871 GlobalIndex->createIdentifierIterator());
7872 return new ChainedIdentifierIterator(std::move(ReaderIter),
7873 std::move(ModulesIter));
7874 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 return new ASTIdentifierIterator(*this);
7877}
7878
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007879namespace clang {
7880namespace serialization {
7881
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 class ReadMethodPoolVisitor {
7883 ASTReader &Reader;
7884 Selector Sel;
7885 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007886 unsigned InstanceBits = 0;
7887 unsigned FactoryBits = 0;
7888 bool InstanceHasMoreThanOneDecl = false;
7889 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007890 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7891 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007892
7893 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007894 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007895 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007896 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007897
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007898 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 if (!M.SelectorLookupTable)
7900 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007901
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007903 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 return true;
7905
Richard Smithbdf2d932015-07-30 03:37:16 +00007906 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007907 ASTSelectorLookupTable *PoolTable
7908 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007909 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 if (Pos == PoolTable->end())
7911 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007912
Richard Smithbdf2d932015-07-30 03:37:16 +00007913 ++Reader.NumMethodPoolTableHits;
7914 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 // FIXME: Not quite happy with the statistics here. We probably should
7916 // disable this tracking when called via LoadSelector.
7917 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007918 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007919 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007920 if (Reader.DeserializationListener)
7921 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007922
Richard Smithbdf2d932015-07-30 03:37:16 +00007923 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7924 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7925 InstanceBits = Data.InstanceBits;
7926 FactoryBits = Data.FactoryBits;
7927 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7928 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 return true;
7930 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007931
Guy Benyei11169dd2012-12-18 14:30:41 +00007932 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007933 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7934 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 }
7936
7937 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007938 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 return FactoryMethods;
7940 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007941
7942 unsigned getInstanceBits() const { return InstanceBits; }
7943 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007944
Nico Weberff4b35e2014-12-27 22:14:15 +00007945 bool instanceHasMoreThanOneDecl() const {
7946 return InstanceHasMoreThanOneDecl;
7947 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007948
Nico Weberff4b35e2014-12-27 22:14:15 +00007949 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007950 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007951
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007952} // namespace serialization
7953} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007954
7955/// \brief Add the given set of methods to the method list.
7956static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7957 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007958 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7959 S.addMethodToGlobalList(&List, Methods[I]);
7960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007961}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007962
Guy Benyei11169dd2012-12-18 14:30:41 +00007963void ASTReader::ReadMethodPool(Selector Sel) {
7964 // Get the selector generation and update it to the current generation.
7965 unsigned &Generation = SelectorGeneration[Sel];
7966 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007967 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007968 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007969
Guy Benyei11169dd2012-12-18 14:30:41 +00007970 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007971 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007973 ModuleMgr.visit(Visitor);
7974
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007976 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007978
7979 ++NumMethodPoolHits;
7980
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 if (!getSema())
7982 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007983
Guy Benyei11169dd2012-12-18 14:30:41 +00007984 Sema &S = *getSema();
7985 Sema::GlobalMethodPool::iterator Pos
7986 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007987
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007988 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007989 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007990 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007991 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007992
7993 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7994 // when building a module we keep every method individually and may need to
7995 // update hasMoreThanOneDecl as we add the methods.
7996 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7997 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007998}
7999
Manman Rena0f31a02016-04-29 19:04:05 +00008000void ASTReader::updateOutOfDateSelector(Selector Sel) {
8001 if (SelectorOutOfDate[Sel])
8002 ReadMethodPool(Sel);
8003}
8004
Guy Benyei11169dd2012-12-18 14:30:41 +00008005void ASTReader::ReadKnownNamespaces(
8006 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8007 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008008
Vedant Kumar48b4f762018-04-14 01:40:48 +00008009 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8010 if (NamespaceDecl *Namespace
8011 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008013 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008014}
8015
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008016void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008017 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008018 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008019 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008020 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008021 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008022 Undefined.insert(std::make_pair(D, Loc));
8023 }
8024}
Nick Lewycky8334af82013-01-26 00:35:08 +00008025
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008026void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8027 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8028 Exprs) {
8029 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008030 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008031 uint64_t Count = DelayedDeleteExprs[Idx++];
8032 for (uint64_t C = 0; C < Count; ++C) {
8033 SourceLocation DeleteLoc =
8034 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8035 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8036 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8037 }
8038 }
8039}
8040
Guy Benyei11169dd2012-12-18 14:30:41 +00008041void ASTReader::ReadTentativeDefinitions(
8042 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008043 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8044 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 if (Var)
8046 TentativeDefs.push_back(Var);
8047 }
8048 TentativeDefinitions.clear();
8049}
8050
8051void ASTReader::ReadUnusedFileScopedDecls(
8052 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008053 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8054 DeclaratorDecl *D
8055 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 if (D)
8057 Decls.push_back(D);
8058 }
8059 UnusedFileScopedDecls.clear();
8060}
8061
8062void ASTReader::ReadDelegatingConstructors(
8063 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008064 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8065 CXXConstructorDecl *D
8066 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 if (D)
8068 Decls.push_back(D);
8069 }
8070 DelegatingCtorDecls.clear();
8071}
8072
8073void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008074 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8075 TypedefNameDecl *D
8076 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 if (D)
8078 Decls.push_back(D);
8079 }
8080 ExtVectorDecls.clear();
8081}
8082
Nico Weber72889432014-09-06 01:25:55 +00008083void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8084 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008085 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8086 ++I) {
8087 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8088 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008089 if (D)
8090 Decls.insert(D);
8091 }
8092 UnusedLocalTypedefNameCandidates.clear();
8093}
8094
Guy Benyei11169dd2012-12-18 14:30:41 +00008095void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008096 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 if (ReferencedSelectorsData.empty())
8098 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008099
Guy Benyei11169dd2012-12-18 14:30:41 +00008100 // If there are @selector references added them to its pool. This is for
8101 // implementation of -Wselector.
8102 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8103 unsigned I = 0;
8104 while (I < DataSize) {
8105 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8106 SourceLocation SelLoc
8107 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8108 Sels.push_back(std::make_pair(Sel, SelLoc));
8109 }
8110 ReferencedSelectorsData.clear();
8111}
8112
8113void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008114 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 if (WeakUndeclaredIdentifiers.empty())
8116 return;
8117
8118 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008119 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008121 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8123 SourceLocation Loc
8124 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8125 bool Used = WeakUndeclaredIdentifiers[I++];
8126 WeakInfo WI(AliasId, Loc);
8127 WI.setUsed(Used);
8128 WeakIDs.push_back(std::make_pair(WeakId, WI));
8129 }
8130 WeakUndeclaredIdentifiers.clear();
8131}
8132
8133void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8134 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8135 ExternalVTableUse VT;
8136 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8137 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8138 VT.DefinitionRequired = VTableUses[Idx++];
8139 VTables.push_back(VT);
8140 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008141
Guy Benyei11169dd2012-12-18 14:30:41 +00008142 VTableUses.clear();
8143}
8144
8145void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008146 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008148 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 SourceLocation Loc
8150 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8151
8152 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008154 PendingInstantiations.clear();
8155}
8156
Richard Smithe40f2ba2013-08-07 21:41:30 +00008157void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008158 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8159 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008160 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8161 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008162 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008163
Justin Lebar28f09c52016-10-10 16:26:08 +00008164 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008165 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8166
8167 ModuleFile *F = getOwningModuleFile(LT->D);
8168 assert(F && "No module");
8169
8170 unsigned TokN = LateParsedTemplates[Idx++];
8171 LT->Toks.reserve(TokN);
8172 for (unsigned T = 0; T < TokN; ++T)
8173 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8174
Justin Lebar28f09c52016-10-10 16:26:08 +00008175 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008176 }
8177
8178 LateParsedTemplates.clear();
8179}
8180
Guy Benyei11169dd2012-12-18 14:30:41 +00008181void ASTReader::LoadSelector(Selector Sel) {
8182 // It would be complicated to avoid reading the methods anyway. So don't.
8183 ReadMethodPool(Sel);
8184}
8185
8186void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8187 assert(ID && "Non-zero identifier ID required");
8188 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8189 IdentifiersLoaded[ID - 1] = II;
8190 if (DeserializationListener)
8191 DeserializationListener->IdentifierRead(ID, II);
8192}
8193
8194/// \brief Set the globally-visible declarations associated with the given
8195/// identifier.
8196///
8197/// If the AST reader is currently in a state where the given declaration IDs
8198/// cannot safely be resolved, they are queued until it is safe to resolve
8199/// them.
8200///
8201/// \param II an IdentifierInfo that refers to one or more globally-visible
8202/// declarations.
8203///
8204/// \param DeclIDs the set of declaration IDs with the name @p II that are
8205/// visible at global scope.
8206///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008207/// \param Decls if non-null, this vector will be populated with the set of
8208/// deserialized declarations. These declarations will not be pushed into
8209/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008210void
8211ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8212 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008213 SmallVectorImpl<Decl *> *Decls) {
8214 if (NumCurrentElementsDeserializing && !Decls) {
8215 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008216 return;
8217 }
8218
Vedant Kumar48b4f762018-04-14 01:40:48 +00008219 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008220 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 // Queue this declaration so that it will be added to the
8222 // translation unit scope and identifier's declaration chain
8223 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008224 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008225 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008227
Vedant Kumar48b4f762018-04-14 01:40:48 +00008228 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008229
8230 // If we're simply supposed to record the declarations, do so now.
8231 if (Decls) {
8232 Decls->push_back(D);
8233 continue;
8234 }
8235
8236 // Introduce this declaration into the translation-unit scope
8237 // and add it to the declaration chain for this identifier, so
8238 // that (unqualified) name lookup will find it.
8239 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 }
8241}
8242
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008243IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008245 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008246
8247 if (IdentifiersLoaded.empty()) {
8248 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008249 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 }
8251
8252 ID -= 1;
8253 if (!IdentifiersLoaded[ID]) {
8254 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8255 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8256 ModuleFile *M = I->second;
8257 unsigned Index = ID - M->BaseIdentifierID;
8258 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8259
8260 // All of the strings in the AST file are preceded by a 16-bit length.
8261 // Extract that 16-bit length to avoid having to execute strlen().
8262 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8263 // unsigned integers. This is important to avoid integer overflow when
8264 // we cast them to 'unsigned'.
8265 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8266 unsigned StrLen = (((unsigned) StrLenPtr[0])
8267 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008268 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8269 IdentifiersLoaded[ID] = &II;
8270 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008272 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008273 }
8274
8275 return IdentifiersLoaded[ID];
8276}
8277
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008278IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8279 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008280}
8281
8282IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8283 if (LocalID < NUM_PREDEF_IDENT_IDS)
8284 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008285
Richard Smith37a93df2017-02-18 00:32:02 +00008286 if (!M.ModuleOffsetMap.empty())
8287 ReadModuleOffsetMap(M);
8288
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8290 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008291 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008292 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008293
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 return LocalID + I->second;
8295}
8296
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008297MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008298 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008299 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008300
8301 if (MacrosLoaded.empty()) {
8302 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008303 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 }
8305
8306 ID -= NUM_PREDEF_MACRO_IDS;
8307 if (!MacrosLoaded[ID]) {
8308 GlobalMacroMapType::iterator I
8309 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8310 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8311 ModuleFile *M = I->second;
8312 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008313 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008314
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008315 if (DeserializationListener)
8316 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8317 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008318 }
8319
8320 return MacrosLoaded[ID];
8321}
8322
8323MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8324 if (LocalID < NUM_PREDEF_MACRO_IDS)
8325 return LocalID;
8326
Richard Smith37a93df2017-02-18 00:32:02 +00008327 if (!M.ModuleOffsetMap.empty())
8328 ReadModuleOffsetMap(M);
8329
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8331 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8332 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8333
8334 return LocalID + I->second;
8335}
8336
8337serialization::SubmoduleID
8338ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8339 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8340 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008341
Richard Smith37a93df2017-02-18 00:32:02 +00008342 if (!M.ModuleOffsetMap.empty())
8343 ReadModuleOffsetMap(M);
8344
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8346 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008347 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008348 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008349
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 return LocalID + I->second;
8351}
8352
8353Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8354 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8355 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008356 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008357 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008358
Guy Benyei11169dd2012-12-18 14:30:41 +00008359 if (GlobalID > SubmodulesLoaded.size()) {
8360 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008361 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008362 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008363
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8365}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008366
8367Module *ASTReader::getModule(unsigned ID) {
8368 return getSubmodule(ID);
8369}
8370
Richard Smithd88a7f12015-09-01 20:35:42 +00008371ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8372 if (ID & 1) {
8373 // It's a module, look it up by submodule ID.
8374 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8375 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8376 } else {
8377 // It's a prefix (preamble, PCH, ...). Look it up by index.
8378 unsigned IndexFromEnd = ID >> 1;
8379 assert(IndexFromEnd && "got reference to unknown module file");
8380 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8381 }
8382}
8383
8384unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8385 if (!F)
8386 return 1;
8387
8388 // For a file representing a module, use the submodule ID of the top-level
8389 // module as the file ID. For any other kind of file, the number of such
8390 // files loaded beforehand will be the same on reload.
8391 // FIXME: Is this true even if we have an explicit module file and a PCH?
8392 if (F->isModule())
8393 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8394
8395 auto PCHModules = getModuleManager().pch_modules();
8396 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8397 assert(I != PCHModules.end() && "emitting reference to unknown file");
8398 return (I - PCHModules.end()) << 1;
8399}
8400
Adrian Prantl15bcf702015-06-30 17:39:43 +00008401llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8402ASTReader::getSourceDescriptor(unsigned ID) {
8403 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008404 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008405
8406 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008407 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008408 const auto &PCHChain = ModuleMgr.pch_modules();
8409 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008410 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008411 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008412 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8413 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8414 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008415 }
8416 return None;
8417}
8418
David Blaikie1ac9c982017-04-11 21:13:37 +00008419ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008420 auto I = DefinitionSource.find(FD);
8421 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008422 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008423 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008424}
8425
Guy Benyei11169dd2012-12-18 14:30:41 +00008426Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8427 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8428}
8429
8430Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8431 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008432 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008433
8434 if (ID > SelectorsLoaded.size()) {
8435 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008436 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 }
8438
Craig Toppera13603a2014-05-22 05:54:18 +00008439 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 // Load this selector from the selector table.
8441 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8442 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8443 ModuleFile &M = *I->second;
8444 ASTSelectorLookupTrait Trait(*this, M);
8445 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8446 SelectorsLoaded[ID - 1] =
8447 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8448 if (DeserializationListener)
8449 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8450 }
8451
8452 return SelectorsLoaded[ID - 1];
8453}
8454
8455Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8456 return DecodeSelector(ID);
8457}
8458
8459uint32_t ASTReader::GetNumExternalSelectors() {
8460 // ID 0 (the null selector) is considered an external selector.
8461 return getTotalNumSelectors() + 1;
8462}
8463
8464serialization::SelectorID
8465ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8466 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8467 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008468
Richard Smith37a93df2017-02-18 00:32:02 +00008469 if (!M.ModuleOffsetMap.empty())
8470 ReadModuleOffsetMap(M);
8471
Guy Benyei11169dd2012-12-18 14:30:41 +00008472 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8473 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008474 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008475 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008476
Guy Benyei11169dd2012-12-18 14:30:41 +00008477 return LocalID + I->second;
8478}
8479
8480DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008481ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008482 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008483 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008484 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008485 switch (Kind) {
8486 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008487 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008488
8489 case DeclarationName::ObjCZeroArgSelector:
8490 case DeclarationName::ObjCOneArgSelector:
8491 case DeclarationName::ObjCMultiArgSelector:
8492 return DeclarationName(ReadSelector(F, Record, Idx));
8493
8494 case DeclarationName::CXXConstructorName:
8495 return Context.DeclarationNames.getCXXConstructorName(
8496 Context.getCanonicalType(readType(F, Record, Idx)));
8497
8498 case DeclarationName::CXXDestructorName:
8499 return Context.DeclarationNames.getCXXDestructorName(
8500 Context.getCanonicalType(readType(F, Record, Idx)));
8501
Richard Smith35845152017-02-07 01:37:30 +00008502 case DeclarationName::CXXDeductionGuideName:
8503 return Context.DeclarationNames.getCXXDeductionGuideName(
8504 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8505
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 case DeclarationName::CXXConversionFunctionName:
8507 return Context.DeclarationNames.getCXXConversionFunctionName(
8508 Context.getCanonicalType(readType(F, Record, Idx)));
8509
8510 case DeclarationName::CXXOperatorName:
8511 return Context.DeclarationNames.getCXXOperatorName(
8512 (OverloadedOperatorKind)Record[Idx++]);
8513
8514 case DeclarationName::CXXLiteralOperatorName:
8515 return Context.DeclarationNames.getCXXLiteralOperatorName(
8516 GetIdentifierInfo(F, Record, Idx));
8517
8518 case DeclarationName::CXXUsingDirective:
8519 return DeclarationName::getUsingDirectiveName();
8520 }
8521
8522 llvm_unreachable("Invalid NameKind!");
8523}
8524
8525void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8526 DeclarationNameLoc &DNLoc,
8527 DeclarationName Name,
8528 const RecordData &Record, unsigned &Idx) {
8529 switch (Name.getNameKind()) {
8530 case DeclarationName::CXXConstructorName:
8531 case DeclarationName::CXXDestructorName:
8532 case DeclarationName::CXXConversionFunctionName:
8533 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8534 break;
8535
8536 case DeclarationName::CXXOperatorName:
8537 DNLoc.CXXOperatorName.BeginOpNameLoc
8538 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8539 DNLoc.CXXOperatorName.EndOpNameLoc
8540 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8541 break;
8542
8543 case DeclarationName::CXXLiteralOperatorName:
8544 DNLoc.CXXLiteralOperatorName.OpNameLoc
8545 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8546 break;
8547
8548 case DeclarationName::Identifier:
8549 case DeclarationName::ObjCZeroArgSelector:
8550 case DeclarationName::ObjCOneArgSelector:
8551 case DeclarationName::ObjCMultiArgSelector:
8552 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008553 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008554 break;
8555 }
8556}
8557
8558void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8559 DeclarationNameInfo &NameInfo,
8560 const RecordData &Record, unsigned &Idx) {
8561 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8562 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8563 DeclarationNameLoc DNLoc;
8564 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8565 NameInfo.setInfo(DNLoc);
8566}
8567
8568void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8569 const RecordData &Record, unsigned &Idx) {
8570 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8571 unsigned NumTPLists = Record[Idx++];
8572 Info.NumTemplParamLists = NumTPLists;
8573 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008574 Info.TemplParamLists =
8575 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008576 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8578 }
8579}
8580
8581TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008582ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008584 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008585 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008586 switch (Kind) {
8587 case TemplateName::Template:
8588 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8589
8590 case TemplateName::OverloadedTemplate: {
8591 unsigned size = Record[Idx++];
8592 UnresolvedSet<8> Decls;
8593 while (size--)
8594 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8595
8596 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8597 }
8598
8599 case TemplateName::QualifiedTemplate: {
8600 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8601 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008602 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8604 }
8605
8606 case TemplateName::DependentTemplate: {
8607 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8608 if (Record[Idx++]) // isIdentifier
8609 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008610 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 Idx));
8612 return Context.getDependentTemplateName(NNS,
8613 (OverloadedOperatorKind)Record[Idx++]);
8614 }
8615
8616 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008617 TemplateTemplateParmDecl *param
8618 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8619 if (!param) return TemplateName();
8620 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8621 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008622 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008623
Guy Benyei11169dd2012-12-18 14:30:41 +00008624 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008625 TemplateTemplateParmDecl *Param
8626 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008628 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008629
Guy Benyei11169dd2012-12-18 14:30:41 +00008630 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8631 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008632 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008633
Guy Benyei11169dd2012-12-18 14:30:41 +00008634 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8635 }
8636 }
8637
8638 llvm_unreachable("Unhandled template name kind!");
8639}
8640
Richard Smith2bb3c342015-08-09 01:05:31 +00008641TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8642 const RecordData &Record,
8643 unsigned &Idx,
8644 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008645 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008646 if (Canonicalize) {
8647 // The caller wants a canonical template argument. Sometimes the AST only
8648 // wants template arguments in canonical form (particularly as the template
8649 // argument lists of template specializations) so ensure we preserve that
8650 // canonical form across serialization.
8651 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8652 return Context.getCanonicalTemplateArgument(Arg);
8653 }
8654
Vedant Kumar48b4f762018-04-14 01:40:48 +00008655 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 switch (Kind) {
8657 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008658 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008659 case TemplateArgument::Type:
8660 return TemplateArgument(readType(F, Record, Idx));
8661 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008662 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008663 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 }
8665 case TemplateArgument::NullPtr:
8666 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8667 case TemplateArgument::Integral: {
8668 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8669 QualType T = readType(F, Record, Idx);
8670 return TemplateArgument(Context, Value, T);
8671 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008672 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008673 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8674 case TemplateArgument::TemplateExpansion: {
8675 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008676 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008677 if (unsigned NumExpansions = Record[Idx++])
8678 NumTemplateExpansions = NumExpansions - 1;
8679 return TemplateArgument(Name, NumTemplateExpansions);
8680 }
8681 case TemplateArgument::Expression:
8682 return TemplateArgument(ReadExpr(F));
8683 case TemplateArgument::Pack: {
8684 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008685 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008686 for (unsigned I = 0; I != NumArgs; ++I)
8687 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008688 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008689 }
8690 }
8691
8692 llvm_unreachable("Unhandled template argument kind!");
8693}
8694
8695TemplateParameterList *
8696ASTReader::ReadTemplateParameterList(ModuleFile &F,
8697 const RecordData &Record, unsigned &Idx) {
8698 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8699 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8700 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8701
8702 unsigned NumParams = Record[Idx++];
8703 SmallVector<NamedDecl *, 16> Params;
8704 Params.reserve(NumParams);
8705 while (NumParams--)
8706 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8707
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008708 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008709 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8710 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008711 return TemplateParams;
8712}
8713
8714void
8715ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008716ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008717 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008718 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008719 unsigned NumTemplateArgs = Record[Idx++];
8720 TemplArgs.reserve(NumTemplateArgs);
8721 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008722 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008723}
8724
8725/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008726void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 const RecordData &Record, unsigned &Idx) {
8728 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008729 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008731 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008732 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008733 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008734 }
8735}
8736
8737CXXBaseSpecifier
8738ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8739 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008740 bool isVirtual = static_cast<bool>(Record[Idx++]);
8741 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8742 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8743 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008744 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8745 SourceRange Range = ReadSourceRange(F, Record, Idx);
8746 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008747 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008748 EllipsisLoc);
8749 Result.setInheritConstructors(inheritConstructors);
8750 return Result;
8751}
8752
Richard Smithc2bb8182015-03-24 06:36:48 +00008753CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008754ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8755 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008756 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008757 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008758 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008759 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008760 for (unsigned i = 0; i != NumInitializers; ++i) {
8761 TypeSourceInfo *TInfo = nullptr;
8762 bool IsBaseVirtual = false;
8763 FieldDecl *Member = nullptr;
8764 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008765
Vedant Kumar48b4f762018-04-14 01:40:48 +00008766 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008767 switch (Type) {
8768 case CTOR_INITIALIZER_BASE:
8769 TInfo = GetTypeSourceInfo(F, Record, Idx);
8770 IsBaseVirtual = Record[Idx++];
8771 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008772
Richard Smithc2bb8182015-03-24 06:36:48 +00008773 case CTOR_INITIALIZER_DELEGATING:
8774 TInfo = GetTypeSourceInfo(F, Record, Idx);
8775 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008776
Richard Smithc2bb8182015-03-24 06:36:48 +00008777 case CTOR_INITIALIZER_MEMBER:
8778 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8779 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008780
Richard Smithc2bb8182015-03-24 06:36:48 +00008781 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8782 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8783 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008784 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008785
8786 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8787 Expr *Init = ReadExpr(F);
8788 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8789 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008790
8791 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008792 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008793 BOMInit = new (Context)
8794 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8795 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008796 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008797 BOMInit = new (Context)
8798 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008799 else if (Member)
8800 BOMInit = new (Context)
8801 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8802 Init, RParenLoc);
8803 else
8804 BOMInit = new (Context)
8805 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8806 LParenLoc, Init, RParenLoc);
8807
Richard Smith418ed822016-12-14 19:45:03 +00008808 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008809 unsigned SourceOrder = Record[Idx++];
8810 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008811 }
8812
Richard Smithc2bb8182015-03-24 06:36:48 +00008813 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008814 }
8815
Richard Smithc2bb8182015-03-24 06:36:48 +00008816 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008817}
8818
8819NestedNameSpecifier *
8820ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8821 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008822 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008823 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008824 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008825 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008826 NestedNameSpecifier::SpecifierKind Kind
8827 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008828 switch (Kind) {
8829 case NestedNameSpecifier::Identifier: {
8830 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8831 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8832 break;
8833 }
8834
8835 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008836 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008837 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8838 break;
8839 }
8840
8841 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008842 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008843 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8844 break;
8845 }
8846
8847 case NestedNameSpecifier::TypeSpec:
8848 case NestedNameSpecifier::TypeSpecWithTemplate: {
8849 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8850 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008851 return nullptr;
8852
Guy Benyei11169dd2012-12-18 14:30:41 +00008853 bool Template = Record[Idx++];
8854 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8855 break;
8856 }
8857
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008858 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008859 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8860 // No associated value, and there can't be a prefix.
8861 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008862
8863 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008864 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008865 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8866 break;
8867 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008868 }
8869 Prev = NNS;
8870 }
8871 return NNS;
8872}
8873
8874NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008875ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008876 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008877 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008878 unsigned N = Record[Idx++];
8879 NestedNameSpecifierLocBuilder Builder;
8880 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008881 NestedNameSpecifier::SpecifierKind Kind
8882 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008883 switch (Kind) {
8884 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008885 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008886 SourceRange Range = ReadSourceRange(F, Record, Idx);
8887 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8888 break;
8889 }
8890
8891 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008892 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008893 SourceRange Range = ReadSourceRange(F, Record, Idx);
8894 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8895 break;
8896 }
8897
8898 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008899 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008900 SourceRange Range = ReadSourceRange(F, Record, Idx);
8901 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8902 break;
8903 }
8904
8905 case NestedNameSpecifier::TypeSpec:
8906 case NestedNameSpecifier::TypeSpecWithTemplate: {
8907 bool Template = Record[Idx++];
8908 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8909 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008910 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00008911 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8912
8913 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008914 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008915 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8916 T->getTypeLoc(), ColonColonLoc);
8917 break;
8918 }
8919
8920 case NestedNameSpecifier::Global: {
8921 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8922 Builder.MakeGlobal(Context, ColonColonLoc);
8923 break;
8924 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008925
8926 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008927 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008928 SourceRange Range = ReadSourceRange(F, Record, Idx);
8929 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8930 break;
8931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008932 }
8933 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008934
Guy Benyei11169dd2012-12-18 14:30:41 +00008935 return Builder.getWithLocInContext(Context);
8936}
8937
8938SourceRange
8939ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8940 unsigned &Idx) {
8941 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8942 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8943 return SourceRange(beg, end);
8944}
8945
8946/// \brief Read an integral value
8947llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8948 unsigned BitWidth = Record[Idx++];
8949 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8950 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8951 Idx += NumWords;
8952 return Result;
8953}
8954
8955/// \brief Read a signed integral value
8956llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8957 bool isUnsigned = Record[Idx++];
8958 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8959}
8960
8961/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008962llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8963 const llvm::fltSemantics &Sem,
8964 unsigned &Idx) {
8965 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008966}
8967
8968// \brief Read a string
8969std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8970 unsigned Len = Record[Idx++];
8971 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8972 Idx += Len;
8973 return Result;
8974}
8975
Richard Smith7ed1bc92014-12-05 22:42:13 +00008976std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8977 unsigned &Idx) {
8978 std::string Filename = ReadString(Record, Idx);
8979 ResolveImportedPath(F, Filename);
8980 return Filename;
8981}
8982
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008983VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008984 unsigned &Idx) {
8985 unsigned Major = Record[Idx++];
8986 unsigned Minor = Record[Idx++];
8987 unsigned Subminor = Record[Idx++];
8988 if (Minor == 0)
8989 return VersionTuple(Major);
8990 if (Subminor == 0)
8991 return VersionTuple(Major, Minor - 1);
8992 return VersionTuple(Major, Minor - 1, Subminor - 1);
8993}
8994
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008995CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008996 const RecordData &Record,
8997 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008998 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008999 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009000}
9001
Richard Smith37a93df2017-02-18 00:32:02 +00009002DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009003 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009004}
9005
Richard Smith37a93df2017-02-18 00:32:02 +00009006DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009007 return Diags.Report(Loc, DiagID);
9008}
9009
9010/// \brief Retrieve the identifier table associated with the
9011/// preprocessor.
9012IdentifierTable &ASTReader::getIdentifierTable() {
9013 return PP.getIdentifierTable();
9014}
9015
9016/// \brief Record that the given ID maps to the given switch-case
9017/// statement.
9018void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009019 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009020 "Already have a SwitchCase with this ID");
9021 (*CurrSwitchCaseStmts)[ID] = SC;
9022}
9023
9024/// \brief Retrieve the switch-case statement with the given ID.
9025SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009026 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009027 return (*CurrSwitchCaseStmts)[ID];
9028}
9029
9030void ASTReader::ClearSwitchCaseIDs() {
9031 CurrSwitchCaseStmts->clear();
9032}
9033
9034void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009035 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009036 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009037 for (SmallVectorImpl<std::pair<BitstreamCursor,
9038 serialization::ModuleFile *>>::iterator
9039 I = CommentsCursors.begin(),
9040 E = CommentsCursors.end();
9041 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009042 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009043 BitstreamCursor &Cursor = I->first;
9044 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009045 SavedStreamPosition SavedPosition(Cursor);
9046
9047 RecordData Record;
9048 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009049 llvm::BitstreamEntry Entry =
9050 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009051
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009052 switch (Entry.Kind) {
9053 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9054 case llvm::BitstreamEntry::Error:
9055 Error("malformed block record in AST file");
9056 return;
9057 case llvm::BitstreamEntry::EndBlock:
9058 goto NextCursor;
9059 case llvm::BitstreamEntry::Record:
9060 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009061 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009062 }
9063
9064 // Read a record.
9065 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009066 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009067 case COMMENTS_RAW_COMMENT: {
9068 unsigned Idx = 0;
9069 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009070 RawComment::CommentKind Kind =
9071 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009072 bool IsTrailingComment = Record[Idx++];
9073 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009074 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009075 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009076 break;
9077 }
9078 }
9079 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009080 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009081 // De-serialized SourceLocations get negative FileIDs for other modules,
9082 // potentially invalidating the original order. Sort it again.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00009083 llvm::sort(Comments.begin(), Comments.end(),
9084 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009085 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009087}
9088
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009089void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9090 bool IncludeSystem, bool Complain,
9091 llvm::function_ref<void(const serialization::InputFile &IF,
9092 bool isSystem)> Visitor) {
9093 unsigned NumUserInputs = MF.NumUserInputFiles;
9094 unsigned NumInputs = MF.InputFilesLoaded.size();
9095 assert(NumUserInputs <= NumInputs);
9096 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9097 for (unsigned I = 0; I < N; ++I) {
9098 bool IsSystem = I >= NumUserInputs;
9099 InputFile IF = getInputFile(MF, I+1, Complain);
9100 Visitor(IF, IsSystem);
9101 }
9102}
9103
Richard Smithf3f84612017-06-29 02:19:42 +00009104void ASTReader::visitTopLevelModuleMaps(
9105 serialization::ModuleFile &MF,
9106 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9107 unsigned NumInputs = MF.InputFilesLoaded.size();
9108 for (unsigned I = 0; I < NumInputs; ++I) {
9109 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9110 if (IFI.TopLevelModuleMap)
9111 // FIXME: This unnecessarily re-reads the InputFileInfo.
9112 if (auto *FE = getInputFile(MF, I + 1).getFile())
9113 Visitor(FE);
9114 }
9115}
9116
Richard Smithcd45dbc2014-04-19 03:48:30 +00009117std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9118 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009119 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009120 return M->getFullModuleName();
9121
9122 // Otherwise, use the name of the top-level module the decl is within.
9123 if (ModuleFile *M = getOwningModuleFile(D))
9124 return M->ModuleName;
9125
9126 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009127 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009128}
9129
Guy Benyei11169dd2012-12-18 14:30:41 +00009130void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009131 while (!PendingIdentifierInfos.empty() ||
9132 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009133 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009134 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009135 // If any identifiers with corresponding top-level declarations have
9136 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009137 using TopLevelDeclsMap =
9138 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009139 TopLevelDeclsMap TopLevelDecls;
9140
Guy Benyei11169dd2012-12-18 14:30:41 +00009141 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009142 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009143 SmallVector<uint32_t, 4> DeclIDs =
9144 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009145 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009146
9147 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009148 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009149
Richard Smith851072e2014-05-19 20:59:20 +00009150 // For each decl chain that we wanted to complete while deserializing, mark
9151 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009152 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9153 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9154 }
Richard Smith851072e2014-05-19 20:59:20 +00009155 PendingIncompleteDeclChains.clear();
9156
Guy Benyei11169dd2012-12-18 14:30:41 +00009157 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009158 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9159 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009160 PendingDeclChains.clear();
9161
Douglas Gregor6168bd22013-02-18 15:53:43 +00009162 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009163 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9164 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9165 IdentifierInfo *II = TLD->first;
9166 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9167 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009168 }
9169 }
9170
Guy Benyei11169dd2012-12-18 14:30:41 +00009171 // Load any pending macro definitions.
9172 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009173 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9174 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9175 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9176 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009177 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009178 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009179 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009180 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009181 resolvePendingMacro(II, Info);
9182 }
9183 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009184 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009185 ++IDIdx) {
9186 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009187 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009188 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009189 }
9190 }
9191 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009192
9193 // Wire up the DeclContexts for Decls that we delayed setting until
9194 // recursive loading is completed.
9195 while (!PendingDeclContextInfos.empty()) {
9196 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9197 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009198 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9199 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009200 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9201 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009202
Richard Smithd1c46742014-04-30 02:24:17 +00009203 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009204 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009205 auto Update = PendingUpdateRecords.pop_back_val();
9206 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009207 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009209 }
Richard Smith8a639892015-01-24 01:07:20 +00009210
9211 // At this point, all update records for loaded decls are in place, so any
9212 // fake class definitions should have become real.
9213 assert(PendingFakeDefinitionData.empty() &&
9214 "faked up a class definition but never saw the real one");
9215
Guy Benyei11169dd2012-12-18 14:30:41 +00009216 // If we deserialized any C++ or Objective-C class definitions, any
9217 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009218 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009219 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009220 for (Decl *D : PendingDefinitions) {
9221 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9222 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009223 // Make sure that the TagType points at the definition.
9224 const_cast<TagType*>(TagT)->decl = TD;
9225 }
Richard Smith8ce51082015-03-11 01:44:51 +00009226
Vedant Kumar48b4f762018-04-14 01:40:48 +00009227 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009228 for (auto *R = getMostRecentExistingDecl(RD); R;
9229 R = R->getPreviousDecl()) {
9230 assert((R == D) ==
9231 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009232 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009233 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009234 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009235 }
9236
9237 continue;
9238 }
Richard Smith8ce51082015-03-11 01:44:51 +00009239
Vedant Kumar48b4f762018-04-14 01:40:48 +00009240 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009241 // Make sure that the ObjCInterfaceType points at the definition.
9242 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9243 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009244
9245 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9246 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9247
Guy Benyei11169dd2012-12-18 14:30:41 +00009248 continue;
9249 }
Richard Smith8ce51082015-03-11 01:44:51 +00009250
Vedant Kumar48b4f762018-04-14 01:40:48 +00009251 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009252 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9253 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9254
Guy Benyei11169dd2012-12-18 14:30:41 +00009255 continue;
9256 }
Richard Smith8ce51082015-03-11 01:44:51 +00009257
Vedant Kumar48b4f762018-04-14 01:40:48 +00009258 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009259 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9260 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009261 }
9262 PendingDefinitions.clear();
9263
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009264 // Load the bodies of any functions or methods we've encountered. We do
9265 // this now (delayed) so that we can be sure that the declaration chains
9266 // have been fully wired up (hasBody relies on this).
9267 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009268 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9269 PBEnd = PendingBodies.end();
9270 PB != PBEnd; ++PB) {
9271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009272 // FIXME: Check for =delete/=default?
9273 // FIXME: Complain about ODR violations here?
9274 const FunctionDecl *Defn = nullptr;
9275 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009276 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009277 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009278 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009279 mergeDefinitionVisibility(NonConstDefn, FD);
9280
9281 if (!FD->isLateTemplateParsed() &&
9282 !NonConstDefn->isLateTemplateParsed() &&
9283 FD->getODRHash() != NonConstDefn->getODRHash()) {
9284 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9285 }
9286 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009287 continue;
9288 }
9289
Vedant Kumar48b4f762018-04-14 01:40:48 +00009290 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009291 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009292 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009293 }
9294 PendingBodies.clear();
9295
Richard Smith42413142015-05-15 20:05:43 +00009296 // Do some cleanup.
9297 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9298 getContext().deduplicateMergedDefinitonsFor(ND);
9299 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009300}
9301
9302void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009303 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9304 PendingFunctionOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009305 return;
9306
Richard Smitha0ce9c42014-07-29 23:23:27 +00009307 // Trigger the import of the full definition of each class that had any
9308 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009309 // These updates may in turn find and diagnose some ODR failures, so take
9310 // ownership of the set first.
9311 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9312 PendingOdrMergeFailures.clear();
9313 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009314 Merge.first->buildLookup();
9315 Merge.first->decls_begin();
9316 Merge.first->bases_begin();
9317 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009318 for (auto &RecordPair : Merge.second) {
9319 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009320 RD->decls_begin();
9321 RD->bases_begin();
9322 RD->vbases_begin();
9323 }
9324 }
9325
Richard Trieue6caa262017-12-23 00:41:01 +00009326 // Trigger the import of functions.
9327 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9328 PendingFunctionOdrMergeFailures.clear();
9329 for (auto &Merge : FunctionOdrMergeFailures) {
9330 Merge.first->buildLookup();
9331 Merge.first->decls_begin();
9332 Merge.first->getBody();
9333 for (auto &FD : Merge.second) {
9334 FD->buildLookup();
9335 FD->decls_begin();
9336 FD->getBody();
9337 }
9338 }
9339
Richard Smitha0ce9c42014-07-29 23:23:27 +00009340 // For each declaration from a merged context, check that the canonical
9341 // definition of that context also contains a declaration of the same
9342 // entity.
9343 //
9344 // Caution: this loop does things that might invalidate iterators into
9345 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9346 while (!PendingOdrMergeChecks.empty()) {
9347 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9348
9349 // FIXME: Skip over implicit declarations for now. This matters for things
9350 // like implicitly-declared special member functions. This isn't entirely
9351 // correct; we can end up with multiple unmerged declarations of the same
9352 // implicit entity.
9353 if (D->isImplicit())
9354 continue;
9355
9356 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009357
9358 bool Found = false;
9359 const Decl *DCanon = D->getCanonicalDecl();
9360
Richard Smith01bdb7a2014-08-28 05:44:07 +00009361 for (auto RI : D->redecls()) {
9362 if (RI->getLexicalDeclContext() == CanonDef) {
9363 Found = true;
9364 break;
9365 }
9366 }
9367 if (Found)
9368 continue;
9369
Richard Smith0f4e2c42015-08-06 04:23:48 +00009370 // Quick check failed, time to do the slow thing. Note, we can't just
9371 // look up the name of D in CanonDef here, because the member that is
9372 // in CanonDef might not be found by name lookup (it might have been
9373 // replaced by a more recent declaration in the lookup table), and we
9374 // can't necessarily find it in the redeclaration chain because it might
9375 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009376 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009377 for (auto *CanonMember : CanonDef->decls()) {
9378 if (CanonMember->getCanonicalDecl() == DCanon) {
9379 // This can happen if the declaration is merely mergeable and not
9380 // actually redeclarable (we looked for redeclarations earlier).
9381 //
9382 // FIXME: We should be able to detect this more efficiently, without
9383 // pulling in all of the members of CanonDef.
9384 Found = true;
9385 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009386 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009387 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9388 if (ND->getDeclName() == D->getDeclName())
9389 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009390 }
9391
9392 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009393 // The AST doesn't like TagDecls becoming invalid after they've been
9394 // completed. We only really need to mark FieldDecls as invalid here.
9395 if (!isa<TagDecl>(D))
9396 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009397
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009398 // Ensure we don't accidentally recursively enter deserialization while
9399 // we're producing our diagnostic.
9400 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009401
9402 std::string CanonDefModule =
9403 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9404 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9405 << D << getOwningModuleNameForDiagnostic(D)
9406 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9407
9408 if (Candidates.empty())
9409 Diag(cast<Decl>(CanonDef)->getLocation(),
9410 diag::note_module_odr_violation_no_possible_decls) << D;
9411 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009412 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9413 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009414 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009415 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009416 }
9417
9418 DiagnosedOdrMergeFailures.insert(CanonDef);
9419 }
9420 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009421
Richard Trieue6caa262017-12-23 00:41:01 +00009422 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009423 return;
9424
9425 // Ensure we don't accidentally recursively enter deserialization while
9426 // we're producing our diagnostics.
9427 Deserializing RecursionGuard(this);
9428
Richard Trieue6caa262017-12-23 00:41:01 +00009429 // Common code for hashing helpers.
9430 ODRHash Hash;
9431 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9432 Hash.clear();
9433 Hash.AddQualType(Ty);
9434 return Hash.CalculateHash();
9435 };
9436
9437 auto ComputeODRHash = [&Hash](const Stmt *S) {
9438 assert(S);
9439 Hash.clear();
9440 Hash.AddStmt(S);
9441 return Hash.CalculateHash();
9442 };
9443
9444 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9445 assert(D);
9446 Hash.clear();
9447 Hash.AddSubDecl(D);
9448 return Hash.CalculateHash();
9449 };
9450
Richard Smithcd45dbc2014-04-19 03:48:30 +00009451 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009452 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009453 // If we've already pointed out a specific problem with this class, don't
9454 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009455 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009456 continue;
9457
9458 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009459 CXXRecordDecl *FirstRecord = Merge.first;
9460 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009461 for (auto &RecordPair : Merge.second) {
9462 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009463 // Multiple different declarations got merged together; tell the user
9464 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009465 if (FirstRecord == SecondRecord)
9466 continue;
9467
9468 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009469
9470 auto *FirstDD = FirstRecord->DefinitionData;
9471 auto *SecondDD = RecordPair.second;
9472
9473 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9474
9475 // Diagnostics from DefinitionData are emitted here.
9476 if (FirstDD != SecondDD) {
9477 enum ODRDefinitionDataDifference {
9478 NumBases,
9479 NumVBases,
9480 BaseType,
9481 BaseVirtual,
9482 BaseAccess,
9483 };
9484 auto ODRDiagError = [FirstRecord, &FirstModule,
9485 this](SourceLocation Loc, SourceRange Range,
9486 ODRDefinitionDataDifference DiffType) {
9487 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9488 << FirstRecord << FirstModule.empty() << FirstModule << Range
9489 << DiffType;
9490 };
9491 auto ODRDiagNote = [&SecondModule,
9492 this](SourceLocation Loc, SourceRange Range,
9493 ODRDefinitionDataDifference DiffType) {
9494 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9495 << SecondModule << Range << DiffType;
9496 };
9497
Richard Trieue13eabe2017-09-30 02:19:17 +00009498 unsigned FirstNumBases = FirstDD->NumBases;
9499 unsigned FirstNumVBases = FirstDD->NumVBases;
9500 unsigned SecondNumBases = SecondDD->NumBases;
9501 unsigned SecondNumVBases = SecondDD->NumVBases;
9502
9503 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9504 unsigned NumBases = DD->NumBases;
9505 if (NumBases == 0) return SourceRange();
9506 auto bases = DD->bases();
9507 return SourceRange(bases[0].getLocStart(),
9508 bases[NumBases - 1].getLocEnd());
9509 };
9510
9511 if (FirstNumBases != SecondNumBases) {
9512 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9513 NumBases)
9514 << FirstNumBases;
9515 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9516 NumBases)
9517 << SecondNumBases;
9518 Diagnosed = true;
9519 break;
9520 }
9521
9522 if (FirstNumVBases != SecondNumVBases) {
9523 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9524 NumVBases)
9525 << FirstNumVBases;
9526 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9527 NumVBases)
9528 << SecondNumVBases;
9529 Diagnosed = true;
9530 break;
9531 }
9532
9533 auto FirstBases = FirstDD->bases();
9534 auto SecondBases = SecondDD->bases();
9535 unsigned i = 0;
9536 for (i = 0; i < FirstNumBases; ++i) {
9537 auto FirstBase = FirstBases[i];
9538 auto SecondBase = SecondBases[i];
9539 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9540 ComputeQualTypeODRHash(SecondBase.getType())) {
9541 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9542 BaseType)
9543 << (i + 1) << FirstBase.getType();
9544 ODRDiagNote(SecondRecord->getLocation(),
9545 SecondBase.getSourceRange(), BaseType)
9546 << (i + 1) << SecondBase.getType();
9547 break;
9548 }
9549
9550 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9551 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9552 BaseVirtual)
9553 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9554 ODRDiagNote(SecondRecord->getLocation(),
9555 SecondBase.getSourceRange(), BaseVirtual)
9556 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9557 break;
9558 }
9559
9560 if (FirstBase.getAccessSpecifierAsWritten() !=
9561 SecondBase.getAccessSpecifierAsWritten()) {
9562 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9563 BaseAccess)
9564 << (i + 1) << FirstBase.getType()
9565 << (int)FirstBase.getAccessSpecifierAsWritten();
9566 ODRDiagNote(SecondRecord->getLocation(),
9567 SecondBase.getSourceRange(), BaseAccess)
9568 << (i + 1) << SecondBase.getType()
9569 << (int)SecondBase.getAccessSpecifierAsWritten();
9570 break;
9571 }
9572 }
9573
9574 if (i != FirstNumBases) {
9575 Diagnosed = true;
9576 break;
9577 }
9578 }
9579
Richard Trieue7f7ed22017-02-22 01:11:25 +00009580 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009581
9582 const ClassTemplateDecl *FirstTemplate =
9583 FirstRecord->getDescribedClassTemplate();
9584 const ClassTemplateDecl *SecondTemplate =
9585 SecondRecord->getDescribedClassTemplate();
9586
9587 assert(!FirstTemplate == !SecondTemplate &&
9588 "Both pointers should be null or non-null");
9589
9590 enum ODRTemplateDifference {
9591 ParamEmptyName,
9592 ParamName,
9593 ParamSingleDefaultArgument,
9594 ParamDifferentDefaultArgument,
9595 };
9596
9597 if (FirstTemplate && SecondTemplate) {
9598 DeclHashes FirstTemplateHashes;
9599 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009600
9601 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009602 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9603 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009604 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009605 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009606 }
9607 };
9608
9609 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9610 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9611
9612 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9613 "Number of template parameters should be equal.");
9614
9615 auto FirstIt = FirstTemplateHashes.begin();
9616 auto FirstEnd = FirstTemplateHashes.end();
9617 auto SecondIt = SecondTemplateHashes.begin();
9618 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9619 if (FirstIt->second == SecondIt->second)
9620 continue;
9621
9622 auto ODRDiagError = [FirstRecord, &FirstModule,
9623 this](SourceLocation Loc, SourceRange Range,
9624 ODRTemplateDifference DiffType) {
9625 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9626 << FirstRecord << FirstModule.empty() << FirstModule << Range
9627 << DiffType;
9628 };
9629 auto ODRDiagNote = [&SecondModule,
9630 this](SourceLocation Loc, SourceRange Range,
9631 ODRTemplateDifference DiffType) {
9632 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9633 << SecondModule << Range << DiffType;
9634 };
9635
Vedant Kumar48b4f762018-04-14 01:40:48 +00009636 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9637 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009638
9639 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9640 "Parameter Decl's should be the same kind.");
9641
9642 DeclarationName FirstName = FirstDecl->getDeclName();
9643 DeclarationName SecondName = SecondDecl->getDeclName();
9644
9645 if (FirstName != SecondName) {
9646 const bool FirstNameEmpty =
9647 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9648 const bool SecondNameEmpty =
9649 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9650 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9651 "Both template parameters cannot be unnamed.");
9652 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9653 FirstNameEmpty ? ParamEmptyName : ParamName)
9654 << FirstName;
9655 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9656 SecondNameEmpty ? ParamEmptyName : ParamName)
9657 << SecondName;
9658 break;
9659 }
9660
9661 switch (FirstDecl->getKind()) {
9662 default:
9663 llvm_unreachable("Invalid template parameter type.");
9664 case Decl::TemplateTypeParm: {
9665 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9666 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9667 const bool HasFirstDefaultArgument =
9668 FirstParam->hasDefaultArgument() &&
9669 !FirstParam->defaultArgumentWasInherited();
9670 const bool HasSecondDefaultArgument =
9671 SecondParam->hasDefaultArgument() &&
9672 !SecondParam->defaultArgumentWasInherited();
9673
9674 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9675 ODRDiagError(FirstDecl->getLocation(),
9676 FirstDecl->getSourceRange(),
9677 ParamSingleDefaultArgument)
9678 << HasFirstDefaultArgument;
9679 ODRDiagNote(SecondDecl->getLocation(),
9680 SecondDecl->getSourceRange(),
9681 ParamSingleDefaultArgument)
9682 << HasSecondDefaultArgument;
9683 break;
9684 }
9685
9686 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9687 "Expecting default arguments.");
9688
9689 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9690 ParamDifferentDefaultArgument);
9691 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9692 ParamDifferentDefaultArgument);
9693
9694 break;
9695 }
9696 case Decl::NonTypeTemplateParm: {
9697 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9698 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9699 const bool HasFirstDefaultArgument =
9700 FirstParam->hasDefaultArgument() &&
9701 !FirstParam->defaultArgumentWasInherited();
9702 const bool HasSecondDefaultArgument =
9703 SecondParam->hasDefaultArgument() &&
9704 !SecondParam->defaultArgumentWasInherited();
9705
9706 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9707 ODRDiagError(FirstDecl->getLocation(),
9708 FirstDecl->getSourceRange(),
9709 ParamSingleDefaultArgument)
9710 << HasFirstDefaultArgument;
9711 ODRDiagNote(SecondDecl->getLocation(),
9712 SecondDecl->getSourceRange(),
9713 ParamSingleDefaultArgument)
9714 << HasSecondDefaultArgument;
9715 break;
9716 }
9717
9718 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9719 "Expecting default arguments.");
9720
9721 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9722 ParamDifferentDefaultArgument);
9723 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9724 ParamDifferentDefaultArgument);
9725
9726 break;
9727 }
9728 case Decl::TemplateTemplateParm: {
9729 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9730 const auto *SecondParam =
9731 cast<TemplateTemplateParmDecl>(SecondDecl);
9732 const bool HasFirstDefaultArgument =
9733 FirstParam->hasDefaultArgument() &&
9734 !FirstParam->defaultArgumentWasInherited();
9735 const bool HasSecondDefaultArgument =
9736 SecondParam->hasDefaultArgument() &&
9737 !SecondParam->defaultArgumentWasInherited();
9738
9739 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9740 ODRDiagError(FirstDecl->getLocation(),
9741 FirstDecl->getSourceRange(),
9742 ParamSingleDefaultArgument)
9743 << HasFirstDefaultArgument;
9744 ODRDiagNote(SecondDecl->getLocation(),
9745 SecondDecl->getSourceRange(),
9746 ParamSingleDefaultArgument)
9747 << HasSecondDefaultArgument;
9748 break;
9749 }
9750
9751 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9752 "Expecting default arguments.");
9753
9754 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9755 ParamDifferentDefaultArgument);
9756 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9757 ParamDifferentDefaultArgument);
9758
9759 break;
9760 }
9761 }
9762
9763 break;
9764 }
9765
9766 if (FirstIt != FirstEnd) {
9767 Diagnosed = true;
9768 break;
9769 }
9770 }
9771
Richard Trieue7f7ed22017-02-22 01:11:25 +00009772 DeclHashes FirstHashes;
9773 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009774
Richard Trieue6caa262017-12-23 00:41:01 +00009775 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9776 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009777 for (auto *D : Record->decls()) {
9778 // Due to decl merging, the first CXXRecordDecl is the parent of
9779 // Decls in both records.
9780 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9781 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009782 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009783 }
9784 };
9785 PopulateHashes(FirstHashes, FirstRecord);
9786 PopulateHashes(SecondHashes, SecondRecord);
9787
9788 // Used with err_module_odr_violation_mismatch_decl and
9789 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009790 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009791 enum {
9792 EndOfClass,
9793 PublicSpecifer,
9794 PrivateSpecifer,
9795 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009796 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009797 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009798 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009799 TypeAlias,
9800 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009801 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009802 Friend,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009803 Other
9804 } FirstDiffType = Other,
9805 SecondDiffType = Other;
9806
9807 auto DifferenceSelector = [](Decl *D) {
9808 assert(D && "valid Decl required");
9809 switch (D->getKind()) {
9810 default:
9811 return Other;
9812 case Decl::AccessSpec:
9813 switch (D->getAccess()) {
9814 case AS_public:
9815 return PublicSpecifer;
9816 case AS_private:
9817 return PrivateSpecifer;
9818 case AS_protected:
9819 return ProtectedSpecifer;
9820 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009821 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009822 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009823 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009824 case Decl::StaticAssert:
9825 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009826 case Decl::Field:
9827 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009828 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009829 case Decl::CXXConstructor:
9830 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009831 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009832 case Decl::TypeAlias:
9833 return TypeAlias;
9834 case Decl::Typedef:
9835 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009836 case Decl::Var:
9837 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009838 case Decl::Friend:
9839 return Friend;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009840 }
9841 };
9842
9843 Decl *FirstDecl = nullptr;
9844 Decl *SecondDecl = nullptr;
9845 auto FirstIt = FirstHashes.begin();
9846 auto SecondIt = SecondHashes.begin();
9847
9848 // If there is a diagnoseable difference, FirstDiffType and
9849 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9850 // filled in if not EndOfClass.
9851 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009852 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9853 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009854 ++FirstIt;
9855 ++SecondIt;
9856 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009857 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009858
Richard Trieue7f7ed22017-02-22 01:11:25 +00009859 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9860 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9861
9862 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9863 SecondDiffType =
9864 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9865
9866 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009867 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009868
9869 if (FirstDiffType == Other || SecondDiffType == Other) {
9870 // Reaching this point means an unexpected Decl was encountered
9871 // or no difference was detected. This causes a generic error
9872 // message to be emitted.
9873 Diag(FirstRecord->getLocation(),
9874 diag::err_module_odr_violation_different_definitions)
9875 << FirstRecord << FirstModule.empty() << FirstModule;
9876
Richard Trieuca48d362017-06-21 01:43:13 +00009877 if (FirstDecl) {
9878 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9879 << FirstRecord << FirstDecl->getSourceRange();
9880 }
9881
Richard Trieue7f7ed22017-02-22 01:11:25 +00009882 Diag(SecondRecord->getLocation(),
9883 diag::note_module_odr_violation_different_definitions)
9884 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009885
9886 if (SecondDecl) {
9887 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9888 << SecondDecl->getSourceRange();
9889 }
9890
Richard Trieue7f7ed22017-02-22 01:11:25 +00009891 Diagnosed = true;
9892 break;
9893 }
9894
9895 if (FirstDiffType != SecondDiffType) {
9896 SourceLocation FirstLoc;
9897 SourceRange FirstRange;
9898 if (FirstDiffType == EndOfClass) {
9899 FirstLoc = FirstRecord->getBraceRange().getEnd();
9900 } else {
9901 FirstLoc = FirstIt->first->getLocation();
9902 FirstRange = FirstIt->first->getSourceRange();
9903 }
9904 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9905 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9906 << FirstDiffType;
9907
9908 SourceLocation SecondLoc;
9909 SourceRange SecondRange;
9910 if (SecondDiffType == EndOfClass) {
9911 SecondLoc = SecondRecord->getBraceRange().getEnd();
9912 } else {
9913 SecondLoc = SecondDecl->getLocation();
9914 SecondRange = SecondDecl->getSourceRange();
9915 }
9916 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9917 << SecondModule << SecondRange << SecondDiffType;
9918 Diagnosed = true;
9919 break;
9920 }
9921
Richard Trieu639d7b62017-02-22 22:22:42 +00009922 assert(FirstDiffType == SecondDiffType);
9923
9924 // Used with err_module_odr_violation_mismatch_decl_diff and
9925 // note_module_odr_violation_mismatch_decl_diff
9926 enum ODRDeclDifference{
9927 StaticAssertCondition,
9928 StaticAssertMessage,
9929 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009930 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009931 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009932 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009933 FieldDifferentWidthBitField,
9934 FieldSingleMutable,
9935 FieldSingleInitializer,
9936 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009937 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009938 MethodDeleted,
9939 MethodVirtual,
9940 MethodStatic,
9941 MethodVolatile,
9942 MethodConst,
9943 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009944 MethodNumberParameters,
9945 MethodParameterType,
9946 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009947 MethodParameterSingleDefaultArgument,
9948 MethodParameterDifferentDefaultArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009949 TypedefName,
9950 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009951 VarName,
9952 VarType,
9953 VarSingleInitializer,
9954 VarDifferentInitializer,
9955 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009956 FriendTypeFunction,
9957 FriendType,
9958 FriendFunction,
Richard Trieu639d7b62017-02-22 22:22:42 +00009959 };
9960
9961 // These lambdas have the common portions of the ODR diagnostics. This
9962 // has the same return as Diag(), so addition parameters can be passed
9963 // in with operator<<
9964 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9965 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9966 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9967 << FirstRecord << FirstModule.empty() << FirstModule << Range
9968 << DiffType;
9969 };
9970 auto ODRDiagNote = [&SecondModule, this](
9971 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9972 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9973 << SecondModule << Range << DiffType;
9974 };
9975
Richard Trieu639d7b62017-02-22 22:22:42 +00009976 switch (FirstDiffType) {
9977 case Other:
9978 case EndOfClass:
9979 case PublicSpecifer:
9980 case PrivateSpecifer:
9981 case ProtectedSpecifer:
9982 llvm_unreachable("Invalid diff type");
9983
9984 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009985 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9986 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +00009987
9988 Expr *FirstExpr = FirstSA->getAssertExpr();
9989 Expr *SecondExpr = SecondSA->getAssertExpr();
9990 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9991 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9992 if (FirstODRHash != SecondODRHash) {
9993 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9994 StaticAssertCondition);
9995 ODRDiagNote(SecondExpr->getLocStart(),
9996 SecondExpr->getSourceRange(), StaticAssertCondition);
9997 Diagnosed = true;
9998 break;
9999 }
10000
10001 StringLiteral *FirstStr = FirstSA->getMessage();
10002 StringLiteral *SecondStr = SecondSA->getMessage();
10003 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10004 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10005 SourceLocation FirstLoc, SecondLoc;
10006 SourceRange FirstRange, SecondRange;
10007 if (FirstStr) {
10008 FirstLoc = FirstStr->getLocStart();
10009 FirstRange = FirstStr->getSourceRange();
10010 } else {
10011 FirstLoc = FirstSA->getLocStart();
10012 FirstRange = FirstSA->getSourceRange();
10013 }
10014 if (SecondStr) {
10015 SecondLoc = SecondStr->getLocStart();
10016 SecondRange = SecondStr->getSourceRange();
10017 } else {
10018 SecondLoc = SecondSA->getLocStart();
10019 SecondRange = SecondSA->getSourceRange();
10020 }
10021 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10022 << (FirstStr == nullptr);
10023 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10024 << (SecondStr == nullptr);
10025 Diagnosed = true;
10026 break;
10027 }
10028
10029 if (FirstStr && SecondStr &&
10030 FirstStr->getString() != SecondStr->getString()) {
10031 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
10032 StaticAssertMessage);
10033 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
10034 StaticAssertMessage);
10035 Diagnosed = true;
10036 break;
10037 }
10038 break;
10039 }
Richard Trieud0786092017-02-23 00:23:01 +000010040 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010041 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10042 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010043 IdentifierInfo *FirstII = FirstField->getIdentifier();
10044 IdentifierInfo *SecondII = SecondField->getIdentifier();
10045 if (FirstII->getName() != SecondII->getName()) {
10046 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10047 FieldName)
10048 << FirstII;
10049 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10050 FieldName)
10051 << SecondII;
10052
10053 Diagnosed = true;
10054 break;
10055 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010056
Richard Smithdbafb6c2017-06-29 23:23:46 +000010057 assert(getContext().hasSameType(FirstField->getType(),
10058 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010059
10060 QualType FirstType = FirstField->getType();
10061 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010062 if (ComputeQualTypeODRHash(FirstType) !=
10063 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010064 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10065 FieldTypeName)
10066 << FirstII << FirstType;
10067 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10068 FieldTypeName)
10069 << SecondII << SecondType;
10070
10071 Diagnosed = true;
10072 break;
10073 }
10074
Richard Trieu93772fc2017-02-24 20:59:28 +000010075 const bool IsFirstBitField = FirstField->isBitField();
10076 const bool IsSecondBitField = SecondField->isBitField();
10077 if (IsFirstBitField != IsSecondBitField) {
10078 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10079 FieldSingleBitField)
10080 << FirstII << IsFirstBitField;
10081 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10082 FieldSingleBitField)
10083 << SecondII << IsSecondBitField;
10084 Diagnosed = true;
10085 break;
10086 }
10087
10088 if (IsFirstBitField && IsSecondBitField) {
10089 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10090 FieldDifferentWidthBitField)
10091 << FirstII << FirstField->getBitWidth()->getSourceRange();
10092 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10093 FieldDifferentWidthBitField)
10094 << SecondII << SecondField->getBitWidth()->getSourceRange();
10095 Diagnosed = true;
10096 break;
10097 }
10098
Richard Trieu8d543e22017-02-24 23:35:37 +000010099 const bool IsFirstMutable = FirstField->isMutable();
10100 const bool IsSecondMutable = SecondField->isMutable();
10101 if (IsFirstMutable != IsSecondMutable) {
10102 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10103 FieldSingleMutable)
10104 << FirstII << IsFirstMutable;
10105 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10106 FieldSingleMutable)
10107 << SecondII << IsSecondMutable;
10108 Diagnosed = true;
10109 break;
10110 }
10111
10112 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10113 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10114 if ((!FirstInitializer && SecondInitializer) ||
10115 (FirstInitializer && !SecondInitializer)) {
10116 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10117 FieldSingleInitializer)
10118 << FirstII << (FirstInitializer != nullptr);
10119 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10120 FieldSingleInitializer)
10121 << SecondII << (SecondInitializer != nullptr);
10122 Diagnosed = true;
10123 break;
10124 }
10125
10126 if (FirstInitializer && SecondInitializer) {
10127 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10128 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10129 if (FirstInitHash != SecondInitHash) {
10130 ODRDiagError(FirstField->getLocation(),
10131 FirstField->getSourceRange(),
10132 FieldDifferentInitializers)
10133 << FirstII << FirstInitializer->getSourceRange();
10134 ODRDiagNote(SecondField->getLocation(),
10135 SecondField->getSourceRange(),
10136 FieldDifferentInitializers)
10137 << SecondII << SecondInitializer->getSourceRange();
10138 Diagnosed = true;
10139 break;
10140 }
10141 }
10142
Richard Trieud0786092017-02-23 00:23:01 +000010143 break;
10144 }
Richard Trieu48143742017-02-28 21:24:38 +000010145 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010146 enum {
10147 DiagMethod,
10148 DiagConstructor,
10149 DiagDestructor,
10150 } FirstMethodType,
10151 SecondMethodType;
10152 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10153 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10154 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10155 return DiagMethod;
10156 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010157 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10158 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010159 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10160 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010161 auto FirstName = FirstMethod->getDeclName();
10162 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010163 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010164 ODRDiagError(FirstMethod->getLocation(),
10165 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010166 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010167 ODRDiagNote(SecondMethod->getLocation(),
10168 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010169 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010170
10171 Diagnosed = true;
10172 break;
10173 }
10174
Richard Trieu583e2c12017-03-04 00:08:58 +000010175 const bool FirstDeleted = FirstMethod->isDeleted();
10176 const bool SecondDeleted = SecondMethod->isDeleted();
10177 if (FirstDeleted != SecondDeleted) {
10178 ODRDiagError(FirstMethod->getLocation(),
10179 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010180 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010181
10182 ODRDiagNote(SecondMethod->getLocation(),
10183 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010184 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010185 Diagnosed = true;
10186 break;
10187 }
10188
10189 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10190 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10191 const bool FirstPure = FirstMethod->isPure();
10192 const bool SecondPure = SecondMethod->isPure();
10193 if ((FirstVirtual || SecondVirtual) &&
10194 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10195 ODRDiagError(FirstMethod->getLocation(),
10196 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010197 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010198 ODRDiagNote(SecondMethod->getLocation(),
10199 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010200 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010201 Diagnosed = true;
10202 break;
10203 }
10204
10205 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10206 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10207 // class needs to be checked instead.
10208 const auto FirstStorage = FirstMethod->getStorageClass();
10209 const auto SecondStorage = SecondMethod->getStorageClass();
10210 const bool FirstStatic = FirstStorage == SC_Static;
10211 const bool SecondStatic = SecondStorage == SC_Static;
10212 if (FirstStatic != SecondStatic) {
10213 ODRDiagError(FirstMethod->getLocation(),
10214 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010215 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010216 ODRDiagNote(SecondMethod->getLocation(),
10217 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010218 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010219 Diagnosed = true;
10220 break;
10221 }
10222
10223 const bool FirstVolatile = FirstMethod->isVolatile();
10224 const bool SecondVolatile = SecondMethod->isVolatile();
10225 if (FirstVolatile != SecondVolatile) {
10226 ODRDiagError(FirstMethod->getLocation(),
10227 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010228 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010229 ODRDiagNote(SecondMethod->getLocation(),
10230 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010231 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010232 Diagnosed = true;
10233 break;
10234 }
10235
10236 const bool FirstConst = FirstMethod->isConst();
10237 const bool SecondConst = SecondMethod->isConst();
10238 if (FirstConst != SecondConst) {
10239 ODRDiagError(FirstMethod->getLocation(),
10240 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010241 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010242 ODRDiagNote(SecondMethod->getLocation(),
10243 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010244 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010245 Diagnosed = true;
10246 break;
10247 }
10248
10249 const bool FirstInline = FirstMethod->isInlineSpecified();
10250 const bool SecondInline = SecondMethod->isInlineSpecified();
10251 if (FirstInline != SecondInline) {
10252 ODRDiagError(FirstMethod->getLocation(),
10253 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010254 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010255 ODRDiagNote(SecondMethod->getLocation(),
10256 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010257 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010258 Diagnosed = true;
10259 break;
10260 }
10261
Richard Trieu02552272017-05-02 23:58:52 +000010262 const unsigned FirstNumParameters = FirstMethod->param_size();
10263 const unsigned SecondNumParameters = SecondMethod->param_size();
10264 if (FirstNumParameters != SecondNumParameters) {
10265 ODRDiagError(FirstMethod->getLocation(),
10266 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010267 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010268 ODRDiagNote(SecondMethod->getLocation(),
10269 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010270 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010271 Diagnosed = true;
10272 break;
10273 }
10274
10275 // Need this status boolean to know when break out of the switch.
10276 bool ParameterMismatch = false;
10277 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10278 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10279 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10280
10281 QualType FirstParamType = FirstParam->getType();
10282 QualType SecondParamType = SecondParam->getType();
10283 if (FirstParamType != SecondParamType &&
10284 ComputeQualTypeODRHash(FirstParamType) !=
10285 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010286 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010287 FirstParamType->getAs<DecayedType>()) {
10288 ODRDiagError(FirstMethod->getLocation(),
10289 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010290 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10291 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010292 } else {
10293 ODRDiagError(FirstMethod->getLocation(),
10294 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010295 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10296 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010297 }
10298
Vedant Kumar48b4f762018-04-14 01:40:48 +000010299 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010300 SecondParamType->getAs<DecayedType>()) {
10301 ODRDiagNote(SecondMethod->getLocation(),
10302 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010303 << SecondMethodType << SecondName << (I + 1)
10304 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010305 << ParamDecayedType->getOriginalType();
10306 } else {
10307 ODRDiagNote(SecondMethod->getLocation(),
10308 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010309 << SecondMethodType << SecondName << (I + 1)
10310 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010311 }
10312 ParameterMismatch = true;
10313 break;
10314 }
10315
10316 DeclarationName FirstParamName = FirstParam->getDeclName();
10317 DeclarationName SecondParamName = SecondParam->getDeclName();
10318 if (FirstParamName != SecondParamName) {
10319 ODRDiagError(FirstMethod->getLocation(),
10320 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010321 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010322 ODRDiagNote(SecondMethod->getLocation(),
10323 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010324 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010325 ParameterMismatch = true;
10326 break;
10327 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010328
10329 const Expr *FirstInit = FirstParam->getInit();
10330 const Expr *SecondInit = SecondParam->getInit();
10331 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10332 ODRDiagError(FirstMethod->getLocation(),
10333 FirstMethod->getSourceRange(),
10334 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010335 << FirstMethodType << FirstName << (I + 1)
10336 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010337 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10338 ODRDiagNote(SecondMethod->getLocation(),
10339 SecondMethod->getSourceRange(),
10340 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010341 << SecondMethodType << SecondName << (I + 1)
10342 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010343 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10344 ParameterMismatch = true;
10345 break;
10346 }
10347
10348 if (FirstInit && SecondInit &&
10349 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10350 ODRDiagError(FirstMethod->getLocation(),
10351 FirstMethod->getSourceRange(),
10352 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010353 << FirstMethodType << FirstName << (I + 1)
10354 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010355 ODRDiagNote(SecondMethod->getLocation(),
10356 SecondMethod->getSourceRange(),
10357 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010358 << SecondMethodType << SecondName << (I + 1)
10359 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010360 ParameterMismatch = true;
10361 break;
10362
10363 }
Richard Trieu02552272017-05-02 23:58:52 +000010364 }
10365
10366 if (ParameterMismatch) {
10367 Diagnosed = true;
10368 break;
10369 }
10370
Richard Trieu48143742017-02-28 21:24:38 +000010371 break;
10372 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010373 case TypeAlias:
10374 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010375 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10376 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010377 auto FirstName = FirstTD->getDeclName();
10378 auto SecondName = SecondTD->getDeclName();
10379 if (FirstName != SecondName) {
10380 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10381 TypedefName)
10382 << (FirstDiffType == TypeAlias) << FirstName;
10383 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10384 TypedefName)
10385 << (FirstDiffType == TypeAlias) << SecondName;
10386 Diagnosed = true;
10387 break;
10388 }
10389
10390 QualType FirstType = FirstTD->getUnderlyingType();
10391 QualType SecondType = SecondTD->getUnderlyingType();
10392 if (ComputeQualTypeODRHash(FirstType) !=
10393 ComputeQualTypeODRHash(SecondType)) {
10394 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10395 TypedefType)
10396 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10397 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10398 TypedefType)
10399 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10400 Diagnosed = true;
10401 break;
10402 }
10403 break;
10404 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010405 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010406 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10407 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010408 auto FirstName = FirstVD->getDeclName();
10409 auto SecondName = SecondVD->getDeclName();
10410 if (FirstName != SecondName) {
10411 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10412 VarName)
10413 << FirstName;
10414 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10415 VarName)
10416 << SecondName;
10417 Diagnosed = true;
10418 break;
10419 }
10420
10421 QualType FirstType = FirstVD->getType();
10422 QualType SecondType = SecondVD->getType();
10423 if (ComputeQualTypeODRHash(FirstType) !=
10424 ComputeQualTypeODRHash(SecondType)) {
10425 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10426 VarType)
10427 << FirstName << FirstType;
10428 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10429 VarType)
10430 << SecondName << SecondType;
10431 Diagnosed = true;
10432 break;
10433 }
10434
10435 const Expr *FirstInit = FirstVD->getInit();
10436 const Expr *SecondInit = SecondVD->getInit();
10437 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10438 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10439 VarSingleInitializer)
10440 << FirstName << (FirstInit == nullptr)
10441 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10442 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10443 VarSingleInitializer)
10444 << SecondName << (SecondInit == nullptr)
10445 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10446 Diagnosed = true;
10447 break;
10448 }
10449
10450 if (FirstInit && SecondInit &&
10451 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10452 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10453 VarDifferentInitializer)
10454 << FirstName << FirstInit->getSourceRange();
10455 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10456 VarDifferentInitializer)
10457 << SecondName << SecondInit->getSourceRange();
10458 Diagnosed = true;
10459 break;
10460 }
10461
10462 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10463 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10464 if (FirstIsConstexpr != SecondIsConstexpr) {
10465 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10466 VarConstexpr)
10467 << FirstName << FirstIsConstexpr;
10468 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10469 VarConstexpr)
10470 << SecondName << SecondIsConstexpr;
10471 Diagnosed = true;
10472 break;
10473 }
10474 break;
10475 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010476 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010477 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10478 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010479
10480 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10481 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10482
10483 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10484 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10485
10486 if (FirstND && SecondND) {
10487 ODRDiagError(FirstFriend->getFriendLoc(),
10488 FirstFriend->getSourceRange(), FriendFunction)
10489 << FirstND;
10490 ODRDiagNote(SecondFriend->getFriendLoc(),
10491 SecondFriend->getSourceRange(), FriendFunction)
10492 << SecondND;
10493
10494 Diagnosed = true;
10495 break;
10496 }
10497
10498 if (FirstTSI && SecondTSI) {
10499 QualType FirstFriendType = FirstTSI->getType();
10500 QualType SecondFriendType = SecondTSI->getType();
10501 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10502 ComputeQualTypeODRHash(SecondFriendType));
10503 ODRDiagError(FirstFriend->getFriendLoc(),
10504 FirstFriend->getSourceRange(), FriendType)
10505 << FirstFriendType;
10506 ODRDiagNote(SecondFriend->getFriendLoc(),
10507 SecondFriend->getSourceRange(), FriendType)
10508 << SecondFriendType;
10509 Diagnosed = true;
10510 break;
10511 }
10512
10513 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10514 FriendTypeFunction)
10515 << (FirstTSI == nullptr);
10516 ODRDiagNote(SecondFriend->getFriendLoc(),
10517 SecondFriend->getSourceRange(), FriendTypeFunction)
10518 << (SecondTSI == nullptr);
10519
10520 Diagnosed = true;
10521 break;
10522 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010523 }
10524
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010525 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010526 continue;
10527
Richard Trieu708859a2017-06-08 00:56:21 +000010528 Diag(FirstDecl->getLocation(),
10529 diag::err_module_odr_violation_mismatch_decl_unknown)
10530 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10531 << FirstDecl->getSourceRange();
10532 Diag(SecondDecl->getLocation(),
10533 diag::note_module_odr_violation_mismatch_decl_unknown)
10534 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010535 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010536 }
10537
10538 if (!Diagnosed) {
10539 // All definitions are updates to the same declaration. This happens if a
10540 // module instantiates the declaration of a class template specialization
10541 // and two or more other modules instantiate its definition.
10542 //
10543 // FIXME: Indicate which modules had instantiations of this definition.
10544 // FIXME: How can this even happen?
10545 Diag(Merge.first->getLocation(),
10546 diag::err_module_odr_violation_different_instantiations)
10547 << Merge.first;
10548 }
10549 }
Richard Trieue6caa262017-12-23 00:41:01 +000010550
10551 // Issue ODR failures diagnostics for functions.
10552 for (auto &Merge : FunctionOdrMergeFailures) {
10553 enum ODRFunctionDifference {
10554 ReturnType,
10555 ParameterName,
10556 ParameterType,
10557 ParameterSingleDefaultArgument,
10558 ParameterDifferentDefaultArgument,
10559 FunctionBody,
10560 };
10561
10562 FunctionDecl *FirstFunction = Merge.first;
10563 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
10564
10565 bool Diagnosed = false;
10566 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010567
Richard Trieue6caa262017-12-23 00:41:01 +000010568 if (FirstFunction == SecondFunction)
10569 continue;
10570
10571 std::string SecondModule =
10572 getOwningModuleNameForDiagnostic(SecondFunction);
10573
10574 auto ODRDiagError = [FirstFunction, &FirstModule,
10575 this](SourceLocation Loc, SourceRange Range,
10576 ODRFunctionDifference DiffType) {
10577 return Diag(Loc, diag::err_module_odr_violation_function)
10578 << FirstFunction << FirstModule.empty() << FirstModule << Range
10579 << DiffType;
10580 };
10581 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
10582 SourceRange Range,
10583 ODRFunctionDifference DiffType) {
10584 return Diag(Loc, diag::note_module_odr_violation_function)
10585 << SecondModule << Range << DiffType;
10586 };
10587
10588 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
10589 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
10590 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
10591 FirstFunction->getReturnTypeSourceRange(), ReturnType)
10592 << FirstFunction->getReturnType();
10593 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
10594 SecondFunction->getReturnTypeSourceRange(), ReturnType)
10595 << SecondFunction->getReturnType();
10596 Diagnosed = true;
10597 break;
10598 }
10599
10600 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
10601 "Merged functions with different number of parameters");
10602
10603 auto ParamSize = FirstFunction->param_size();
10604 bool ParameterMismatch = false;
10605 for (unsigned I = 0; I < ParamSize; ++I) {
10606 auto *FirstParam = FirstFunction->getParamDecl(I);
10607 auto *SecondParam = SecondFunction->getParamDecl(I);
10608
10609 assert(getContext().hasSameType(FirstParam->getType(),
10610 SecondParam->getType()) &&
10611 "Merged function has different parameter types.");
10612
10613 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
10614 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10615 ParameterName)
10616 << I + 1 << FirstParam->getDeclName();
10617 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10618 ParameterName)
10619 << I + 1 << SecondParam->getDeclName();
10620 ParameterMismatch = true;
10621 break;
10622 };
10623
10624 QualType FirstParamType = FirstParam->getType();
10625 QualType SecondParamType = SecondParam->getType();
10626 if (FirstParamType != SecondParamType &&
10627 ComputeQualTypeODRHash(FirstParamType) !=
10628 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010629 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000010630 FirstParamType->getAs<DecayedType>()) {
10631 ODRDiagError(FirstParam->getLocation(),
10632 FirstParam->getSourceRange(), ParameterType)
10633 << (I + 1) << FirstParamType << true
10634 << ParamDecayedType->getOriginalType();
10635 } else {
10636 ODRDiagError(FirstParam->getLocation(),
10637 FirstParam->getSourceRange(), ParameterType)
10638 << (I + 1) << FirstParamType << false;
10639 }
10640
Vedant Kumar48b4f762018-04-14 01:40:48 +000010641 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000010642 SecondParamType->getAs<DecayedType>()) {
10643 ODRDiagNote(SecondParam->getLocation(),
10644 SecondParam->getSourceRange(), ParameterType)
10645 << (I + 1) << SecondParamType << true
10646 << ParamDecayedType->getOriginalType();
10647 } else {
10648 ODRDiagNote(SecondParam->getLocation(),
10649 SecondParam->getSourceRange(), ParameterType)
10650 << (I + 1) << SecondParamType << false;
10651 }
10652 ParameterMismatch = true;
10653 break;
10654 }
10655
10656 const Expr *FirstInit = FirstParam->getInit();
10657 const Expr *SecondInit = SecondParam->getInit();
10658 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10659 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10660 ParameterSingleDefaultArgument)
10661 << (I + 1) << (FirstInit == nullptr)
10662 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10663 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10664 ParameterSingleDefaultArgument)
10665 << (I + 1) << (SecondInit == nullptr)
10666 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10667 ParameterMismatch = true;
10668 break;
10669 }
10670
10671 if (FirstInit && SecondInit &&
10672 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10673 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10674 ParameterDifferentDefaultArgument)
10675 << (I + 1) << FirstInit->getSourceRange();
10676 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10677 ParameterDifferentDefaultArgument)
10678 << (I + 1) << SecondInit->getSourceRange();
10679 ParameterMismatch = true;
10680 break;
10681 }
10682
10683 assert(ComputeSubDeclODRHash(FirstParam) ==
10684 ComputeSubDeclODRHash(SecondParam) &&
10685 "Undiagnosed parameter difference.");
10686 }
10687
10688 if (ParameterMismatch) {
10689 Diagnosed = true;
10690 break;
10691 }
10692
10693 // If no error has been generated before now, assume the problem is in
10694 // the body and generate a message.
10695 ODRDiagError(FirstFunction->getLocation(),
10696 FirstFunction->getSourceRange(), FunctionBody);
10697 ODRDiagNote(SecondFunction->getLocation(),
10698 SecondFunction->getSourceRange(), FunctionBody);
10699 Diagnosed = true;
10700 break;
10701 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000010702 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000010703 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10704 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010705}
10706
Richard Smithce18a182015-07-14 00:26:00 +000010707void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010708 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000010709 ReadTimer->startTimer();
10710}
10711
Guy Benyei11169dd2012-12-18 14:30:41 +000010712void ASTReader::FinishedDeserializing() {
10713 assert(NumCurrentElementsDeserializing &&
10714 "FinishedDeserializing not paired with StartedDeserializing");
10715 if (NumCurrentElementsDeserializing == 1) {
10716 // We decrease NumCurrentElementsDeserializing only after pending actions
10717 // are finished, to avoid recursively re-calling finishPendingActions().
10718 finishPendingActions();
10719 }
10720 --NumCurrentElementsDeserializing;
10721
Richard Smitha0ce9c42014-07-29 23:23:27 +000010722 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010723 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000010724 while (!PendingExceptionSpecUpdates.empty()) {
10725 auto Updates = std::move(PendingExceptionSpecUpdates);
10726 PendingExceptionSpecUpdates.clear();
10727 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000010728 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000010729 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000010730 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000010731 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000010732 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000010733 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000010734 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000010735 }
Richard Smith9e2341d2015-03-23 03:25:59 +000010736 }
10737
Richard Smithce18a182015-07-14 00:26:00 +000010738 if (ReadTimer)
10739 ReadTimer->stopTimer();
10740
Richard Smith0f4e2c42015-08-06 04:23:48 +000010741 diagnoseOdrViolations();
10742
Richard Smith04d05b52014-03-23 00:27:18 +000010743 // We are not in recursive loading, so it's safe to pass the "interesting"
10744 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010745 if (Consumer)
10746 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000010747 }
10748}
10749
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010750void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010751 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10752 // Remove any fake results before adding any real ones.
10753 auto It = PendingFakeLookupResults.find(II);
10754 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000010755 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000010756 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000010757 // FIXME: this works around module+PCH performance issue.
10758 // Rather than erase the result from the map, which is O(n), just clear
10759 // the vector of NamedDecls.
10760 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000010761 }
10762 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010763
10764 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10765 SemaObj->TUScope->AddDecl(D);
10766 } else if (SemaObj->TUScope) {
10767 // Adding the decl to IdResolver may have failed because it was already in
10768 // (even though it was not added in scope). If it is already in, make sure
10769 // it gets in the scope as well.
10770 if (std::find(SemaObj->IdResolver.begin(Name),
10771 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10772 SemaObj->TUScope->AddDecl(D);
10773 }
10774}
10775
Richard Smithdbafb6c2017-06-29 23:23:46 +000010776ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000010777 const PCHContainerReader &PCHContainerRdr,
10778 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10779 StringRef isysroot, bool DisableValidation,
10780 bool AllowASTWithCompilerErrors,
10781 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10782 bool UseGlobalIndex,
10783 std::unique_ptr<llvm::Timer> ReadTimer)
10784 : Listener(DisableValidation
10785 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10786 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000010787 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010788 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000010789 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000010790 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
10791 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000010792 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10793 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000010794 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000010795 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10796 AllowConfigurationMismatch(AllowConfigurationMismatch),
10797 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010798 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000010799 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010800
10801 for (const auto &Ext : Extensions) {
10802 auto BlockName = Ext->getExtensionMetadata().BlockName;
10803 auto Known = ModuleFileExtensions.find(BlockName);
10804 if (Known != ModuleFileExtensions.end()) {
10805 Diags.Report(diag::warn_duplicate_module_file_extension)
10806 << BlockName;
10807 continue;
10808 }
10809
10810 ModuleFileExtensions.insert({BlockName, Ext});
10811 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010812}
10813
10814ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000010815 if (OwnsDeserializationListener)
10816 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000010817}
Richard Smith10379092016-05-06 23:14:07 +000010818
10819IdentifierResolver &ASTReader::getIdResolver() {
10820 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10821}
David L. Jonesbe1557a2016-12-21 00:17:49 +000010822
10823unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10824 unsigned AbbrevID) {
10825 Idx = 0;
10826 Record.clear();
10827 return Cursor.readRecord(AbbrevID, Record);
10828}